blob: 2c6b20896b98d36fc012ca48dbc7c647b538fd95 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Pier Ventre229fd0b2016-10-31 16:49:19 -070018import com.google.common.collect.Lists;
Charles Chan051490d2018-01-11 11:48:18 -080019import com.google.common.collect.Sets;
Saurav Das4c35fc42015-11-20 15:27:53 -080020import org.onlab.packet.EthType;
sangho80f11cb2015-04-01 13:05:26 -070021import org.onlab.packet.Ethernet;
Charles Chanef8d12e2017-12-05 21:07:38 -080022import org.onlab.packet.IPv6;
sangho80f11cb2015-04-01 13:05:26 -070023import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080024import org.onlab.packet.Ip6Address;
25import org.onlab.packet.IpAddress;
sangho80f11cb2015-04-01 13:05:26 -070026import org.onlab.packet.IpPrefix;
27import org.onlab.packet.MacAddress;
sangho80f11cb2015-04-01 13:05:26 -070028import org.onlab.packet.MplsLabel;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070029import org.onlab.packet.VlanId;
Charles Chanb7f75ac2016-01-11 18:28:54 -080030import org.onosproject.net.ConnectPoint;
Saurav Das9bf49582018-08-13 15:34:26 -070031import org.onosproject.net.Device;
Charles Chan1eaf4802016-04-18 13:44:03 -070032import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080033import org.onosproject.net.flowobjective.Objective;
Charles Chan1eaf4802016-04-18 13:44:03 -070034import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080035import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -070036import org.onosproject.net.intf.Interface;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080037import org.onosproject.net.packet.PacketPriority;
Charles Chan319d1a22015-11-03 10:42:14 -080038import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
39import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070040import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070041import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sangho80f11cb2015-04-01 13:05:26 -070042import org.onosproject.net.DeviceId;
Saurav Das7c305372015-10-28 12:39:42 -070043import org.onosproject.net.Port;
sangho80f11cb2015-04-01 13:05:26 -070044import org.onosproject.net.PortNumber;
sangho80f11cb2015-04-01 13:05:26 -070045import org.onosproject.net.flow.DefaultTrafficSelector;
46import org.onosproject.net.flow.DefaultTrafficTreatment;
sangho80f11cb2015-04-01 13:05:26 -070047import org.onosproject.net.flow.TrafficSelector;
48import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070049import org.onosproject.net.flow.criteria.Criteria;
50import org.onosproject.net.flowobjective.DefaultFilteringObjective;
51import org.onosproject.net.flowobjective.DefaultForwardingObjective;
52import org.onosproject.net.flowobjective.FilteringObjective;
53import org.onosproject.net.flowobjective.ForwardingObjective;
54import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
Saurav Das9f1c42e2015-10-23 10:51:11 -070055import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070056import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
sangho80f11cb2015-04-01 13:05:26 -070057import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
60import java.util.ArrayList;
Pier Ventre229fd0b2016-10-31 16:49:19 -070061import java.util.Collection;
62import java.util.Collections;
Saurav Das261c3002017-06-13 15:35:54 -070063import java.util.HashMap;
Saurav Dasc28b3432015-10-30 17:45:38 -070064import java.util.HashSet;
sangho80f11cb2015-04-01 13:05:26 -070065import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070066import java.util.Map;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080067import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070068import java.util.Set;
sanghofb7c7292015-04-13 15:15:58 -070069import java.util.concurrent.atomic.AtomicLong;
Charles Chanf17f66b2018-02-26 21:33:25 -080070import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -070071
72import static com.google.common.base.Preconditions.checkNotNull;
Pier Luigib9632ba2017-01-12 18:14:58 -080073import static org.onlab.packet.Ethernet.TYPE_ARP;
74import static org.onlab.packet.Ethernet.TYPE_IPV6;
Charles Chan051490d2018-01-11 11:48:18 -080075import static org.onlab.packet.ICMP6.NEIGHBOR_ADVERTISEMENT;
Pier Luigib9632ba2017-01-12 18:14:58 -080076import static org.onlab.packet.ICMP6.NEIGHBOR_SOLICITATION;
Charles Chan051490d2018-01-11 11:48:18 -080077import static org.onlab.packet.ICMP6.ROUTER_ADVERTISEMENT;
78import static org.onlab.packet.ICMP6.ROUTER_SOLICITATION;
Pier Luigib9632ba2017-01-12 18:14:58 -080079import static org.onlab.packet.IPv6.PROTOCOL_ICMP6;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070080import static org.onosproject.segmentrouting.SegmentRoutingService.DEFAULT_PRIORITY;
sangho80f11cb2015-04-01 13:05:26 -070081
Charles Chanb7f75ac2016-01-11 18:28:54 -080082/**
83 * Populator of segment routing flow rules.
84 */
sangho80f11cb2015-04-01 13:05:26 -070085public class RoutingRulePopulator {
Charles Chanef8d12e2017-12-05 21:07:38 -080086 private static final Logger log = LoggerFactory.getLogger(RoutingRulePopulator.class);
87
88 private static final int ARP_NDP_PRIORITY = 30000;
sangho80f11cb2015-04-01 13:05:26 -070089
sanghofb7c7292015-04-13 15:15:58 -070090 private AtomicLong rulePopulationCounter;
sangho9b169e32015-04-14 16:27:13 -070091 private SegmentRoutingManager srManager;
92 private DeviceConfiguration config;
psneha86e60d32019-03-26 06:31:41 -040093 private RouteSimplifierUtils routeSimplifierUtils;
Saurav Das9f1c42e2015-10-23 10:51:11 -070094
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -070095 // used for signalling the driver to remove vlan table and tmac entry also
96 private static final long CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES = 1;
97 private static final long DOUBLE_TAGGED_METADATA_MASK = 0xffffffffffffffffL;
98
sangho80f11cb2015-04-01 13:05:26 -070099 /**
100 * Creates a RoutingRulePopulator object.
101 *
Thomas Vachuska8a075092015-04-15 18:20:08 -0700102 * @param srManager segment routing manager reference
sangho80f11cb2015-04-01 13:05:26 -0700103 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700104 RoutingRulePopulator(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700105 this.srManager = srManager;
sangho9b169e32015-04-14 16:27:13 -0700106 this.config = checkNotNull(srManager.deviceConfiguration);
sanghofb7c7292015-04-13 15:15:58 -0700107 this.rulePopulationCounter = new AtomicLong(0);
psneha86e60d32019-03-26 06:31:41 -0400108 this.routeSimplifierUtils = new RouteSimplifierUtils(srManager);
sanghofb7c7292015-04-13 15:15:58 -0700109 }
110
111 /**
112 * Resets the population counter.
113 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700114 void resetCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700115 rulePopulationCounter.set(0);
116 }
117
118 /**
119 * Returns the number of rules populated.
Thomas Vachuska7cfc6202015-04-30 18:13:25 -0700120 *
121 * @return number of rules
sanghofb7c7292015-04-13 15:15:58 -0700122 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700123 long getCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700124 return rulePopulationCounter.get();
sangho80f11cb2015-04-01 13:05:26 -0700125 }
126
127 /**
Charles Chand66d6712018-03-29 16:03:41 -0700128 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
129 * output to given port.
130 *
131 * @param deviceId device ID
132 * @param port port
133 * @param mac mac address
134 * @param vlanId VLAN ID
135 */
136 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
137 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
138 if (fob == null) {
139 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
140 return;
141 }
142
143 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700144 (objective) -> log.debug("Brigding rule for {}/{} populated", mac, vlanId),
145 (objective, error) -> log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700146 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
147 }
148
149 /**
150 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
151 * output to given port.
152 *
153 * @param deviceId device ID
154 * @param port port
155 * @param mac mac address
156 * @param vlanId VLAN ID
157 */
158 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
159 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
160 if (fob == null) {
161 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
162 return;
163 }
164
165 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700166 (objective) -> log.debug("Brigding rule for {}/{} revoked", mac, vlanId),
167 (objective, error) -> log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700168 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
169 }
170
171 /**
172 * Generates a forwarding objective builder for bridging rules.
173 * <p>
174 * The forwarding objective bridges packets destined to a given MAC to
175 * given port on given device.
176 *
177 * @param deviceId Device that host attaches to
178 * @param mac MAC address of the host
179 * @param hostVlanId VLAN ID of the host
180 * @param outport Port that host attaches to
181 * @param revoke true if forwarding objective is meant to revoke forwarding rule
182 * @return Forwarding objective builder
183 */
184 private ForwardingObjective.Builder bridgingFwdObjBuilder(
185 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
186 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan098ca202018-05-01 11:50:20 -0700187 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
188 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
189 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chand66d6712018-03-29 16:03:41 -0700190
191 // Create host selector
192 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
193 sbuilder.matchEthDst(mac);
194
195 // Create host treatment
196 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
197 tbuilder.immediate().setOutput(outport);
198
199 // Create host meta
200 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
201
202 // Adjust the selector, treatment and meta according to VLAN configuration
203 if (taggedVlans.contains(hostVlanId)) {
204 sbuilder.matchVlanId(hostVlanId);
205 mbuilder.matchVlanId(hostVlanId);
206 } else if (hostVlanId.equals(VlanId.NONE)) {
207 if (untaggedVlan != null) {
208 sbuilder.matchVlanId(untaggedVlan);
209 mbuilder.matchVlanId(untaggedVlan);
210 tbuilder.immediate().popVlan();
211 } else if (nativeVlan != null) {
212 sbuilder.matchVlanId(nativeVlan);
213 mbuilder.matchVlanId(nativeVlan);
214 tbuilder.immediate().popVlan();
215 } else {
216 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
217 "vlan config", mac, hostVlanId, connectPoint);
218 return null;
219 }
220 } else {
221 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
222 mac, hostVlanId, connectPoint);
223 return null;
224 }
225
226 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
227 // If the objective is to revoke an existing rule, and for some reason
228 // the next-objective does not exist, then a new one should not be created
229 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
230 tbuilder.build(), mbuilder.build(), !revoke);
231 if (portNextObjId == -1) {
232 // Warning log will come from getPortNextObjective method
233 return null;
234 }
235
236 return DefaultForwardingObjective.builder()
237 .withFlag(ForwardingObjective.Flag.SPECIFIC)
238 .withSelector(sbuilder.build())
239 .nextStep(portNextObjId)
240 .withPriority(100)
241 .fromApp(srManager.appId)
242 .makePermanent();
243 }
244
245 /**
246 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
247 * and hostMAC connected to given port, and output to given port only when
248 * vlan information is valid.
249 *
250 * @param deviceId device ID that host attaches to
251 * @param portNum port number that host attaches to
252 * @param hostMac mac address of the host connected to the switch port
253 * @param vlanId Vlan ID configured on the switch port
254 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
255 * @param install true to populate the objective, false to revoke
256 */
257 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
258 // revokeBridging and bridgingFwdObjBuilder.
259 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
260 VlanId vlanId, boolean popVlan, boolean install) {
261 // Create host selector
262 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
263 sbuilder.matchEthDst(hostMac);
264
265 // Create host meta
266 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
267
268 sbuilder.matchVlanId(vlanId);
269 mbuilder.matchVlanId(vlanId);
270
271 // Create host treatment
272 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
273 tbuilder.immediate().setOutput(portNum);
274
275 if (popVlan) {
276 tbuilder.immediate().popVlan();
277 }
278
279 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
280 tbuilder.build(), mbuilder.build(), install);
281 if (portNextObjId != -1) {
282 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
283 .withFlag(ForwardingObjective.Flag.SPECIFIC)
284 .withSelector(sbuilder.build())
285 .nextStep(portNextObjId)
286 .withPriority(100)
287 .fromApp(srManager.appId)
288 .makePermanent();
289
290 ObjectiveContext context = new DefaultObjectiveContext(
291 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
292 install ? "populated" : "revoked"),
293 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
294 install ? "populate" : "revoke", hostMac, vlanId, error));
295 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
296 } else {
297 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
298 }
299 }
300
301 /**
302 * Populates IP rules for a route that has direct connection to the switch.
303 * This method should not be invoked directly without going through DefaultRoutingHandler.
sangho80f11cb2015-04-01 13:05:26 -0700304 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700305 * @param deviceId device ID of the device that next hop attaches to
306 * @param prefix IP prefix of the route
307 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800308 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700309 * @param outPort port where the next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000310 * @param directHost host is of type direct or indirect
sangho80f11cb2015-04-01 13:05:26 -0700311 */
Charles Chan910be6a2017-08-23 14:46:43 -0700312 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000313 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Saurav Das261c3002017-06-13 15:35:54 -0700314 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chanddac7fd2016-10-27 14:19:48 -0700315 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800316 ForwardingObjective.Builder fwdBuilder;
Charles Chan319d1a22015-11-03 10:42:14 -0800317 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700318 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000319 hostVlanId, outPort, directHost, false);
Charles Chan319d1a22015-11-03 10:42:14 -0800320 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -0700321 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan319d1a22015-11-03 10:42:14 -0800322 return;
323 }
Saurav Das07c74602016-04-27 18:35:50 -0700324 if (fwdBuilder == null) {
Saurav Das368cf212017-03-15 15:15:14 -0700325 log.warn("Aborting host routing table entry due "
Charles Chanddac7fd2016-10-27 14:19:48 -0700326 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das07c74602016-04-27 18:35:50 -0700327 return;
328 }
Charles Chan910be6a2017-08-23 14:46:43 -0700329
330 int nextId = fwdBuilder.add().nextId();
Charles Chan1eaf4802016-04-18 13:44:03 -0700331 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan910be6a2017-08-23 14:46:43 -0700332 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
333 prefix, nextId),
Charles Chan1eaf4802016-04-18 13:44:03 -0700334 (objective, error) ->
Saurav Das261c3002017-06-13 15:35:54 -0700335 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das368cf212017-03-15 15:15:14 -0700336 prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700337 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chanf4586112015-11-09 16:37:23 -0800338 rulePopulationCounter.incrementAndGet();
339 }
340
Charles Chanb7f75ac2016-01-11 18:28:54 -0800341 /**
Charles Chanddac7fd2016-10-27 14:19:48 -0700342 * Removes IP rules for a route when the next hop is gone.
Charles Chand66d6712018-03-29 16:03:41 -0700343 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800344 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700345 * @param deviceId device ID of the device that next hop attaches to
346 * @param prefix IP prefix of the route
347 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800348 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700349 * @param outPort port that next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000350 * @param directHost host is of type direct or indirect
Charles Chanb7f75ac2016-01-11 18:28:54 -0800351 */
Charles Chan910be6a2017-08-23 14:46:43 -0700352 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000353 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chanddac7fd2016-10-27 14:19:48 -0700354 log.debug("Revoke IP table entry for route {} at {}:{}",
355 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800356 ForwardingObjective.Builder fwdBuilder;
357 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700358 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000359 hostVlanId, outPort, directHost, true);
Charles Chanf4586112015-11-09 16:37:23 -0800360 } catch (DeviceConfigNotFoundException e) {
361 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
362 return;
363 }
Charles Chanea702b12016-11-30 11:55:05 -0800364 if (fwdBuilder == null) {
365 log.warn("Aborting host routing table entries due "
366 + "to error for dev:{} route:{}", deviceId, prefix);
367 return;
368 }
Charles Chan1eaf4802016-04-18 13:44:03 -0700369 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chanddac7fd2016-10-27 14:19:48 -0700370 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chan1eaf4802016-04-18 13:44:03 -0700371 (objective, error) ->
Charles Chanddac7fd2016-10-27 14:19:48 -0700372 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700373 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chanf4586112015-11-09 16:37:23 -0800374 }
375
Charles Chanddac7fd2016-10-27 14:19:48 -0700376 /**
Charles Chan18fa4252017-02-08 16:10:40 -0800377 * Returns a forwarding objective builder for routing rules.
378 * <p>
379 * The forwarding objective routes packets destined to a given prefix to
380 * given port on given device with given destination MAC.
Charles Chanddac7fd2016-10-27 14:19:48 -0700381 *
382 * @param deviceId device ID
383 * @param prefix prefix that need to be routed
384 * @param hostMac MAC address of the nexthop
Charles Chan90772a72017-02-08 15:52:08 -0800385 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700386 * @param outPort port where the nexthop attaches to
Saurav Das2cb38292017-03-29 19:09:17 -0700387 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000388 * @param directHost host is direct or indirect
Charles Chanddac7fd2016-10-27 14:19:48 -0700389 * @return forwarding objective builder
390 * @throws DeviceConfigNotFoundException if given device is not configured
391 */
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000392
393 private ForwardingObjective.Builder
394
395
396 routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700397 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700398 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000399 boolean directHost, boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800400 throws DeviceConfigNotFoundException {
401 MacAddress deviceMac;
402 deviceMac = config.getDeviceMac(deviceId);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000403 int nextObjId = -1;
Charles Chan319d1a22015-11-03 10:42:14 -0800404
Charles Chan90772a72017-02-08 15:52:08 -0800405 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700406 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
407 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
408 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700409
Charles Chan90772a72017-02-08 15:52:08 -0800410 // Create route selector
411 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
412
413 // Create route treatment
Charles Chanddac7fd2016-10-27 14:19:48 -0700414 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho27462c62015-05-14 00:39:53 -0700415 tbuilder.deferred()
416 .setEthDst(hostMac)
Charles Chan319d1a22015-11-03 10:42:14 -0800417 .setEthSrc(deviceMac)
sangho80f11cb2015-04-01 13:05:26 -0700418 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800419
Charles Chan90772a72017-02-08 15:52:08 -0800420 // Create route meta
421 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800422
Charles Chan90772a72017-02-08 15:52:08 -0800423 // Adjust the meta according to VLAN configuration
424 if (taggedVlans.contains(hostVlanId)) {
425 tbuilder.setVlanId(hostVlanId);
426 } else if (hostVlanId.equals(VlanId.NONE)) {
427 if (untaggedVlan != null) {
428 mbuilder.matchVlanId(untaggedVlan);
429 } else if (nativeVlan != null) {
430 mbuilder.matchVlanId(nativeVlan);
431 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700432 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
433 hostMac, hostVlanId, connectPoint);
434 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800435 }
436 } else {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700437 // Internally-assigned dummy VLAN id will be given as hostVlanId
438 // when destination is double-tagged.
439 VlanId vlanId = srManager.dummyVlanIdStore().get(
440 new DummyVlanIdStoreKey(connectPoint, prefix.address()));
441 if (vlanId != null && vlanId.equals(hostVlanId)) {
442 tbuilder.setVlanId(hostVlanId);
443 mbuilder.matchVlanId(VlanId.ANY);
444 } else {
445 log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
446 + " in tagged vlan", hostMac, hostVlanId, connectPoint);
447 return null;
448 }
Saurav Das07c74602016-04-27 18:35:50 -0700449 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000450
451 if (directHost) {
452 // if the objective is to revoke an existing rule, and for some reason
453 // the next-objective does not exist, then a new one should not be created
454 nextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
Saurav Das2cb38292017-03-29 19:09:17 -0700455 tbuilder.build(), mbuilder.build(), !revoke);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000456 } else {
457 // if the objective is to revoke an existing rule, and for some reason
458 // the next-objective does not exist, then a new one should not be created
459 nextObjId = srManager.getMacVlanNextObjectiveId(deviceId, hostMac, hostVlanId,
Ruchi Sahota07869322019-05-09 17:26:14 -0400460 outPort, !revoke);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000461 }
462 if (nextObjId == -1) {
463 // Warning log will come from getMacVlanNextObjective method
Charles Chan90772a72017-02-08 15:52:08 -0800464 return null;
465 }
466
Charles Chanf4586112015-11-09 16:37:23 -0800467 return DefaultForwardingObjective.builder()
Charles Chan90772a72017-02-08 15:52:08 -0800468 .withSelector(sbuilder.build())
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000469 .nextStep(nextObjId)
Charles Chanf4586112015-11-09 16:37:23 -0800470 .fromApp(srManager.appId).makePermanent()
Charles Chanddac7fd2016-10-27 14:19:48 -0700471 .withPriority(getPriorityFromPrefix(prefix))
Charles Chan82ab1932016-01-30 23:22:37 -0800472 .withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700473 }
474
475 /**
Saurav Das261c3002017-06-13 15:35:54 -0700476 * Populates IP flow rules for all the given prefixes reachable from the
477 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700478 *
Saurav Das261c3002017-06-13 15:35:54 -0700479 * @param targetSw switch where rules are to be programmed
480 * @param subnets subnets/prefixes being added
481 * @param destSw1 destination switch where the prefixes are reachable
482 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
483 * Should be null if there is no paired destination switch (by config)
484 * or if the given prefixes are reachable only via destSw1
485 * @param nextHops a map containing a set of next-hops for each destination switch.
486 * If destSw2 is not null, then this map must contain an
487 * entry for destSw2 with its next-hops from the targetSw
488 * (although the next-hop set may be empty in certain scenarios).
489 * If destSw2 is null, there should not be an entry in this
490 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700491 * @return true if all rules are set successfully, false otherwise
492 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700493 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700494 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
psneha86e60d32019-03-26 06:31:41 -0400495 // Get pair device of the target switch
496 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
497 // Route simplification will be off in case of the nexthop location at target switch is down
498 // (routing through spine case)
499 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
500 // Iterates over the routes
501 // If route simplification is enabled
502 // If the target device is another leaf in the network
503 if (srManager.routeSimplification && !routeSimplOff) {
504 for (IpPrefix subnet : subnets) {
505 // Skip route programming on the target device
506 // If route simplification applies
507 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
508 // XXX route simplification assumes that source of the traffic
509 // towards the nexthops are co-located with the nexthops. In different
510 // scenarios will not work properly.
511 continue;
512 }
513 // populate the route in the remaning scenarios
514 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
515 return false;
516 }
517 }
518 } else {
519 // Populate IP flow rules for all the subnets.
520 for (IpPrefix subnet : subnets) {
521 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
522 return false;
523 }
sangho80f11cb2015-04-01 13:05:26 -0700524 }
525 }
Charles Chanc22cef32016-04-29 14:38:22 -0700526 return true;
527 }
sangho80f11cb2015-04-01 13:05:26 -0700528
Charles Chanc22cef32016-04-29 14:38:22 -0700529 /**
Charles Chand66d6712018-03-29 16:03:41 -0700530 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700531 *
Charles Chand66d6712018-03-29 16:03:41 -0700532 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700533 * @param subnets subnet being removed
534 * @return true if all rules are removed successfully, false otherwise
535 */
Charles Chand66d6712018-03-29 16:03:41 -0700536 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700537 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700538 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700539 return false;
540 }
541 }
sangho80f11cb2015-04-01 13:05:26 -0700542 return true;
543 }
544
545 /**
Saurav Dase0237a32016-05-27 13:54:07 -0700546 * Populates IP flow rules for an IP prefix in the target device. The prefix
Saurav Das261c3002017-06-13 15:35:54 -0700547 * is reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700548 *
Saurav Das261c3002017-06-13 15:35:54 -0700549 * @param targetSw target device ID to set the rules
550 * @param ipPrefix the IP prefix
551 * @param destSw1 destination switch where the prefixes are reachable
552 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
553 * Should be null if there is no paired destination switch (by config)
554 * or if the given prefixes are reachable only via destSw1
555 * @param nextHops map of destination switches and their next-hops.
556 * Should only contain destination switches that are
557 * actually meant to be routed to. If destSw2 is null, there
558 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700559 * @return true if all rules are set successfully, false otherwise
560 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700561 private boolean populateIpRuleForRouter(DeviceId targetSw,
Saurav Das261c3002017-06-13 15:35:54 -0700562 IpPrefix ipPrefix, DeviceId destSw1,
563 DeviceId destSw2,
564 Map<DeviceId, Set<DeviceId>> nextHops) {
565 int segmentId1, segmentId2 = -1;
Charles Chan319d1a22015-11-03 10:42:14 -0800566 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800567 if (ipPrefix.isIp4()) {
Saurav Das261c3002017-06-13 15:35:54 -0700568 segmentId1 = config.getIPv4SegmentId(destSw1);
569 if (destSw2 != null) {
570 segmentId2 = config.getIPv4SegmentId(destSw2);
571 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800572 } else {
Saurav Das261c3002017-06-13 15:35:54 -0700573 segmentId1 = config.getIPv6SegmentId(destSw1);
574 if (destSw2 != null) {
575 segmentId2 = config.getIPv6SegmentId(destSw2);
576 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800577 }
Charles Chan319d1a22015-11-03 10:42:14 -0800578 } catch (DeviceConfigNotFoundException e) {
579 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
580 return false;
581 }
sangho80f11cb2015-04-01 13:05:26 -0700582
Pier Ventreadb4ae62016-11-23 09:57:42 -0800583 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanf4586112015-11-09 16:37:23 -0800584 TrafficSelector selector = sbuilder.build();
sangho80f11cb2015-04-01 13:05:26 -0700585
Charles Chanf4586112015-11-09 16:37:23 -0800586 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das261c3002017-06-13 15:35:54 -0700587 DestinationSet ds;
Charles Chanf4586112015-11-09 16:37:23 -0800588 TrafficTreatment treatment;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700589 DestinationSet.DestinationSetType dsType;
sangho80f11cb2015-04-01 13:05:26 -0700590
Saurav Das261c3002017-06-13 15:35:54 -0700591 if (destSw2 == null) {
592 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800593 // If the next hop is the same as the final destination, then MPLS
594 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700595 Set<DeviceId> nhd1 = nextHops.get(destSw1);
596 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
597 tbuilder.immediate().decNwTtl();
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700598 ds = DestinationSet.createTypePushNone(destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700599 treatment = tbuilder.build();
600 } else {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700601 ds = DestinationSet.createTypePushBos(segmentId1, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700602 treatment = null;
603 }
604 } else {
605 // dst pair - IP rules for dst-pairs are always from other edge nodes
606 // the destination set needs to have both destinations, even if there
607 // are no next hops to one of them
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700608 ds = DestinationSet.createTypePushBos(segmentId1, destSw1, segmentId2, destSw2);
Charles Chanf4586112015-11-09 16:37:23 -0800609 treatment = null;
sangho80f11cb2015-04-01 13:05:26 -0700610 }
611
Saurav Das4c35fc42015-11-20 15:27:53 -0800612 // setup metadata to pass to nextObjective - indicate the vlan on egress
613 // if needed by the switch pipeline. Since neighbor sets are always to
614 // other neighboring routers, there is no subnet assigned on those ports.
615 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700616 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Saurav Das261c3002017-06-13 15:35:54 -0700617 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700618 if (grpHandler == null) {
619 log.warn("populateIPRuleForRouter: groupHandler for device {} "
Saurav Das261c3002017-06-13 15:35:54 -0700620 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700621 return false;
622 }
Saurav Das4c35fc42015-11-20 15:27:53 -0800623
Saurav Das261c3002017-06-13 15:35:54 -0700624 int nextId = grpHandler.getNextObjectiveId(ds, nextHops,
Saurav Das97241862018-02-14 14:14:54 -0800625 metabuilder.build(), false);
Saurav Das4c35fc42015-11-20 15:27:53 -0800626 if (nextId <= 0) {
Saurav Das261c3002017-06-13 15:35:54 -0700627 log.warn("No next objective in {} for ds: {}", targetSw, ds);
sangho2165d222015-05-01 09:38:25 -0700628 return false;
629 }
630
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700631 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
632 .builder()
633 .fromApp(srManager.appId)
634 .makePermanent()
Saurav Das4c35fc42015-11-20 15:27:53 -0800635 .nextStep(nextId)
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700636 .withSelector(selector)
Charles Chan82ab1932016-01-30 23:22:37 -0800637 .withPriority(getPriorityFromPrefix(ipPrefix))
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700638 .withFlag(ForwardingObjective.Flag.SPECIFIC);
Charles Chanf4586112015-11-09 16:37:23 -0800639 if (treatment != null) {
640 fwdBuilder.withTreatment(treatment);
641 }
Saurav Das62ae6792017-05-15 15:34:25 -0700642 log.debug("Installing IPv4 forwarding objective for router IP/subnet {} "
Saurav Das261c3002017-06-13 15:35:54 -0700643 + "in switch {} with nextId: {}", ipPrefix, targetSw, nextId);
Charles Chan1eaf4802016-04-18 13:44:03 -0700644 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Dase0237a32016-05-27 13:54:07 -0700645 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700646 ipPrefix, targetSw),
Charles Chan1eaf4802016-04-18 13:44:03 -0700647 (objective, error) ->
Saurav Dase0237a32016-05-27 13:54:07 -0700648 log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700649 ipPrefix, error, targetSw));
650 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
sanghofb7c7292015-04-13 15:15:58 -0700651 rulePopulationCounter.incrementAndGet();
sangho80f11cb2015-04-01 13:05:26 -0700652
653 return true;
654 }
655
sangho80f11cb2015-04-01 13:05:26 -0700656 /**
Charles Chand66d6712018-03-29 16:03:41 -0700657 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700658 *
Charles Chand66d6712018-03-29 16:03:41 -0700659 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700660 * @param ipPrefix the IP address of the destination router
661 * @return true if all rules are removed successfully, false otherwise
662 */
Charles Chand66d6712018-03-29 16:03:41 -0700663 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800664 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700665 TrafficSelector selector = sbuilder.build();
666 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
667
668 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
669 .builder()
670 .fromApp(srManager.appId)
671 .makePermanent()
672 .withSelector(selector)
673 .withTreatment(dummyTreatment)
674 .withPriority(getPriorityFromPrefix(ipPrefix))
675 .withFlag(ForwardingObjective.Flag.SPECIFIC);
676
Charles Chand66d6712018-03-29 16:03:41 -0700677 ObjectiveContext context = new DefaultObjectiveContext(
678 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
679 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
680 ipPrefix, targetSw, error));
681 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700682
683 return true;
684 }
685
686 /**
Saurav Das97241862018-02-14 14:14:54 -0800687 * Populates MPLS flow rules in the target device to point towards the
688 * destination device.
689 *
690 * @param targetSwId target device ID of the switch to set the rules
691 * @param destSwId destination switch device ID
692 * @param nextHops next hops switch ID list
693 * @param routerIp the router ip of the destination switch
694 * @return true if all rules are set successfully, false otherwise
695 */
696 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
697 Set<DeviceId> nextHops, IpAddress routerIp) {
698 int segmentId;
699 try {
700 if (routerIp.isIp4()) {
701 segmentId = config.getIPv4SegmentId(destSwId);
702 } else {
703 segmentId = config.getIPv6SegmentId(destSwId);
704 }
705 } catch (DeviceConfigNotFoundException e) {
706 log.warn(e.getMessage() + " Aborting populateMplsRule.");
707 return false;
708 }
709
710 List<ForwardingObjective> fwdObjs = new ArrayList<>();
711 Collection<ForwardingObjective> fwdObjsMpls;
712 // Generates the transit rules used by the standard "routing".
713 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
714 routerIp, true);
715 if (fwdObjsMpls.isEmpty()) {
716 return false;
717 }
718 fwdObjs.addAll(fwdObjsMpls);
719
720 // Generates the transit rules used by the MPLS Pwaas.
721 int pwSrLabel;
722 try {
723 pwSrLabel = config.getPWRoutingLabel(destSwId);
724 } catch (DeviceConfigNotFoundException e) {
725 log.warn(e.getMessage()
726 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
727 return false;
728 }
729 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
730 routerIp, false);
731 if (fwdObjsMpls.isEmpty()) {
732 return false;
733 }
734 fwdObjs.addAll(fwdObjsMpls);
735
736 for (ForwardingObjective fwdObj : fwdObjs) {
737 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
738 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
739 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
740 rulePopulationCounter.incrementAndGet();
741 }
742
743 return true;
744 }
745
746 /**
747 * Differentiates between popping and swapping labels when building an MPLS
748 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700749 *
750 * @param targetSwId the target sw
751 * @param destSwId the destination sw
752 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800753 * @param segmentId the segmentId to match representing the destination
754 * switch
755 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700756 * @return a collection of fwdobjective
757 */
Saurav Das261c3002017-06-13 15:35:54 -0700758 private Collection<ForwardingObjective> handleMpls(
759 DeviceId targetSwId,
760 DeviceId destSwId,
761 Set<DeviceId> nextHops,
762 int segmentId,
763 IpAddress routerIp,
764 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700765
766 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
767 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800768 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700769 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
770 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
771 sbuilder.matchMplsBos(isMplsBos);
772 TrafficSelector selector = sbuilder.build();
773
774 // setup metadata to pass to nextObjective - indicate the vlan on egress
775 // if needed by the switch pipeline. Since mpls next-hops are always to
776 // other neighboring routers, there is no subnet assigned on those ports.
777 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700778 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre229fd0b2016-10-31 16:49:19 -0700779
780 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
781 // If the next hop is the destination router for the segment, do pop
782 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700783 + "label {} in switch {} with pop to next-hops {}",
784 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700785 ForwardingObjective.Builder fwdObjNoBosBuilder =
786 getMplsForwardingObjective(targetSwId,
787 nextHops,
788 true,
789 isMplsBos,
790 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700791 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800792 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700793 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700794 // Error case, we cannot handle, exit.
795 if (fwdObjNoBosBuilder == null) {
796 return Collections.emptyList();
797 }
798 fwdObjBuilders.add(fwdObjNoBosBuilder);
799
800 } else {
Saurav Das97241862018-02-14 14:14:54 -0800801 // next hop is not destination, irrespective of the number of next
802 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700803 log.debug("Installing MPLS forwarding objective for "
804 + "label {} in switch {} without pop to next-hops {}",
805 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700806 ForwardingObjective.Builder fwdObjNoBosBuilder =
807 getMplsForwardingObjective(targetSwId,
808 nextHops,
809 false,
810 isMplsBos,
811 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700812 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800813 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700814 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700815 // Error case, we cannot handle, exit.
816 if (fwdObjNoBosBuilder == null) {
817 return Collections.emptyList();
818 }
819 fwdObjBuilders.add(fwdObjNoBosBuilder);
820
821 }
822
823 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
824 // We add the final property to the fwdObjs.
825 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700826 ((Builder) ((Builder) fwdObjBuilder
827 .fromApp(srManager.appId)
828 .makePermanent())
829 .withSelector(selector)
830 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
831 .withFlag(ForwardingObjective.Flag.SPECIFIC);
832
833 ObjectiveContext context = new DefaultObjectiveContext(
834 (objective) ->
835 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
836 objective.id(), segmentId, targetSwId),
837 (objective, error) ->
838 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
839 objective.id(), segmentId, error, targetSwId));
840
841 ForwardingObjective fob = fwdObjBuilder.add(context);
842 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700843 }
844
845 return fwdObjs;
846 }
847
848 /**
Saurav Das97241862018-02-14 14:14:54 -0800849 * Returns a Forwarding Objective builder for the MPLS rule that references
850 * the desired Next Objective. Creates a DestinationSet that allows the
851 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700852 *
Saurav Das97241862018-02-14 14:14:54 -0800853 * @param targetSw the target sw
854 * @param nextHops the set of next hops
855 * @param phpRequired true if penultimate-hop-popping is required
856 * @param isBos true if matched label is bottom-of-stack
857 * @param meta metadata for creating next objective
858 * @param routerIp the router ip representing the destination switch
859 * @param destSw the destination sw
860 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700861 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800862 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700863 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800864 Set<DeviceId> nextHops,
865 boolean phpRequired,
866 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800867 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700868 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800869 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700870 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800871
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700872 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
873 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700874
875 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800876 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700877 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800878 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700879 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800880 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700881 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700882 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700883 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800884 if (routerIp.isIp4()) {
885 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
886 } else {
887 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
888 }
889 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800890 // standard case -> BoS == True; pop results in IP packet and forwarding
891 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700892 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700893 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800894 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
895 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800896 // double-label case -> BoS == False, pop results in MPLS packet
897 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700898 ds = DestinationSet.createTypePopNotBos(destSw);
899 if (!srManager.getMplsEcmp()) {
900 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800901 }
sangho80f11cb2015-04-01 13:05:26 -0700902 }
903 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800904 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800905 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700906 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800907 // swap results in MPLS packet with same BoS bit regardless of bit value
908 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700909 // differentiate here between swap with not bos or swap with bos
910 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
911 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
912 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800913 simple = true;
914 }
sangho80f11cb2015-04-01 13:05:26 -0700915 }
916
Saurav Das4c35fc42015-11-20 15:27:53 -0800917 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800918 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
919 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700920 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
921 if (gh == null) {
922 log.warn("getNextObjectiveId query - groupHandler for device {} "
923 + "not found", targetSw);
924 return null;
925 }
Saurav Das97241862018-02-14 14:14:54 -0800926
Saurav Das261c3002017-06-13 15:35:54 -0700927 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
928 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800929 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800930 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800931 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800932 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700933 } else {
Saurav Das97241862018-02-14 14:14:54 -0800934 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
935 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -0700936 }
937
Saurav Das4c35fc42015-11-20 15:27:53 -0800938 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700939 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -0700940 }
941
942 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -0700943 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -0700944 * dstMac corresponding to the router's MAC address. For those pipelines
945 * that need to internally assign vlans to untagged packets, this method
946 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -0700947 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -0800948 * Note that the vlan assignment and filter programming should only be done by
949 * the master for a switch. This method is typically called at deviceAdd and
950 * programs filters only for the enabled ports of the device. For port-updates,
951 * that enable/disable ports after device add, singlePortFilter methods should
952 * be called.
sangho80f11cb2015-04-01 13:05:26 -0700953 *
Saurav Das9f1c42e2015-10-23 10:51:11 -0700954 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -0800955 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -0700956 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700957 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -0700958 log.debug("Installing per-port filtering objective for untagged "
959 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800960
Saurav Das07c74602016-04-27 18:35:50 -0700961 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -0800962 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -0700963 log.warn("Device {} ports not available. Unable to add MacVlan filters",
964 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -0800965 return null;
Saurav Das07c74602016-04-27 18:35:50 -0700966 }
Saurav Dasf9332192017-02-18 14:05:44 -0800967 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -0700968 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -0700969 if (!port.isEnabled()) {
970 disabledPorts++;
971 continue;
972 }
Charles Chan43be46b2017-02-26 22:59:35 -0800973 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -0800974 filteredPorts++;
975 } else {
976 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -0700977 }
Saurav Das7c305372015-10-28 12:39:42 -0700978 }
Charles Chan077314e2017-06-22 14:27:17 -0700979 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -0800980 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan9d2dd552018-06-19 20:56:33 -0700981 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Dasf9332192017-02-18 14:05:44 -0800982 }
983
984 /**
Charles Chan43be46b2017-02-26 22:59:35 -0800985 * Creates or removes filtering objectives for a single port. Should only be
986 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -0800987 *
988 * @param deviceId device identifier
989 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -0800990 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -0800991 * @return true if no errors occurred during the build of the filtering objective
992 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700993 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -0800994 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -0700995 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
996 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
997 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -0800998
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700999 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -08001000 if (taggedVlans.size() != 0) {
1001 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -07001002 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan43be46b2017-02-26 22:59:35 -08001003 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan90772a72017-02-08 15:52:08 -08001004 return false;
1005 }
1006 if (nativeVlan != null) {
1007 // Filter for native vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001008 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001009 return false;
1010 }
1011 }
1012 } else if (untaggedVlan != null) {
1013 // Filter for untagged vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001014 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001015 return false;
1016 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001017 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001018 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das9bf49582018-08-13 15:34:26 -07001019 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1020 srManager.getDefaultInternalVlan(),
1021 install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001022 return false;
1023 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001024 // Filter for receiveing pseudowire traffic
Saurav Das9bf49582018-08-13 15:34:26 -07001025 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1026 srManager.getPwTransportVlan(),
1027 install)) {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001028 return false;
1029 }
Charles Chan90772a72017-02-08 15:52:08 -08001030 }
1031 return true;
1032 }
1033
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001034 /**
1035 * Updates filtering objectives for a single port. Should only be called by
1036 * the master for a switch
1037 * @param deviceId device identifier
1038 * @param portNum port identifier for port to be filtered
1039 * @param pushVlan true to push vlan, false otherwise
1040 * @param vlanId vlan identifier
1041 * @param install true to install the filtering objective, false to remove
1042 */
1043 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1044 boolean pushVlan, VlanId vlanId, boolean install) {
1045 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
1046 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1047 deviceId, portNum, vlanId);
1048 }
1049 }
1050
Charles Chan43be46b2017-02-26 22:59:35 -08001051 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1052 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001053 boolean doTMAC = true;
1054
1055 if (!pushVlan) {
1056 // Skip the tagged vlans belonging to an interface without an IP address
1057 Set<Interface> ifaces = srManager.interfaceService
1058 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1059 .stream()
1060 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1061 .collect(Collectors.toSet());
1062 if (!ifaces.isEmpty()) {
1063 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1064 vlanId, deviceId, portnum);
1065 doTMAC = false;
1066 }
1067 }
1068
1069 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Dasf9332192017-02-18 14:05:44 -08001070 if (fob == null) {
1071 // error encountered during build
1072 return false;
1073 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001074 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001075 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001076 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001077 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001078 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001079 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001080 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001081 if (install) {
1082 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1083 } else {
1084 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001085 }
Charles Chan90772a72017-02-08 15:52:08 -08001086 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001087 }
1088
Charles Chan90772a72017-02-08 15:52:08 -08001089 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001090 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Dasf9332192017-02-18 14:05:44 -08001091 MacAddress deviceMac;
1092 try {
1093 deviceMac = config.getDeviceMac(deviceId);
1094 } catch (DeviceConfigNotFoundException e) {
1095 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1096 return null;
1097 }
Saurav Dasf9332192017-02-18 14:05:44 -08001098 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001099
1100 if (doTMAC) {
1101 fob.withKey(Criteria.matchInPort(portnum))
1102 .addCondition(Criteria.matchEthDst(deviceMac))
1103 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1104 } else {
1105 fob.withKey(Criteria.matchInPort(portnum))
1106 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1107 }
Charles Chan90772a72017-02-08 15:52:08 -08001108
Charles Chan17ca2202017-12-19 19:55:57 -08001109 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1110
Charles Chan90772a72017-02-08 15:52:08 -08001111 if (pushVlan) {
1112 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001113 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001114 } else {
1115 fob.addCondition(Criteria.matchVlanId(vlanId));
1116 }
1117
Charles Chan17ca2202017-12-19 19:55:57 -08001118 // NOTE: Some switch hardware share the same filtering flow among different ports.
1119 // We use this metadata to let the driver know that there is no more enabled port
1120 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001121 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001122 tBuilder.wipeDeferred();
1123 }
1124
1125 fob.withMeta(tBuilder.build());
1126
Saurav Dasf9332192017-02-18 14:05:44 -08001127 fob.permit().fromApp(srManager.appId);
1128 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001129 }
1130
1131 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001132 * Creates or removes filtering objectives for a double-tagged host on a port.
1133 *
1134 * @param deviceId device identifier
1135 * @param portNum port identifier for port to be filtered
1136 * @param outerVlan outer VLAN ID
1137 * @param innerVlan inner VLAN ID
1138 * @param install true to install the filtering objective, false to remove
1139 */
1140 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1141 VlanId innerVlan, boolean install) {
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001142 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum, outerVlan, innerVlan, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001143 if (fob == null) {
1144 // error encountered during build
1145 return;
1146 }
1147 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1148 install ? "Installing" : "Removing", deviceId, portNum);
1149 ObjectiveContext context = new DefaultObjectiveContext(
1150 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1151 install ? "installed" : "removed"),
1152 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1153 install ? "install" : "remove", deviceId, portNum, error));
1154 if (install) {
1155 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1156 } else {
1157 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1158 }
1159 }
1160
1161 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001162 VlanId outerVlan, VlanId innerVlan,
1163 boolean cleanupDoubleTaggedRules) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001164 MacAddress deviceMac;
1165 try {
1166 deviceMac = config.getDeviceMac(deviceId);
1167 } catch (DeviceConfigNotFoundException e) {
1168 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1169 return null;
1170 }
1171 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1172 // Outer vlan id match should be appeared before inner vlan id match.
1173 fob.withKey(Criteria.matchInPort(portNum))
1174 .addCondition(Criteria.matchEthDst(deviceMac))
1175 .addCondition(Criteria.matchVlanId(outerVlan))
1176 .addCondition(Criteria.matchVlanId(innerVlan))
1177 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1178
1179 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1180 // Pop outer vlan
1181 tBuilder.popVlan();
1182
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001183 // special metadata for driver
1184 if (cleanupDoubleTaggedRules) {
1185 tBuilder.writeMetadata(CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES, DOUBLE_TAGGED_METADATA_MASK);
1186 } else {
1187 tBuilder.writeMetadata(0, DOUBLE_TAGGED_METADATA_MASK);
1188 }
1189
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001190 // NOTE: Some switch hardware share the same filtering flow among different ports.
1191 // We use this metadata to let the driver know that there is no more enabled port
1192 // within the same VLAN on this device.
1193 if (noMoreEnabledPort(deviceId, outerVlan)) {
1194 tBuilder.wipeDeferred();
1195 }
1196
1197 fob.withMeta(tBuilder.build());
1198
1199 fob.permit().fromApp(srManager.appId);
1200 return fob;
1201 }
1202
1203 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001204 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001205 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001206 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001207 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001208 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001209 * @param deviceId the switch dpid for the router
sangho80f11cb2015-04-01 13:05:26 -07001210 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001211 void populateIpPunts(DeviceId deviceId) {
Saurav Das261c3002017-06-13 15:35:54 -07001212 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001213 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001214 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001215 routerIpv4 = config.getRouterIpv4(deviceId);
1216 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001217 routerLinkLocalIpv6 = Ip6Address.valueOf(
1218 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1219
Saurav Das261c3002017-06-13 15:35:54 -07001220 if (config.isPairedEdge(deviceId)) {
1221 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1222 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1223 }
Charles Chan319d1a22015-11-03 10:42:14 -08001224 } catch (DeviceConfigNotFoundException e) {
Charles Chan18fa4252017-02-08 16:10:40 -08001225 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001226 return;
1227 }
1228
Saurav Dasc28b3432015-10-30 17:45:38 -07001229 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1230 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1231 deviceId);
1232 return;
1233 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001234 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1235 allIps.add(routerIpv4);
1236 if (routerIpv6 != null) {
1237 allIps.add(routerIpv6);
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001238 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001239 }
Saurav Das261c3002017-06-13 15:35:54 -07001240 if (pairRouterIpv4 != null) {
1241 allIps.add(pairRouterIpv4);
1242 }
1243 if (pairRouterIpv6 != null) {
1244 allIps.add(pairRouterIpv6);
1245 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001246 for (IpAddress ipaddr : allIps) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001247 populateSingleIpPunts(deviceId, ipaddr);
1248 }
1249 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001250
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001251 /**
1252 * Creates a forwarding objective to punt all IP packets, destined to the
1253 * specified IP address, which should be router's port IP address.
1254 *
1255 * @param deviceId the switch dpid for the router
1256 * @param ipAddress the IP address of the router's port
1257 */
1258 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1259 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1260 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1261
1262 srManager.packetService.requestPackets(sbuilder.build(),
1263 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1264 }
1265
1266 /**
1267 * Removes a forwarding objective to punt all IP packets, destined to the
1268 * specified IP address, which should be router's port IP address.
1269 *
1270 * @param deviceId the switch dpid for the router
1271 * @param ipAddress the IP address of the router's port
1272 */
1273 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1274 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1275 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1276
1277 try {
1278 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1279 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1280 srManager.packetService.cancelPackets(sbuilder.build(),
1281 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1282 }
1283 } catch (DeviceConfigNotFoundException e) {
1284 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das9f1c42e2015-10-23 10:51:11 -07001285 }
sangho80f11cb2015-04-01 13:05:26 -07001286 }
1287
Charles Chanf4586112015-11-09 16:37:23 -08001288 /**
Pier Ventreadb4ae62016-11-23 09:57:42 -08001289 * Method to build IPv4 or IPv6 selector.
1290 *
1291 * @param addressToMatch the address to match
1292 */
1293 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1294 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1295 }
1296
1297 /**
1298 * Method to build IPv4 or IPv6 selector.
1299 *
1300 * @param prefixToMatch the prefix to match
1301 */
1302 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1303 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001304 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001305 if (prefixToMatch.isIp4()) {
1306 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1307 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1308 return selectorBuilder;
1309 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001310 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001311 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1312 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1313 return selectorBuilder;
1314 }
1315
1316 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001317 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1318 * Furthermore, these are applied only by the master instance. Deferred actions
1319 * are not cleared such that packets can be flooded in the cross connect use case
1320 *
1321 * @param deviceId the switch dpid for the router
1322 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001323 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001324 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001325 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1326 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1327 deviceId);
1328 return;
1329 }
1330
Charles Chan3ed34d82017-06-22 18:03:14 -07001331 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001332 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001333 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001334 .add(new ObjectiveContext() {
1335 @Override
1336 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001337 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001338 deviceId, error);
1339 }
1340 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001341 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001342
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001343 if (isIpv6Configured(deviceId)) {
1344 // We punt all NDP packets towards the controller.
1345 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1346 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1347 @Override
1348 public void onError(Objective objective, ObjectiveError error) {
1349 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1350 deviceId, error);
1351 }
1352 });
1353 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan051490d2018-01-11 11:48:18 -08001354 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001355 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001356
Saurav Dasec683dc2018-04-27 18:42:30 -07001357 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001358 ForwardingObjective pairFwdObj;
1359 // Do not punt ARP packets from pair port
1360 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1361 .add(new ObjectiveContext() {
1362 @Override
1363 public void onError(Objective objective, ObjectiveError error) {
1364 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1365 deviceId, error);
1366 }
1367 });
1368 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1369
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001370 if (isIpv6Configured(deviceId)) {
1371 // Do not punt NDP packets from pair port
1372 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1373 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan3ed34d82017-06-22 18:03:14 -07001374 @Override
1375 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001376 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan3ed34d82017-06-22 18:03:14 -07001377 deviceId, error);
1378 }
1379 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001380 srManager.flowObjectiveService.forward(deviceId, obj);
1381 });
1382
1383 // Do not forward DAD packets from pair port
1384 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1385 .add(new ObjectiveContext() {
1386 @Override
1387 public void onError(Objective objective, ObjectiveError error) {
1388 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1389 deviceId, error);
1390 }
1391 });
1392 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1393 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001394 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001395 }
1396
Charles Chan3ed34d82017-06-22 18:03:14 -07001397 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1398 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001399 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001400 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001401 .withSelector(selector)
1402 .fromApp(srManager.appId)
1403 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001404 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001405 .makePermanent();
1406 }
1407
Charles Chan3ed34d82017-06-22 18:03:14 -07001408 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001409 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1410 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001411 if (port != null) {
1412 sBuilder.matchInPort(port);
1413 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001414
Charles Chan3ed34d82017-06-22 18:03:14 -07001415 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1416 if (punt) {
1417 tBuilder.punt();
1418 }
1419 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001420 }
1421
Charles Chan051490d2018-01-11 11:48:18 -08001422 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1423 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001424
Charles Chan051490d2018-01-11 11:48:18 -08001425 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1426 .forEach(type -> {
1427 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1428 sBuilder.matchEthType(TYPE_IPV6)
1429 .matchIPProtocol(PROTOCOL_ICMP6)
1430 .matchIcmpv6Type(type);
1431 if (port != null) {
1432 sBuilder.matchInPort(port);
1433 }
1434
1435 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1436 if (punt) {
1437 tBuilder.punt();
1438 }
1439
1440 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1441 });
1442
1443 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001444 }
1445
1446 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1447 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1448 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001449 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1450 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1451 // .matchIPProtocol(PROTOCOL_ICMP6)
1452 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001453 if (port != null) {
1454 sBuilder.matchInPort(port);
1455 }
1456
1457 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1458 tBuilder.wipeDeferred();
1459 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001460 }
1461
1462 /**
Charles Chan155ec442018-09-16 14:30:19 -07001463 * Block given prefix in routing table.
Charles Chanf4586112015-11-09 16:37:23 -08001464 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001465 * @param address the address to block
1466 * @param deviceId switch ID to set the rules
1467 */
1468 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1469 updateDefaultRouteBlackhole(deviceId, address, true);
1470 }
1471
1472 /**
Charles Chan155ec442018-09-16 14:30:19 -07001473 * Unblock given prefix in routing table.
Andrea Campanella60ce2222018-04-30 11:48:55 +02001474 *
1475 * @param address the address to block
1476 * @param deviceId switch ID to set the rules
1477 */
1478 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1479 updateDefaultRouteBlackhole(deviceId, address, false);
1480 }
1481
1482 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1483 try {
1484 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1485
1486 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1487 if (address.isIp4()) {
1488 sbuilder.matchIPDst(address);
1489 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1490 } else {
1491 sbuilder.matchIPv6Dst(address);
1492 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1493 }
1494
1495 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
Andrea Campanella60ce2222018-04-30 11:48:55 +02001496 tBuilder.wipeDeferred();
1497
1498 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1499 fob.withFlag(Flag.SPECIFIC)
1500 .withSelector(sbuilder.build())
1501 .withTreatment(tBuilder.build())
1502 .withPriority(getPriorityFromPrefix(address))
1503 .fromApp(srManager.appId)
1504 .makePermanent();
1505
1506 log.debug("{} blackhole forwarding objectives for dev: {}",
1507 install ? "Installing" : "Removing", deviceId);
1508 ObjectiveContext context = new DefaultObjectiveContext(
1509 (objective) -> log.debug("Forward for {} {}", deviceId,
1510 install ? "installed" : "removed"),
1511 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1512 install ? "install" : "remove", deviceId, error));
1513 if (install) {
1514 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1515 } else {
1516 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1517 }
1518 }
1519 } catch (DeviceConfigNotFoundException e) {
1520 log.info("Not populating blackhole for un-configured device {}", deviceId);
1521 }
1522
1523 }
1524
1525 /**
1526 * Populates a forwarding objective to send packets that miss other high
1527 * priority Bridging Table entries to a group that contains all ports of
1528 * its subnet.
1529 *
Charles Chanf4586112015-11-09 16:37:23 -08001530 * @param deviceId switch ID to set the rules
1531 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001532 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001533 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001534 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001535 });
1536 }
1537
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001538 /**
1539 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1540 * @param deviceId switch ID to set the rule
1541 * @param vlanId vlan ID to specify the subnet
1542 * @param install true to install the rule, false to revoke the rule
1543 */
1544 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1545 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1546
1547 if (nextId < 0) {
1548 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1549 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1550 return;
1551 }
1552
1553 // Driver should treat objective with MacAddress.NONE as the
1554 // subnet broadcast rule
1555 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1556 sbuilder.matchVlanId(vlanId);
1557 sbuilder.matchEthDst(MacAddress.NONE);
1558
1559 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1560 fob.withFlag(Flag.SPECIFIC)
1561 .withSelector(sbuilder.build())
1562 .nextStep(nextId)
1563 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1564 .fromApp(srManager.appId)
1565 .makePermanent();
1566 ObjectiveContext context = new DefaultObjectiveContext(
1567 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1568 (objective, error) ->
1569 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1570
1571 if (install) {
1572 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1573 } else {
1574 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1575 }
1576 }
1577
Charles Chan82ab1932016-01-30 23:22:37 -08001578 private int getPriorityFromPrefix(IpPrefix prefix) {
1579 return (prefix.isIp4()) ?
1580 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1581 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001582 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001583
1584 /**
1585 * Update Forwarding objective for each host and IP address connected to given port.
1586 * And create corresponding Simple Next objective if it does not exist.
1587 * Applied only when populating Forwarding objective
1588 * @param deviceId switch ID to set the rule
1589 * @param portNumber port number
1590 * @param prefix IP prefix of the route
1591 * @param hostMac MAC address of the next hop
1592 * @param vlanId Vlan ID of the port
1593 * @param popVlan true to pop vlan tag in TrafficTreatment
1594 * @param install true to populate the forwarding objective, false to revoke
1595 */
1596 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1597 VlanId vlanId, boolean popVlan, boolean install) {
1598 ForwardingObjective.Builder fob;
1599 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1600 MacAddress deviceMac;
1601 try {
1602 deviceMac = config.getDeviceMac(deviceId);
1603 } catch (DeviceConfigNotFoundException e) {
1604 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1605 return;
1606 }
1607
1608 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1609 tbuilder.deferred()
1610 .setEthDst(hostMac)
1611 .setEthSrc(deviceMac)
1612 .setOutput(portNumber);
1613
1614 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1615
1616 if (!popVlan) {
1617 tbuilder.setVlanId(vlanId);
1618 } else {
1619 mbuilder.matchVlanId(vlanId);
1620 }
1621
1622 // if the objective is to revoke an existing rule, and for some reason
1623 // the next-objective does not exist, then a new one should not be created
1624 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1625 tbuilder.build(), mbuilder.build(), install);
1626 if (portNextObjId == -1) {
1627 // Warning log will come from getPortNextObjective method
1628 return;
1629 }
1630
1631 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1632 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1633 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1634
1635 ObjectiveContext context = new DefaultObjectiveContext(
1636 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1637 (objective, error) ->
1638 log.warn("Failed to {} IP rule for route {}: {}",
1639 install ? "install" : "revoke", prefix, error));
1640 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1641
1642 if (!install) {
1643 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1644 if (grpHandler == null) {
1645 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1646 } else {
1647 // Remove L3UG for the given port and host
1648 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1649 }
1650 }
1651 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001652
1653 /**
1654 * Checks if there is other enabled port within the given VLAN on the given device.
1655 *
1656 * @param deviceId device ID
1657 * @param vlanId VLAN ID
1658 * @return true if there is no more port enabled within the given VLAN on the given device
1659 */
1660 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1661 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1662 .filter(Port::isEnabled)
1663 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1664 .collect(Collectors.toSet());
1665
1666 return enabledPorts.stream().noneMatch(cp ->
1667 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001668 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001669 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001670 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Saurav Das9bf49582018-08-13 15:34:26 -07001671 vlanId.equals(srManager.getDefaultInternalVlan())) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001672 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1673 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1674 );
1675 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001676
1677 /**
1678 * Returns a forwarding objective builder for egress forwarding rules.
1679 * <p>
1680 * The forwarding objective installs flow rules to egress pipeline to push
1681 * two vlan headers with given inner, outer vlan ids and outer tpid.
1682 *
1683 * @param portNumber port where the next hop attaches to
1684 * @param dummyVlanId vlan ID of the packet to match
1685 * @param innerVlan inner vlan ID of the next hop
1686 * @param outerVlan outer vlan ID of the next hop
1687 * @param outerTpid outer TPID of the next hop
1688 * @return forwarding objective builder
1689 */
1690 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1691 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1692 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1693 sbuilder.matchVlanId(dummyVlanId);
1694 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1695 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1696
1697 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1698 tbuilder.pushVlan(outerTpid);
1699 } else {
1700 tbuilder.pushVlan();
1701 }
1702
1703 tbuilder.setVlanId(outerVlan);
1704 return DefaultForwardingObjective.builder()
1705 .withSelector(sbuilder.build())
1706 .withTreatment(tbuilder.build())
1707 .fromApp(srManager.appId)
1708 .makePermanent()
1709 .withPriority(DEFAULT_PRIORITY)
1710 .withFlag(ForwardingObjective.Flag.EGRESS);
1711 }
1712
1713 /**
1714 * Populates IP rules for a route that has double-tagged next hop.
1715 *
1716 * @param deviceId device ID of the device that next hop attaches to
1717 * @param prefix IP prefix of the route
1718 * @param hostMac MAC address of the next hop
1719 * @param dummyVlan Dummy Vlan ID allocated for this route
1720 * @param innerVlan inner Vlan ID of the next hop
1721 * @param outerVlan outer Vlan ID of the next hop
1722 * @param outerTpid outer TPID of the next hop
1723 * @param outPort port where the next hop attaches to
1724 */
1725 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId dummyVlan,
1726 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1727 ForwardingObjective.Builder fwdBuilder;
1728 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1729 prefix, deviceId, outPort);
1730
1731 ForwardingObjective.Builder egressFwdBuilder = egressFwdObjBuilder(
1732 outPort, dummyVlan, innerVlan, outerVlan, outerTpid);
1733 DefaultObjectiveContext egressFwdContext = new DefaultObjectiveContext(
1734 objective -> log.debug("Egress rule for IP {} is populated", prefix.address()),
1735 (objective, error) -> {
1736 log.warn("Failed to populate egress rule for IP {}: {}", prefix.address(), error);
1737 srManager.dummyVlanIdStore().remove(new DummyVlanIdStoreKey(
1738 new ConnectPoint(deviceId, outPort), prefix.address()
1739 ));
1740 });
1741 try {
Daniele Morodbf1a3a2019-07-02 17:25:25 -07001742 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, dummyVlan, outPort, true, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001743 } catch (DeviceConfigNotFoundException e) {
1744 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1745 return;
1746 }
1747 if (fwdBuilder == null) {
1748 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1749 deviceId, prefix);
1750 return;
1751 }
1752
1753 // Egress forwarding objective should be installed after the nextObjective for the output port is installed.
1754 // Installation of routingFwdObj will ensure the installation of the nextObjective.
1755 int nextId = fwdBuilder.add().nextId();
1756 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1757 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
1758 srManager.flowObjectiveService.forward(deviceId, egressFwdBuilder.add(egressFwdContext));
1759 }, (objective, error) ->
1760 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1761 );
1762 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1763 rulePopulationCounter.incrementAndGet();
1764 }
1765
1766 /**
1767 * Revokes IP rules for a route that has double-tagged next hop.
1768 *
1769 * @param deviceId device ID of the device that next hop attaches to
1770 * @param prefix IP prefix of the route
1771 * @param hostMac MAC address of the next hop
1772 * @param hostVlan Vlan ID of the next hop
1773 * @param innerVlan inner Vlan ID of the next hop
1774 * @param outerVlan outer Vlan ID of the next hop
1775 * @param outerTpid outer TPID of the next hop
1776 * @param outPort port where the next hop attaches to
1777 */
1778 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
1779 VlanId hostVlan, VlanId innerVlan, VlanId outerVlan,
1780 EthType outerTpid, PortNumber outPort) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001781 revokeRoute(deviceId, prefix, hostMac, hostVlan, outPort, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001782
1783 DummyVlanIdStoreKey key = new DummyVlanIdStoreKey(
1784 new ConnectPoint(deviceId, outPort), prefix.address());
1785 VlanId dummyVlanId = srManager.dummyVlanIdStore().get(key);
1786 if (dummyVlanId == null) {
1787 log.warn("Failed to retrieve dummy VLAN ID for {}/{} and {}",
1788 deviceId, outPort, prefix.address());
1789 return;
1790 }
1791 ForwardingObjective.Builder fob = egressFwdObjBuilder(
1792 outPort, dummyVlanId, innerVlan, outerVlan, outerTpid);
1793 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1794 log.debug("Egress rule for IP {} revoked", prefix.address());
1795 srManager.dummyVlanIdStore().remove(key);
1796 }, (objective, error) -> {
1797 log.warn("Failed to revoke egress rule for IP {}: {}", prefix.address(), error);
1798 });
1799 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1800 }
1801
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001802 /**
1803 * Checks whether the specified port has IP configuration or not.
1804 *
1805 * @param cp ConnectPoint to check the existance of IP configuration
1806 * @return true if the port has IP configuration; false otherwise.
1807 */
1808 private boolean hasIPConfiguration(ConnectPoint cp) {
1809 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1810 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1811 }
Saurav Das9bf49582018-08-13 15:34:26 -07001812
1813 /**
1814 * Updates filtering rules for unconfigured ports on all devices for which
1815 * this controller instance is master.
1816 *
1817 * @param pushVlan true if the filtering rule requires a push vlan action
1818 * @param oldVlanId the vlanId to be removed
1819 * @param newVlanId the vlanId to be added
1820 */
1821 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1822 VlanId newVlanId) {
1823 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1824 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1825 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1826 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1827 && p.isEnabled()) {
1828 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1829 oldVlanId, false);
1830 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1831 newVlanId, true);
1832 }
1833 }
1834 }
1835 }
1836 }
1837
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001838 private boolean isIpv6Configured(DeviceId deviceId) {
1839 boolean isIpv6Configured;
1840 try {
1841 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1842 } catch (DeviceConfigNotFoundException e) {
1843 isIpv6Configured = false;
1844 }
1845 return isIpv6Configured;
1846 }
sangho80f11cb2015-04-01 13:05:26 -07001847}