blob: 7dddd3fa3cc979e6e2789d0f6d9da9ada9a6c202 [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;
Charles Chan61c086d2019-07-26 17:46:15 -070020import org.apache.commons.lang3.tuple.ImmutablePair;
Saurav Das4c35fc42015-11-20 15:27:53 -080021import org.onlab.packet.EthType;
sangho80f11cb2015-04-01 13:05:26 -070022import org.onlab.packet.Ethernet;
Charles Chanef8d12e2017-12-05 21:07:38 -080023import org.onlab.packet.IPv6;
sangho80f11cb2015-04-01 13:05:26 -070024import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080025import org.onlab.packet.Ip6Address;
26import org.onlab.packet.IpAddress;
sangho80f11cb2015-04-01 13:05:26 -070027import org.onlab.packet.IpPrefix;
28import org.onlab.packet.MacAddress;
sangho80f11cb2015-04-01 13:05:26 -070029import org.onlab.packet.MplsLabel;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070030import org.onlab.packet.VlanId;
Charles Chanb7f75ac2016-01-11 18:28:54 -080031import org.onosproject.net.ConnectPoint;
Saurav Das9bf49582018-08-13 15:34:26 -070032import org.onosproject.net.Device;
Charles Chan1eaf4802016-04-18 13:44:03 -070033import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080034import org.onosproject.net.flowobjective.Objective;
Charles Chan1eaf4802016-04-18 13:44:03 -070035import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080036import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -070037import org.onosproject.net.intf.Interface;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080038import org.onosproject.net.packet.PacketPriority;
Charles Chan319d1a22015-11-03 10:42:14 -080039import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
40import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070041import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070042import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sangho80f11cb2015-04-01 13:05:26 -070043import org.onosproject.net.DeviceId;
Saurav Das7c305372015-10-28 12:39:42 -070044import org.onosproject.net.Port;
sangho80f11cb2015-04-01 13:05:26 -070045import org.onosproject.net.PortNumber;
sangho80f11cb2015-04-01 13:05:26 -070046import org.onosproject.net.flow.DefaultTrafficSelector;
47import org.onosproject.net.flow.DefaultTrafficTreatment;
sangho80f11cb2015-04-01 13:05:26 -070048import org.onosproject.net.flow.TrafficSelector;
49import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070050import org.onosproject.net.flow.criteria.Criteria;
51import org.onosproject.net.flowobjective.DefaultFilteringObjective;
52import org.onosproject.net.flowobjective.DefaultForwardingObjective;
53import org.onosproject.net.flowobjective.FilteringObjective;
54import org.onosproject.net.flowobjective.ForwardingObjective;
55import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
Saurav Das9f1c42e2015-10-23 10:51:11 -070056import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
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,
Charles Chan61c086d2019-07-26 17:46:15 -0700319 hostVlanId, outPort, null, null, 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,
Charles Chan61c086d2019-07-26 17:46:15 -0700359 hostVlanId, outPort, null, null, 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
Charles Chan61c086d2019-07-26 17:46:15 -0700393 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700394 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700395 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
Charles Chan61c086d2019-07-26 17:46:15 -0700396 VlanId innerVlan, EthType outerTpid,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000397 boolean directHost, boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800398 throws DeviceConfigNotFoundException {
Charles Chan61c086d2019-07-26 17:46:15 -0700399 int nextObjId;
400 if (directHost) {
401 // if the objective is to revoke an existing rule, and for some reason
402 // the next-objective does not exist, then a new one should not be created
403 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta =
404 getTreatmentAndMeta(deviceId, hostMac, hostVlanId, outPort, innerVlan, outerTpid);
405 if (treatmentAndMeta == null) {
406 // Warning log will come from getTreatmentAndMeta method
407 return null;
408 }
409 nextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
410 treatmentAndMeta.getLeft(), treatmentAndMeta.getRight(), !revoke);
411 } else {
412 // if the objective is to revoke an existing rule, and for some reason
413 // the next-objective does not exist, then a new one should not be created
414 nextObjId = srManager.getMacVlanNextObjectiveId(deviceId, hostMac, hostVlanId,
415 outPort, !revoke);
416 }
417 if (nextObjId == -1) {
418 // Warning log will come from getMacVlanNextObjective method
419 return null;
420 }
421
422 return DefaultForwardingObjective.builder()
423 .withSelector(buildIpSelectorFromIpPrefix(prefix).build())
424 .nextStep(nextObjId)
425 .fromApp(srManager.appId).makePermanent()
426 .withPriority(getPriorityFromPrefix(prefix))
427 .withFlag(ForwardingObjective.Flag.SPECIFIC);
428 }
429
430 private ImmutablePair<TrafficTreatment, TrafficSelector> getTreatmentAndMeta(
431 DeviceId deviceId, MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
432 VlanId innerVlan, EthType outerTpid)
433 throws DeviceConfigNotFoundException {
434 MacAddress routerMac;
435 routerMac = config.getDeviceMac(deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800436
Charles Chan90772a72017-02-08 15:52:08 -0800437 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700438 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
439 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
440 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700441
Charles Chan90772a72017-02-08 15:52:08 -0800442 // Create route treatment
Charles Chanddac7fd2016-10-27 14:19:48 -0700443 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho27462c62015-05-14 00:39:53 -0700444 tbuilder.deferred()
445 .setEthDst(hostMac)
Charles Chan61c086d2019-07-26 17:46:15 -0700446 .setEthSrc(routerMac)
sangho80f11cb2015-04-01 13:05:26 -0700447 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800448
Charles Chan90772a72017-02-08 15:52:08 -0800449 // Create route meta
450 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800451
Charles Chan61c086d2019-07-26 17:46:15 -0700452 // Adjust treatment and meta according to VLAN configuration
Charles Chan90772a72017-02-08 15:52:08 -0800453 if (taggedVlans.contains(hostVlanId)) {
454 tbuilder.setVlanId(hostVlanId);
455 } else if (hostVlanId.equals(VlanId.NONE)) {
456 if (untaggedVlan != null) {
457 mbuilder.matchVlanId(untaggedVlan);
458 } else if (nativeVlan != null) {
459 mbuilder.matchVlanId(nativeVlan);
460 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700461 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
462 hostMac, hostVlanId, connectPoint);
463 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800464 }
465 } else {
Charles Chan61c086d2019-07-26 17:46:15 -0700466 // Double tagged hosts
467 if (innerVlan == null || outerTpid == null) {
468 log.warn("Failed to construct NextObj for double tagged hosts {}/{}. {} {}",
469 hostMac, hostVlanId,
470 (innerVlan == null) ? "innerVlan = null." : "",
471 (outerTpid == null) ? "outerTpid = null." : "");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700472 return null;
473 }
Charles Chan61c086d2019-07-26 17:46:15 -0700474 tbuilder.setVlanId(innerVlan);
475 tbuilder.pushVlan(outerTpid);
476 tbuilder.setVlanId(hostVlanId);
477 mbuilder.matchVlanId(VlanId.ANY);
Saurav Das07c74602016-04-27 18:35:50 -0700478 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000479
Charles Chan61c086d2019-07-26 17:46:15 -0700480 return ImmutablePair.of(tbuilder.build(), mbuilder.build());
sangho80f11cb2015-04-01 13:05:26 -0700481 }
482
483 /**
Saurav Das261c3002017-06-13 15:35:54 -0700484 * Populates IP flow rules for all the given prefixes reachable from the
485 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700486 *
Saurav Das261c3002017-06-13 15:35:54 -0700487 * @param targetSw switch where rules are to be programmed
488 * @param subnets subnets/prefixes being added
489 * @param destSw1 destination switch where the prefixes are reachable
490 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
491 * Should be null if there is no paired destination switch (by config)
492 * or if the given prefixes are reachable only via destSw1
493 * @param nextHops a map containing a set of next-hops for each destination switch.
494 * If destSw2 is not null, then this map must contain an
495 * entry for destSw2 with its next-hops from the targetSw
496 * (although the next-hop set may be empty in certain scenarios).
497 * If destSw2 is null, there should not be an entry in this
498 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700499 * @return true if all rules are set successfully, false otherwise
500 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700501 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700502 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
psneha86e60d32019-03-26 06:31:41 -0400503 // Get pair device of the target switch
504 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
505 // Route simplification will be off in case of the nexthop location at target switch is down
506 // (routing through spine case)
507 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
508 // Iterates over the routes
509 // If route simplification is enabled
510 // If the target device is another leaf in the network
511 if (srManager.routeSimplification && !routeSimplOff) {
512 for (IpPrefix subnet : subnets) {
513 // Skip route programming on the target device
514 // If route simplification applies
515 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
516 // XXX route simplification assumes that source of the traffic
517 // towards the nexthops are co-located with the nexthops. In different
518 // scenarios will not work properly.
519 continue;
520 }
521 // populate the route in the remaning scenarios
522 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
523 return false;
524 }
525 }
526 } else {
527 // Populate IP flow rules for all the subnets.
528 for (IpPrefix subnet : subnets) {
529 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
530 return false;
531 }
sangho80f11cb2015-04-01 13:05:26 -0700532 }
533 }
Charles Chanc22cef32016-04-29 14:38:22 -0700534 return true;
535 }
sangho80f11cb2015-04-01 13:05:26 -0700536
Charles Chanc22cef32016-04-29 14:38:22 -0700537 /**
Charles Chand66d6712018-03-29 16:03:41 -0700538 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700539 *
Charles Chand66d6712018-03-29 16:03:41 -0700540 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700541 * @param subnets subnet being removed
542 * @return true if all rules are removed successfully, false otherwise
543 */
Charles Chand66d6712018-03-29 16:03:41 -0700544 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700545 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700546 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700547 return false;
548 }
549 }
sangho80f11cb2015-04-01 13:05:26 -0700550 return true;
551 }
552
553 /**
Saurav Dase0237a32016-05-27 13:54:07 -0700554 * Populates IP flow rules for an IP prefix in the target device. The prefix
Saurav Das261c3002017-06-13 15:35:54 -0700555 * is reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700556 *
Saurav Das261c3002017-06-13 15:35:54 -0700557 * @param targetSw target device ID to set the rules
558 * @param ipPrefix the IP prefix
559 * @param destSw1 destination switch where the prefixes are reachable
560 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
561 * Should be null if there is no paired destination switch (by config)
562 * or if the given prefixes are reachable only via destSw1
563 * @param nextHops map of destination switches and their next-hops.
564 * Should only contain destination switches that are
565 * actually meant to be routed to. If destSw2 is null, there
566 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700567 * @return true if all rules are set successfully, false otherwise
568 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700569 private boolean populateIpRuleForRouter(DeviceId targetSw,
Saurav Das261c3002017-06-13 15:35:54 -0700570 IpPrefix ipPrefix, DeviceId destSw1,
571 DeviceId destSw2,
572 Map<DeviceId, Set<DeviceId>> nextHops) {
573 int segmentId1, segmentId2 = -1;
Charles Chan319d1a22015-11-03 10:42:14 -0800574 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800575 if (ipPrefix.isIp4()) {
Saurav Das261c3002017-06-13 15:35:54 -0700576 segmentId1 = config.getIPv4SegmentId(destSw1);
577 if (destSw2 != null) {
578 segmentId2 = config.getIPv4SegmentId(destSw2);
579 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800580 } else {
Saurav Das261c3002017-06-13 15:35:54 -0700581 segmentId1 = config.getIPv6SegmentId(destSw1);
582 if (destSw2 != null) {
583 segmentId2 = config.getIPv6SegmentId(destSw2);
584 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800585 }
Charles Chan319d1a22015-11-03 10:42:14 -0800586 } catch (DeviceConfigNotFoundException e) {
587 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
588 return false;
589 }
sangho80f11cb2015-04-01 13:05:26 -0700590
Pier Ventreadb4ae62016-11-23 09:57:42 -0800591 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanf4586112015-11-09 16:37:23 -0800592 TrafficSelector selector = sbuilder.build();
sangho80f11cb2015-04-01 13:05:26 -0700593
Charles Chanf4586112015-11-09 16:37:23 -0800594 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das261c3002017-06-13 15:35:54 -0700595 DestinationSet ds;
Charles Chanf4586112015-11-09 16:37:23 -0800596 TrafficTreatment treatment;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700597 DestinationSet.DestinationSetType dsType;
sangho80f11cb2015-04-01 13:05:26 -0700598
Saurav Das261c3002017-06-13 15:35:54 -0700599 if (destSw2 == null) {
600 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800601 // If the next hop is the same as the final destination, then MPLS
602 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700603 Set<DeviceId> nhd1 = nextHops.get(destSw1);
604 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
605 tbuilder.immediate().decNwTtl();
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700606 ds = DestinationSet.createTypePushNone(destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700607 treatment = tbuilder.build();
608 } else {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700609 ds = DestinationSet.createTypePushBos(segmentId1, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700610 treatment = null;
611 }
612 } else {
613 // dst pair - IP rules for dst-pairs are always from other edge nodes
614 // the destination set needs to have both destinations, even if there
615 // are no next hops to one of them
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700616 ds = DestinationSet.createTypePushBos(segmentId1, destSw1, segmentId2, destSw2);
Charles Chanf4586112015-11-09 16:37:23 -0800617 treatment = null;
sangho80f11cb2015-04-01 13:05:26 -0700618 }
619
Saurav Das4c35fc42015-11-20 15:27:53 -0800620 // setup metadata to pass to nextObjective - indicate the vlan on egress
621 // if needed by the switch pipeline. Since neighbor sets are always to
622 // other neighboring routers, there is no subnet assigned on those ports.
623 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700624 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Saurav Das261c3002017-06-13 15:35:54 -0700625 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700626 if (grpHandler == null) {
627 log.warn("populateIPRuleForRouter: groupHandler for device {} "
Saurav Das261c3002017-06-13 15:35:54 -0700628 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700629 return false;
630 }
Saurav Das4c35fc42015-11-20 15:27:53 -0800631
Saurav Das261c3002017-06-13 15:35:54 -0700632 int nextId = grpHandler.getNextObjectiveId(ds, nextHops,
Saurav Das97241862018-02-14 14:14:54 -0800633 metabuilder.build(), false);
Saurav Das4c35fc42015-11-20 15:27:53 -0800634 if (nextId <= 0) {
Saurav Das261c3002017-06-13 15:35:54 -0700635 log.warn("No next objective in {} for ds: {}", targetSw, ds);
sangho2165d222015-05-01 09:38:25 -0700636 return false;
637 }
638
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700639 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
640 .builder()
641 .fromApp(srManager.appId)
642 .makePermanent()
Saurav Das4c35fc42015-11-20 15:27:53 -0800643 .nextStep(nextId)
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700644 .withSelector(selector)
Charles Chan82ab1932016-01-30 23:22:37 -0800645 .withPriority(getPriorityFromPrefix(ipPrefix))
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700646 .withFlag(ForwardingObjective.Flag.SPECIFIC);
Charles Chanf4586112015-11-09 16:37:23 -0800647 if (treatment != null) {
648 fwdBuilder.withTreatment(treatment);
649 }
Saurav Das62ae6792017-05-15 15:34:25 -0700650 log.debug("Installing IPv4 forwarding objective for router IP/subnet {} "
Saurav Das261c3002017-06-13 15:35:54 -0700651 + "in switch {} with nextId: {}", ipPrefix, targetSw, nextId);
Charles Chan1eaf4802016-04-18 13:44:03 -0700652 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Dase0237a32016-05-27 13:54:07 -0700653 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700654 ipPrefix, targetSw),
Charles Chan1eaf4802016-04-18 13:44:03 -0700655 (objective, error) ->
Saurav Dase0237a32016-05-27 13:54:07 -0700656 log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700657 ipPrefix, error, targetSw));
658 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
sanghofb7c7292015-04-13 15:15:58 -0700659 rulePopulationCounter.incrementAndGet();
sangho80f11cb2015-04-01 13:05:26 -0700660
661 return true;
662 }
663
sangho80f11cb2015-04-01 13:05:26 -0700664 /**
Charles Chand66d6712018-03-29 16:03:41 -0700665 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700666 *
Charles Chand66d6712018-03-29 16:03:41 -0700667 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700668 * @param ipPrefix the IP address of the destination router
669 * @return true if all rules are removed successfully, false otherwise
670 */
Charles Chand66d6712018-03-29 16:03:41 -0700671 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800672 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700673 TrafficSelector selector = sbuilder.build();
674 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
675
676 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
677 .builder()
678 .fromApp(srManager.appId)
679 .makePermanent()
680 .withSelector(selector)
681 .withTreatment(dummyTreatment)
682 .withPriority(getPriorityFromPrefix(ipPrefix))
683 .withFlag(ForwardingObjective.Flag.SPECIFIC);
684
Charles Chand66d6712018-03-29 16:03:41 -0700685 ObjectiveContext context = new DefaultObjectiveContext(
686 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
687 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
688 ipPrefix, targetSw, error));
689 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700690
691 return true;
692 }
693
694 /**
Saurav Das97241862018-02-14 14:14:54 -0800695 * Populates MPLS flow rules in the target device to point towards the
696 * destination device.
697 *
698 * @param targetSwId target device ID of the switch to set the rules
699 * @param destSwId destination switch device ID
700 * @param nextHops next hops switch ID list
701 * @param routerIp the router ip of the destination switch
702 * @return true if all rules are set successfully, false otherwise
703 */
704 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
705 Set<DeviceId> nextHops, IpAddress routerIp) {
706 int segmentId;
707 try {
708 if (routerIp.isIp4()) {
709 segmentId = config.getIPv4SegmentId(destSwId);
710 } else {
711 segmentId = config.getIPv6SegmentId(destSwId);
712 }
713 } catch (DeviceConfigNotFoundException e) {
714 log.warn(e.getMessage() + " Aborting populateMplsRule.");
715 return false;
716 }
717
718 List<ForwardingObjective> fwdObjs = new ArrayList<>();
719 Collection<ForwardingObjective> fwdObjsMpls;
720 // Generates the transit rules used by the standard "routing".
721 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
722 routerIp, true);
723 if (fwdObjsMpls.isEmpty()) {
724 return false;
725 }
726 fwdObjs.addAll(fwdObjsMpls);
727
728 // Generates the transit rules used by the MPLS Pwaas.
729 int pwSrLabel;
730 try {
731 pwSrLabel = config.getPWRoutingLabel(destSwId);
732 } catch (DeviceConfigNotFoundException e) {
733 log.warn(e.getMessage()
734 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
735 return false;
736 }
737 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
738 routerIp, false);
739 if (fwdObjsMpls.isEmpty()) {
740 return false;
741 }
742 fwdObjs.addAll(fwdObjsMpls);
743
744 for (ForwardingObjective fwdObj : fwdObjs) {
745 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
746 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
747 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
748 rulePopulationCounter.incrementAndGet();
749 }
750
751 return true;
752 }
753
754 /**
755 * Differentiates between popping and swapping labels when building an MPLS
756 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700757 *
758 * @param targetSwId the target sw
759 * @param destSwId the destination sw
760 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800761 * @param segmentId the segmentId to match representing the destination
762 * switch
763 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700764 * @return a collection of fwdobjective
765 */
Saurav Das261c3002017-06-13 15:35:54 -0700766 private Collection<ForwardingObjective> handleMpls(
767 DeviceId targetSwId,
768 DeviceId destSwId,
769 Set<DeviceId> nextHops,
770 int segmentId,
771 IpAddress routerIp,
772 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700773
774 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
775 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800776 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700777 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
778 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
779 sbuilder.matchMplsBos(isMplsBos);
780 TrafficSelector selector = sbuilder.build();
781
782 // setup metadata to pass to nextObjective - indicate the vlan on egress
783 // if needed by the switch pipeline. Since mpls next-hops are always to
784 // other neighboring routers, there is no subnet assigned on those ports.
785 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700786 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre229fd0b2016-10-31 16:49:19 -0700787
788 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
789 // If the next hop is the destination router for the segment, do pop
790 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700791 + "label {} in switch {} with pop to next-hops {}",
792 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700793 ForwardingObjective.Builder fwdObjNoBosBuilder =
794 getMplsForwardingObjective(targetSwId,
795 nextHops,
796 true,
797 isMplsBos,
798 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700799 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800800 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700801 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700802 // Error case, we cannot handle, exit.
803 if (fwdObjNoBosBuilder == null) {
804 return Collections.emptyList();
805 }
806 fwdObjBuilders.add(fwdObjNoBosBuilder);
807
808 } else {
Saurav Das97241862018-02-14 14:14:54 -0800809 // next hop is not destination, irrespective of the number of next
810 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700811 log.debug("Installing MPLS forwarding objective for "
812 + "label {} in switch {} without pop to next-hops {}",
813 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700814 ForwardingObjective.Builder fwdObjNoBosBuilder =
815 getMplsForwardingObjective(targetSwId,
816 nextHops,
817 false,
818 isMplsBos,
819 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700820 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800821 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700822 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700823 // Error case, we cannot handle, exit.
824 if (fwdObjNoBosBuilder == null) {
825 return Collections.emptyList();
826 }
827 fwdObjBuilders.add(fwdObjNoBosBuilder);
828
829 }
830
831 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
832 // We add the final property to the fwdObjs.
833 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700834 ((Builder) ((Builder) fwdObjBuilder
835 .fromApp(srManager.appId)
836 .makePermanent())
837 .withSelector(selector)
838 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
839 .withFlag(ForwardingObjective.Flag.SPECIFIC);
840
841 ObjectiveContext context = new DefaultObjectiveContext(
842 (objective) ->
843 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
844 objective.id(), segmentId, targetSwId),
845 (objective, error) ->
846 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
847 objective.id(), segmentId, error, targetSwId));
848
849 ForwardingObjective fob = fwdObjBuilder.add(context);
850 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700851 }
852
853 return fwdObjs;
854 }
855
856 /**
Saurav Das97241862018-02-14 14:14:54 -0800857 * Returns a Forwarding Objective builder for the MPLS rule that references
858 * the desired Next Objective. Creates a DestinationSet that allows the
859 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700860 *
Saurav Das97241862018-02-14 14:14:54 -0800861 * @param targetSw the target sw
862 * @param nextHops the set of next hops
863 * @param phpRequired true if penultimate-hop-popping is required
864 * @param isBos true if matched label is bottom-of-stack
865 * @param meta metadata for creating next objective
866 * @param routerIp the router ip representing the destination switch
867 * @param destSw the destination sw
868 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700869 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800870 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700871 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800872 Set<DeviceId> nextHops,
873 boolean phpRequired,
874 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800875 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700876 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800877 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700878 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800879
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700880 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
881 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700882
883 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800884 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700885 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800886 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700887 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800888 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700889 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700890 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700891 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800892 if (routerIp.isIp4()) {
893 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
894 } else {
895 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
896 }
897 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800898 // standard case -> BoS == True; pop results in IP packet and forwarding
899 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700900 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700901 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800902 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
903 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800904 // double-label case -> BoS == False, pop results in MPLS packet
905 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700906 ds = DestinationSet.createTypePopNotBos(destSw);
907 if (!srManager.getMplsEcmp()) {
908 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800909 }
sangho80f11cb2015-04-01 13:05:26 -0700910 }
911 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800912 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800913 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700914 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800915 // swap results in MPLS packet with same BoS bit regardless of bit value
916 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700917 // differentiate here between swap with not bos or swap with bos
918 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
919 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
920 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800921 simple = true;
922 }
sangho80f11cb2015-04-01 13:05:26 -0700923 }
924
Saurav Das4c35fc42015-11-20 15:27:53 -0800925 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800926 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
927 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700928 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
929 if (gh == null) {
930 log.warn("getNextObjectiveId query - groupHandler for device {} "
931 + "not found", targetSw);
932 return null;
933 }
Saurav Das97241862018-02-14 14:14:54 -0800934
Saurav Das261c3002017-06-13 15:35:54 -0700935 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
936 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800937 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800938 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800939 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800940 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700941 } else {
Saurav Das97241862018-02-14 14:14:54 -0800942 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
943 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -0700944 }
945
Saurav Das4c35fc42015-11-20 15:27:53 -0800946 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700947 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -0700948 }
949
950 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -0700951 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -0700952 * dstMac corresponding to the router's MAC address. For those pipelines
953 * that need to internally assign vlans to untagged packets, this method
954 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -0700955 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -0800956 * Note that the vlan assignment and filter programming should only be done by
957 * the master for a switch. This method is typically called at deviceAdd and
958 * programs filters only for the enabled ports of the device. For port-updates,
959 * that enable/disable ports after device add, singlePortFilter methods should
960 * be called.
sangho80f11cb2015-04-01 13:05:26 -0700961 *
Saurav Das9f1c42e2015-10-23 10:51:11 -0700962 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -0800963 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -0700964 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700965 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -0700966 log.debug("Installing per-port filtering objective for untagged "
967 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800968
Saurav Das07c74602016-04-27 18:35:50 -0700969 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -0800970 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -0700971 log.warn("Device {} ports not available. Unable to add MacVlan filters",
972 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -0800973 return null;
Saurav Das07c74602016-04-27 18:35:50 -0700974 }
Saurav Dasf9332192017-02-18 14:05:44 -0800975 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -0700976 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -0700977 if (!port.isEnabled()) {
978 disabledPorts++;
979 continue;
980 }
Charles Chan43be46b2017-02-26 22:59:35 -0800981 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -0800982 filteredPorts++;
983 } else {
984 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -0700985 }
Saurav Das7c305372015-10-28 12:39:42 -0700986 }
Charles Chan077314e2017-06-22 14:27:17 -0700987 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -0800988 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan9d2dd552018-06-19 20:56:33 -0700989 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Dasf9332192017-02-18 14:05:44 -0800990 }
991
992 /**
Charles Chan43be46b2017-02-26 22:59:35 -0800993 * Creates or removes filtering objectives for a single port. Should only be
994 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -0800995 *
996 * @param deviceId device identifier
997 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -0800998 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -0800999 * @return true if no errors occurred during the build of the filtering objective
1000 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001001 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -08001002 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -07001003 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
1004 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
1005 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -08001006
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001007 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -08001008 if (taggedVlans.size() != 0) {
1009 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -07001010 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan43be46b2017-02-26 22:59:35 -08001011 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan90772a72017-02-08 15:52:08 -08001012 return false;
1013 }
1014 if (nativeVlan != null) {
1015 // Filter for native vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001016 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001017 return false;
1018 }
1019 }
1020 } else if (untaggedVlan != null) {
1021 // Filter for untagged vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001022 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001023 return false;
1024 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001025 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001026 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das9bf49582018-08-13 15:34:26 -07001027 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1028 srManager.getDefaultInternalVlan(),
1029 install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001030 return false;
1031 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001032 // Filter for receiveing pseudowire traffic
Saurav Das9bf49582018-08-13 15:34:26 -07001033 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1034 srManager.getPwTransportVlan(),
1035 install)) {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001036 return false;
1037 }
Charles Chan90772a72017-02-08 15:52:08 -08001038 }
1039 return true;
1040 }
1041
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001042 /**
1043 * Updates filtering objectives for a single port. Should only be called by
1044 * the master for a switch
1045 * @param deviceId device identifier
1046 * @param portNum port identifier for port to be filtered
1047 * @param pushVlan true to push vlan, false otherwise
1048 * @param vlanId vlan identifier
1049 * @param install true to install the filtering objective, false to remove
1050 */
1051 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1052 boolean pushVlan, VlanId vlanId, boolean install) {
1053 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
1054 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1055 deviceId, portNum, vlanId);
1056 }
1057 }
1058
Charles Chan43be46b2017-02-26 22:59:35 -08001059 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1060 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001061 boolean doTMAC = true;
1062
1063 if (!pushVlan) {
1064 // Skip the tagged vlans belonging to an interface without an IP address
1065 Set<Interface> ifaces = srManager.interfaceService
1066 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1067 .stream()
1068 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1069 .collect(Collectors.toSet());
1070 if (!ifaces.isEmpty()) {
1071 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1072 vlanId, deviceId, portnum);
1073 doTMAC = false;
1074 }
1075 }
1076
1077 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Dasf9332192017-02-18 14:05:44 -08001078 if (fob == null) {
1079 // error encountered during build
1080 return false;
1081 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001082 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001083 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001084 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001085 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001086 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001087 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001088 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001089 if (install) {
1090 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1091 } else {
1092 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001093 }
Charles Chan90772a72017-02-08 15:52:08 -08001094 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001095 }
1096
Charles Chan90772a72017-02-08 15:52:08 -08001097 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001098 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Dasf9332192017-02-18 14:05:44 -08001099 MacAddress deviceMac;
1100 try {
1101 deviceMac = config.getDeviceMac(deviceId);
1102 } catch (DeviceConfigNotFoundException e) {
1103 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1104 return null;
1105 }
Saurav Dasf9332192017-02-18 14:05:44 -08001106 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001107
1108 if (doTMAC) {
1109 fob.withKey(Criteria.matchInPort(portnum))
1110 .addCondition(Criteria.matchEthDst(deviceMac))
1111 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1112 } else {
1113 fob.withKey(Criteria.matchInPort(portnum))
1114 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1115 }
Charles Chan90772a72017-02-08 15:52:08 -08001116
Charles Chan17ca2202017-12-19 19:55:57 -08001117 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1118
Charles Chan90772a72017-02-08 15:52:08 -08001119 if (pushVlan) {
1120 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001121 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001122 } else {
1123 fob.addCondition(Criteria.matchVlanId(vlanId));
1124 }
1125
Charles Chan17ca2202017-12-19 19:55:57 -08001126 // NOTE: Some switch hardware share the same filtering flow among different ports.
1127 // We use this metadata to let the driver know that there is no more enabled port
1128 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001129 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001130 tBuilder.wipeDeferred();
1131 }
1132
1133 fob.withMeta(tBuilder.build());
1134
Saurav Dasf9332192017-02-18 14:05:44 -08001135 fob.permit().fromApp(srManager.appId);
1136 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001137 }
1138
1139 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001140 * Creates or removes filtering objectives for a double-tagged host on a port.
1141 *
1142 * @param deviceId device identifier
1143 * @param portNum port identifier for port to be filtered
1144 * @param outerVlan outer VLAN ID
1145 * @param innerVlan inner VLAN ID
1146 * @param install true to install the filtering objective, false to remove
1147 */
1148 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1149 VlanId innerVlan, boolean install) {
Daniele Moro8fc37b42019-10-29 18:48:35 -07001150 // We should trigger the removal of double tagged rules only when removing
1151 // the filtering objective and no other hosts are connected to the same device port.
1152 boolean cleanupDoubleTaggedRules = srManager.hostService
1153 .getConnectedHosts(new ConnectPoint(deviceId, portNum)).size() == 0 && !install;
1154 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum,
1155 outerVlan, innerVlan,
1156 cleanupDoubleTaggedRules);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001157 if (fob == null) {
1158 // error encountered during build
1159 return;
1160 }
1161 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1162 install ? "Installing" : "Removing", deviceId, portNum);
1163 ObjectiveContext context = new DefaultObjectiveContext(
1164 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1165 install ? "installed" : "removed"),
1166 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1167 install ? "install" : "remove", deviceId, portNum, error));
1168 if (install) {
1169 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1170 } else {
1171 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1172 }
1173 }
1174
1175 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001176 VlanId outerVlan, VlanId innerVlan,
1177 boolean cleanupDoubleTaggedRules) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001178 MacAddress deviceMac;
1179 try {
1180 deviceMac = config.getDeviceMac(deviceId);
1181 } catch (DeviceConfigNotFoundException e) {
1182 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1183 return null;
1184 }
1185 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1186 // Outer vlan id match should be appeared before inner vlan id match.
1187 fob.withKey(Criteria.matchInPort(portNum))
1188 .addCondition(Criteria.matchEthDst(deviceMac))
1189 .addCondition(Criteria.matchVlanId(outerVlan))
Daniele Moro998f2df2019-07-12 17:58:54 -07001190 .addCondition(Criteria.matchInnerVlanId(innerVlan))
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001191 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1192
1193 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1194 // Pop outer vlan
1195 tBuilder.popVlan();
1196
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001197 // special metadata for driver
1198 if (cleanupDoubleTaggedRules) {
1199 tBuilder.writeMetadata(CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES, DOUBLE_TAGGED_METADATA_MASK);
1200 } else {
1201 tBuilder.writeMetadata(0, DOUBLE_TAGGED_METADATA_MASK);
1202 }
1203
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001204 // NOTE: Some switch hardware share the same filtering flow among different ports.
1205 // We use this metadata to let the driver know that there is no more enabled port
1206 // within the same VLAN on this device.
1207 if (noMoreEnabledPort(deviceId, outerVlan)) {
1208 tBuilder.wipeDeferred();
1209 }
1210
1211 fob.withMeta(tBuilder.build());
1212
1213 fob.permit().fromApp(srManager.appId);
1214 return fob;
1215 }
1216
1217 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001218 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001219 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001220 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001221 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001222 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001223 * @param deviceId the switch dpid for the router
sangho80f11cb2015-04-01 13:05:26 -07001224 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001225 void populateIpPunts(DeviceId deviceId) {
Saurav Das261c3002017-06-13 15:35:54 -07001226 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001227 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001228 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001229 routerIpv4 = config.getRouterIpv4(deviceId);
1230 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001231 routerLinkLocalIpv6 = Ip6Address.valueOf(
1232 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1233
Saurav Das261c3002017-06-13 15:35:54 -07001234 if (config.isPairedEdge(deviceId)) {
1235 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1236 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1237 }
Charles Chan319d1a22015-11-03 10:42:14 -08001238 } catch (DeviceConfigNotFoundException e) {
Charles Chan18fa4252017-02-08 16:10:40 -08001239 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001240 return;
1241 }
1242
Saurav Dasc28b3432015-10-30 17:45:38 -07001243 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1244 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1245 deviceId);
1246 return;
1247 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001248 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1249 allIps.add(routerIpv4);
1250 if (routerIpv6 != null) {
1251 allIps.add(routerIpv6);
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001252 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001253 }
Saurav Das261c3002017-06-13 15:35:54 -07001254 if (pairRouterIpv4 != null) {
1255 allIps.add(pairRouterIpv4);
1256 }
1257 if (pairRouterIpv6 != null) {
1258 allIps.add(pairRouterIpv6);
1259 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001260 for (IpAddress ipaddr : allIps) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001261 populateSingleIpPunts(deviceId, ipaddr);
1262 }
1263 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001264
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001265 /**
1266 * Creates a forwarding objective to punt all IP packets, destined to the
1267 * specified IP address, which should be router's port IP address.
1268 *
1269 * @param deviceId the switch dpid for the router
1270 * @param ipAddress the IP address of the router's port
1271 */
1272 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1273 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1274 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1275
1276 srManager.packetService.requestPackets(sbuilder.build(),
1277 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1278 }
1279
1280 /**
1281 * Removes a forwarding objective to punt all IP packets, destined to the
1282 * specified IP address, which should be router's port IP address.
1283 *
1284 * @param deviceId the switch dpid for the router
1285 * @param ipAddress the IP address of the router's port
1286 */
1287 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1288 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1289 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1290
1291 try {
1292 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1293 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1294 srManager.packetService.cancelPackets(sbuilder.build(),
1295 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1296 }
1297 } catch (DeviceConfigNotFoundException e) {
1298 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das9f1c42e2015-10-23 10:51:11 -07001299 }
sangho80f11cb2015-04-01 13:05:26 -07001300 }
1301
Charles Chanf4586112015-11-09 16:37:23 -08001302 /**
Pier Ventreadb4ae62016-11-23 09:57:42 -08001303 * Method to build IPv4 or IPv6 selector.
1304 *
1305 * @param addressToMatch the address to match
1306 */
1307 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1308 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1309 }
1310
1311 /**
1312 * Method to build IPv4 or IPv6 selector.
1313 *
1314 * @param prefixToMatch the prefix to match
1315 */
1316 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1317 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001318 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001319 if (prefixToMatch.isIp4()) {
1320 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1321 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1322 return selectorBuilder;
1323 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001324 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001325 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1326 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1327 return selectorBuilder;
1328 }
1329
1330 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001331 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1332 * Furthermore, these are applied only by the master instance. Deferred actions
1333 * are not cleared such that packets can be flooded in the cross connect use case
1334 *
1335 * @param deviceId the switch dpid for the router
1336 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001337 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001338 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001339 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1340 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1341 deviceId);
1342 return;
1343 }
1344
Charles Chan3ed34d82017-06-22 18:03:14 -07001345 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001346 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001347 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001348 .add(new ObjectiveContext() {
1349 @Override
1350 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001351 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001352 deviceId, error);
1353 }
1354 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001355 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001356
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001357 if (isIpv6Configured(deviceId)) {
1358 // We punt all NDP packets towards the controller.
1359 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1360 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1361 @Override
1362 public void onError(Objective objective, ObjectiveError error) {
1363 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1364 deviceId, error);
1365 }
1366 });
1367 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan051490d2018-01-11 11:48:18 -08001368 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001369 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001370
Saurav Dasec683dc2018-04-27 18:42:30 -07001371 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001372 ForwardingObjective pairFwdObj;
1373 // Do not punt ARP packets from pair port
1374 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1375 .add(new ObjectiveContext() {
1376 @Override
1377 public void onError(Objective objective, ObjectiveError error) {
1378 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1379 deviceId, error);
1380 }
1381 });
1382 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1383
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001384 if (isIpv6Configured(deviceId)) {
1385 // Do not punt NDP packets from pair port
1386 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1387 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan3ed34d82017-06-22 18:03:14 -07001388 @Override
1389 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001390 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan3ed34d82017-06-22 18:03:14 -07001391 deviceId, error);
1392 }
1393 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001394 srManager.flowObjectiveService.forward(deviceId, obj);
1395 });
1396
1397 // Do not forward DAD packets from pair port
1398 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1399 .add(new ObjectiveContext() {
1400 @Override
1401 public void onError(Objective objective, ObjectiveError error) {
1402 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1403 deviceId, error);
1404 }
1405 });
1406 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1407 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001408 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001409 }
1410
Charles Chan3ed34d82017-06-22 18:03:14 -07001411 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1412 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001413 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001414 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001415 .withSelector(selector)
1416 .fromApp(srManager.appId)
1417 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001418 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001419 .makePermanent();
1420 }
1421
Charles Chan3ed34d82017-06-22 18:03:14 -07001422 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001423 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1424 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001425 if (port != null) {
1426 sBuilder.matchInPort(port);
1427 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001428
Charles Chan3ed34d82017-06-22 18:03:14 -07001429 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1430 if (punt) {
1431 tBuilder.punt();
1432 }
1433 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001434 }
1435
Charles Chan051490d2018-01-11 11:48:18 -08001436 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1437 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001438
Charles Chan051490d2018-01-11 11:48:18 -08001439 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1440 .forEach(type -> {
1441 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1442 sBuilder.matchEthType(TYPE_IPV6)
1443 .matchIPProtocol(PROTOCOL_ICMP6)
1444 .matchIcmpv6Type(type);
1445 if (port != null) {
1446 sBuilder.matchInPort(port);
1447 }
1448
1449 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1450 if (punt) {
1451 tBuilder.punt();
1452 }
1453
1454 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1455 });
1456
1457 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001458 }
1459
1460 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1461 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1462 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001463 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1464 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1465 // .matchIPProtocol(PROTOCOL_ICMP6)
1466 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001467 if (port != null) {
1468 sBuilder.matchInPort(port);
1469 }
1470
1471 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1472 tBuilder.wipeDeferred();
1473 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001474 }
1475
1476 /**
Charles Chan155ec442018-09-16 14:30:19 -07001477 * Block given prefix in routing table.
Charles Chanf4586112015-11-09 16:37:23 -08001478 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001479 * @param address the address to block
1480 * @param deviceId switch ID to set the rules
1481 */
1482 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1483 updateDefaultRouteBlackhole(deviceId, address, true);
1484 }
1485
1486 /**
Charles Chan155ec442018-09-16 14:30:19 -07001487 * Unblock given prefix in routing table.
Andrea Campanella60ce2222018-04-30 11:48:55 +02001488 *
1489 * @param address the address to block
1490 * @param deviceId switch ID to set the rules
1491 */
1492 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1493 updateDefaultRouteBlackhole(deviceId, address, false);
1494 }
1495
1496 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1497 try {
1498 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1499
1500 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1501 if (address.isIp4()) {
1502 sbuilder.matchIPDst(address);
1503 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1504 } else {
1505 sbuilder.matchIPv6Dst(address);
1506 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1507 }
1508
1509 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
Andrea Campanella60ce2222018-04-30 11:48:55 +02001510 tBuilder.wipeDeferred();
1511
1512 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1513 fob.withFlag(Flag.SPECIFIC)
1514 .withSelector(sbuilder.build())
1515 .withTreatment(tBuilder.build())
1516 .withPriority(getPriorityFromPrefix(address))
1517 .fromApp(srManager.appId)
1518 .makePermanent();
1519
1520 log.debug("{} blackhole forwarding objectives for dev: {}",
1521 install ? "Installing" : "Removing", deviceId);
1522 ObjectiveContext context = new DefaultObjectiveContext(
1523 (objective) -> log.debug("Forward for {} {}", deviceId,
1524 install ? "installed" : "removed"),
1525 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1526 install ? "install" : "remove", deviceId, error));
1527 if (install) {
1528 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1529 } else {
1530 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1531 }
1532 }
1533 } catch (DeviceConfigNotFoundException e) {
1534 log.info("Not populating blackhole for un-configured device {}", deviceId);
1535 }
1536
1537 }
1538
1539 /**
1540 * Populates a forwarding objective to send packets that miss other high
1541 * priority Bridging Table entries to a group that contains all ports of
1542 * its subnet.
1543 *
Charles Chanf4586112015-11-09 16:37:23 -08001544 * @param deviceId switch ID to set the rules
1545 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001546 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001547 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001548 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001549 });
1550 }
1551
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001552 /**
1553 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1554 * @param deviceId switch ID to set the rule
1555 * @param vlanId vlan ID to specify the subnet
1556 * @param install true to install the rule, false to revoke the rule
1557 */
1558 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1559 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1560
1561 if (nextId < 0) {
1562 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1563 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1564 return;
1565 }
1566
1567 // Driver should treat objective with MacAddress.NONE as the
1568 // subnet broadcast rule
1569 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1570 sbuilder.matchVlanId(vlanId);
1571 sbuilder.matchEthDst(MacAddress.NONE);
1572
1573 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1574 fob.withFlag(Flag.SPECIFIC)
1575 .withSelector(sbuilder.build())
1576 .nextStep(nextId)
1577 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1578 .fromApp(srManager.appId)
1579 .makePermanent();
1580 ObjectiveContext context = new DefaultObjectiveContext(
1581 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1582 (objective, error) ->
1583 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1584
1585 if (install) {
1586 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1587 } else {
1588 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1589 }
1590 }
1591
Charles Chan82ab1932016-01-30 23:22:37 -08001592 private int getPriorityFromPrefix(IpPrefix prefix) {
1593 return (prefix.isIp4()) ?
1594 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1595 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001596 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001597
1598 /**
1599 * Update Forwarding objective for each host and IP address connected to given port.
1600 * And create corresponding Simple Next objective if it does not exist.
1601 * Applied only when populating Forwarding objective
1602 * @param deviceId switch ID to set the rule
1603 * @param portNumber port number
1604 * @param prefix IP prefix of the route
1605 * @param hostMac MAC address of the next hop
1606 * @param vlanId Vlan ID of the port
1607 * @param popVlan true to pop vlan tag in TrafficTreatment
1608 * @param install true to populate the forwarding objective, false to revoke
1609 */
1610 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1611 VlanId vlanId, boolean popVlan, boolean install) {
1612 ForwardingObjective.Builder fob;
1613 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1614 MacAddress deviceMac;
1615 try {
1616 deviceMac = config.getDeviceMac(deviceId);
1617 } catch (DeviceConfigNotFoundException e) {
1618 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1619 return;
1620 }
1621
1622 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1623 tbuilder.deferred()
1624 .setEthDst(hostMac)
1625 .setEthSrc(deviceMac)
1626 .setOutput(portNumber);
1627
1628 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1629
1630 if (!popVlan) {
1631 tbuilder.setVlanId(vlanId);
1632 } else {
1633 mbuilder.matchVlanId(vlanId);
1634 }
1635
1636 // if the objective is to revoke an existing rule, and for some reason
1637 // the next-objective does not exist, then a new one should not be created
1638 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1639 tbuilder.build(), mbuilder.build(), install);
1640 if (portNextObjId == -1) {
1641 // Warning log will come from getPortNextObjective method
1642 return;
1643 }
1644
1645 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1646 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1647 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1648
1649 ObjectiveContext context = new DefaultObjectiveContext(
1650 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1651 (objective, error) ->
1652 log.warn("Failed to {} IP rule for route {}: {}",
1653 install ? "install" : "revoke", prefix, error));
1654 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1655
1656 if (!install) {
1657 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1658 if (grpHandler == null) {
1659 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1660 } else {
1661 // Remove L3UG for the given port and host
1662 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1663 }
1664 }
1665 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001666
1667 /**
1668 * Checks if there is other enabled port within the given VLAN on the given device.
1669 *
1670 * @param deviceId device ID
1671 * @param vlanId VLAN ID
1672 * @return true if there is no more port enabled within the given VLAN on the given device
1673 */
1674 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1675 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1676 .filter(Port::isEnabled)
1677 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1678 .collect(Collectors.toSet());
1679
1680 return enabledPorts.stream().noneMatch(cp ->
1681 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001682 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001683 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001684 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Saurav Das9bf49582018-08-13 15:34:26 -07001685 vlanId.equals(srManager.getDefaultInternalVlan())) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001686 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1687 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1688 );
1689 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001690
1691 /**
1692 * Returns a forwarding objective builder for egress forwarding rules.
1693 * <p>
1694 * The forwarding objective installs flow rules to egress pipeline to push
1695 * two vlan headers with given inner, outer vlan ids and outer tpid.
1696 *
1697 * @param portNumber port where the next hop attaches to
1698 * @param dummyVlanId vlan ID of the packet to match
1699 * @param innerVlan inner vlan ID of the next hop
1700 * @param outerVlan outer vlan ID of the next hop
1701 * @param outerTpid outer TPID of the next hop
1702 * @return forwarding objective builder
1703 */
1704 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1705 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1706 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1707 sbuilder.matchVlanId(dummyVlanId);
1708 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1709 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1710
1711 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1712 tbuilder.pushVlan(outerTpid);
1713 } else {
1714 tbuilder.pushVlan();
1715 }
1716
1717 tbuilder.setVlanId(outerVlan);
1718 return DefaultForwardingObjective.builder()
1719 .withSelector(sbuilder.build())
1720 .withTreatment(tbuilder.build())
1721 .fromApp(srManager.appId)
1722 .makePermanent()
1723 .withPriority(DEFAULT_PRIORITY)
1724 .withFlag(ForwardingObjective.Flag.EGRESS);
1725 }
1726
1727 /**
1728 * Populates IP rules for a route that has double-tagged next hop.
1729 *
1730 * @param deviceId device ID of the device that next hop attaches to
1731 * @param prefix IP prefix of the route
1732 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001733 * @param innerVlan inner Vlan ID of the next hop
1734 * @param outerVlan outer Vlan ID of the next hop
1735 * @param outerTpid outer TPID of the next hop
1736 * @param outPort port where the next hop attaches to
1737 */
Charles Chan61c086d2019-07-26 17:46:15 -07001738 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001739 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1740 ForwardingObjective.Builder fwdBuilder;
1741 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1742 prefix, deviceId, outPort);
1743
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001744 try {
Charles Chan61c086d2019-07-26 17:46:15 -07001745 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1746 true, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001747 } catch (DeviceConfigNotFoundException e) {
1748 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1749 return;
1750 }
1751 if (fwdBuilder == null) {
1752 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1753 deviceId, prefix);
1754 return;
1755 }
1756
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001757 int nextId = fwdBuilder.add().nextId();
1758 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1759 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001760 }, (objective, error) ->
1761 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1762 );
1763 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1764 rulePopulationCounter.incrementAndGet();
1765 }
1766
1767 /**
1768 * Revokes IP rules for a route that has double-tagged next hop.
1769 *
1770 * @param deviceId device ID of the device that next hop attaches to
1771 * @param prefix IP prefix of the route
1772 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001773 * @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,
Charles Chan61c086d2019-07-26 17:46:15 -07001779 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1780 ForwardingObjective.Builder fwdBuilder;
1781 log.debug("Revoking direct routing entry for double-tagged host route {} at {}:{}",
1782 prefix, deviceId, outPort);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001783
Charles Chan61c086d2019-07-26 17:46:15 -07001784 try {
1785 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1786 true, true);
1787 } catch (DeviceConfigNotFoundException e) {
1788 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001789 return;
1790 }
Charles Chan61c086d2019-07-26 17:46:15 -07001791 if (fwdBuilder == null) {
1792 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1793 deviceId, prefix);
1794 return;
1795 }
1796
1797 int nextId = fwdBuilder.remove().nextId();
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001798 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
Charles Chan61c086d2019-07-26 17:46:15 -07001799 log.debug("Direct routing rule for double-tagged host route {} revoked. nextId={}", prefix, nextId);
1800
1801 // Try to remove next objective as well
1802 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta;
1803 try {
1804 treatmentAndMeta = getTreatmentAndMeta(deviceId, hostMac, outerVlan, outPort, innerVlan, outerTpid);
1805 } catch (DeviceConfigNotFoundException e) {
1806 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
1807 return;
1808 }
1809
1810 if (treatmentAndMeta == null) {
1811 // Warning log will come from getTreatmentAndMeta method
1812 return;
1813 }
1814
1815 DefaultGroupHandler groupHandler = srManager.getGroupHandler(deviceId);
1816 if (groupHandler == null) {
1817 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: " +
1818 "group handler not found for {}", prefix, deviceId);
1819 return;
1820 }
1821 groupHandler.removeGroupFromPort(outPort, treatmentAndMeta.getLeft(), treatmentAndMeta.getRight());
1822
1823 }, (objective, error) ->
1824 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: {}", prefix, error)
1825 );
1826 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001827 }
1828
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001829 /**
1830 * Checks whether the specified port has IP configuration or not.
1831 *
1832 * @param cp ConnectPoint to check the existance of IP configuration
1833 * @return true if the port has IP configuration; false otherwise.
1834 */
1835 private boolean hasIPConfiguration(ConnectPoint cp) {
1836 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1837 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1838 }
Saurav Das9bf49582018-08-13 15:34:26 -07001839
1840 /**
1841 * Updates filtering rules for unconfigured ports on all devices for which
1842 * this controller instance is master.
1843 *
1844 * @param pushVlan true if the filtering rule requires a push vlan action
1845 * @param oldVlanId the vlanId to be removed
1846 * @param newVlanId the vlanId to be added
1847 */
1848 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1849 VlanId newVlanId) {
1850 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1851 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1852 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1853 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1854 && p.isEnabled()) {
1855 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1856 oldVlanId, false);
1857 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1858 newVlanId, true);
1859 }
1860 }
1861 }
1862 }
1863 }
1864
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001865 private boolean isIpv6Configured(DeviceId deviceId) {
1866 boolean isIpv6Configured;
1867 try {
1868 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1869 } catch (DeviceConfigNotFoundException e) {
1870 isIpv6Configured = false;
1871 }
1872 return isIpv6Configured;
1873 }
sangho80f11cb2015-04-01 13:05:26 -07001874}