blob: 77103f126976dd722a270590fce74a6f0f5b3bb2 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Pier Ventre229fd0b2016-10-31 16:49:19 -070018import com.google.common.collect.Lists;
Charles Chan051490d2018-01-11 11:48:18 -080019import com.google.common.collect.Sets;
Saurav Das4c35fc42015-11-20 15:27:53 -080020import org.onlab.packet.EthType;
sangho80f11cb2015-04-01 13:05:26 -070021import org.onlab.packet.Ethernet;
Charles Chanef8d12e2017-12-05 21:07:38 -080022import org.onlab.packet.IPv6;
sangho80f11cb2015-04-01 13:05:26 -070023import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080024import org.onlab.packet.Ip6Address;
25import org.onlab.packet.IpAddress;
sangho80f11cb2015-04-01 13:05:26 -070026import org.onlab.packet.IpPrefix;
27import org.onlab.packet.MacAddress;
sangho80f11cb2015-04-01 13:05:26 -070028import org.onlab.packet.MplsLabel;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070029import org.onlab.packet.VlanId;
Charles Chanb7f75ac2016-01-11 18:28:54 -080030import org.onosproject.net.ConnectPoint;
Charles Chan1eaf4802016-04-18 13:44:03 -070031import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080032import org.onosproject.net.flowobjective.Objective;
Charles Chan1eaf4802016-04-18 13:44:03 -070033import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080034import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -070035import org.onosproject.net.intf.Interface;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080036import org.onosproject.net.packet.PacketPriority;
Saurav Dasd1872b02016-12-02 15:43:47 -080037import org.onosproject.segmentrouting.DefaultRoutingHandler.PortFilterInfo;
Charles Chan319d1a22015-11-03 10:42:14 -080038import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
39import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070040import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070041import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sangho80f11cb2015-04-01 13:05:26 -070042import org.onosproject.net.DeviceId;
Saurav Das7c305372015-10-28 12:39:42 -070043import org.onosproject.net.Port;
sangho80f11cb2015-04-01 13:05:26 -070044import org.onosproject.net.PortNumber;
sangho80f11cb2015-04-01 13:05:26 -070045import org.onosproject.net.flow.DefaultTrafficSelector;
46import org.onosproject.net.flow.DefaultTrafficTreatment;
sangho80f11cb2015-04-01 13:05:26 -070047import org.onosproject.net.flow.TrafficSelector;
48import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070049import org.onosproject.net.flow.criteria.Criteria;
50import org.onosproject.net.flowobjective.DefaultFilteringObjective;
51import org.onosproject.net.flowobjective.DefaultForwardingObjective;
52import org.onosproject.net.flowobjective.FilteringObjective;
53import org.onosproject.net.flowobjective.ForwardingObjective;
54import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
Saurav Das9f1c42e2015-10-23 10:51:11 -070055import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070056import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
sangho80f11cb2015-04-01 13:05:26 -070057import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
60import java.util.ArrayList;
Pier Ventre229fd0b2016-10-31 16:49:19 -070061import java.util.Collection;
62import java.util.Collections;
Saurav Das261c3002017-06-13 15:35:54 -070063import java.util.HashMap;
Saurav Dasc28b3432015-10-30 17:45:38 -070064import java.util.HashSet;
sangho80f11cb2015-04-01 13:05:26 -070065import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070066import java.util.Map;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080067import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070068import java.util.Set;
sanghofb7c7292015-04-13 15:15:58 -070069import java.util.concurrent.atomic.AtomicLong;
Charles Chanf17f66b2018-02-26 21:33:25 -080070import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -070071
72import static com.google.common.base.Preconditions.checkNotNull;
Pier Luigib9632ba2017-01-12 18:14:58 -080073import static org.onlab.packet.Ethernet.TYPE_ARP;
74import static org.onlab.packet.Ethernet.TYPE_IPV6;
Charles Chan051490d2018-01-11 11:48:18 -080075import static org.onlab.packet.ICMP6.NEIGHBOR_ADVERTISEMENT;
Pier Luigib9632ba2017-01-12 18:14:58 -080076import static org.onlab.packet.ICMP6.NEIGHBOR_SOLICITATION;
Charles Chan051490d2018-01-11 11:48:18 -080077import static org.onlab.packet.ICMP6.ROUTER_ADVERTISEMENT;
78import static org.onlab.packet.ICMP6.ROUTER_SOLICITATION;
Pier Luigib9632ba2017-01-12 18:14:58 -080079import static org.onlab.packet.IPv6.PROTOCOL_ICMP6;
Charles Chan10b0fb72017-02-02 16:20:42 -080080import static org.onosproject.segmentrouting.SegmentRoutingManager.INTERNAL_VLAN;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070081import static org.onosproject.segmentrouting.SegmentRoutingService.DEFAULT_PRIORITY;
sangho80f11cb2015-04-01 13:05:26 -070082
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -070083import static org.onosproject.segmentrouting.SegmentRoutingManager.PSEUDOWIRE_VLAN;
84
Charles Chanb7f75ac2016-01-11 18:28:54 -080085/**
86 * Populator of segment routing flow rules.
87 */
sangho80f11cb2015-04-01 13:05:26 -070088public class RoutingRulePopulator {
Charles Chanef8d12e2017-12-05 21:07:38 -080089 private static final Logger log = LoggerFactory.getLogger(RoutingRulePopulator.class);
90
91 private static final int ARP_NDP_PRIORITY = 30000;
sangho80f11cb2015-04-01 13:05:26 -070092
sanghofb7c7292015-04-13 15:15:58 -070093 private AtomicLong rulePopulationCounter;
sangho9b169e32015-04-14 16:27:13 -070094 private SegmentRoutingManager srManager;
95 private DeviceConfiguration config;
Saurav Das9f1c42e2015-10-23 10:51:11 -070096
sangho80f11cb2015-04-01 13:05:26 -070097 /**
98 * Creates a RoutingRulePopulator object.
99 *
Thomas Vachuska8a075092015-04-15 18:20:08 -0700100 * @param srManager segment routing manager reference
sangho80f11cb2015-04-01 13:05:26 -0700101 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700102 RoutingRulePopulator(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700103 this.srManager = srManager;
sangho9b169e32015-04-14 16:27:13 -0700104 this.config = checkNotNull(srManager.deviceConfiguration);
sanghofb7c7292015-04-13 15:15:58 -0700105 this.rulePopulationCounter = new AtomicLong(0);
106 }
107
108 /**
109 * Resets the population counter.
110 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700111 void resetCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700112 rulePopulationCounter.set(0);
113 }
114
115 /**
116 * Returns the number of rules populated.
Thomas Vachuska7cfc6202015-04-30 18:13:25 -0700117 *
118 * @return number of rules
sanghofb7c7292015-04-13 15:15:58 -0700119 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700120 long getCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700121 return rulePopulationCounter.get();
sangho80f11cb2015-04-01 13:05:26 -0700122 }
123
124 /**
Charles Chand66d6712018-03-29 16:03:41 -0700125 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
126 * output to given port.
127 *
128 * @param deviceId device ID
129 * @param port port
130 * @param mac mac address
131 * @param vlanId VLAN ID
132 */
133 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
134 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
135 if (fob == null) {
136 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
137 return;
138 }
139
140 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700141 (objective) -> log.debug("Brigding rule for {}/{} populated", mac, vlanId),
142 (objective, error) -> log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700143 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
144 }
145
146 /**
147 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
148 * output to given port.
149 *
150 * @param deviceId device ID
151 * @param port port
152 * @param mac mac address
153 * @param vlanId VLAN ID
154 */
155 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
156 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
157 if (fob == null) {
158 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
159 return;
160 }
161
162 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700163 (objective) -> log.debug("Brigding rule for {}/{} revoked", mac, vlanId),
164 (objective, error) -> log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700165 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
166 }
167
168 /**
169 * Generates a forwarding objective builder for bridging rules.
170 * <p>
171 * The forwarding objective bridges packets destined to a given MAC to
172 * given port on given device.
173 *
174 * @param deviceId Device that host attaches to
175 * @param mac MAC address of the host
176 * @param hostVlanId VLAN ID of the host
177 * @param outport Port that host attaches to
178 * @param revoke true if forwarding objective is meant to revoke forwarding rule
179 * @return Forwarding objective builder
180 */
181 private ForwardingObjective.Builder bridgingFwdObjBuilder(
182 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
183 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan098ca202018-05-01 11:50:20 -0700184 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
185 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
186 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chand66d6712018-03-29 16:03:41 -0700187
188 // Create host selector
189 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
190 sbuilder.matchEthDst(mac);
191
192 // Create host treatment
193 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
194 tbuilder.immediate().setOutput(outport);
195
196 // Create host meta
197 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
198
199 // Adjust the selector, treatment and meta according to VLAN configuration
200 if (taggedVlans.contains(hostVlanId)) {
201 sbuilder.matchVlanId(hostVlanId);
202 mbuilder.matchVlanId(hostVlanId);
203 } else if (hostVlanId.equals(VlanId.NONE)) {
204 if (untaggedVlan != null) {
205 sbuilder.matchVlanId(untaggedVlan);
206 mbuilder.matchVlanId(untaggedVlan);
207 tbuilder.immediate().popVlan();
208 } else if (nativeVlan != null) {
209 sbuilder.matchVlanId(nativeVlan);
210 mbuilder.matchVlanId(nativeVlan);
211 tbuilder.immediate().popVlan();
212 } else {
213 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
214 "vlan config", mac, hostVlanId, connectPoint);
215 return null;
216 }
217 } else {
218 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
219 mac, hostVlanId, connectPoint);
220 return null;
221 }
222
223 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
224 // If the objective is to revoke an existing rule, and for some reason
225 // the next-objective does not exist, then a new one should not be created
226 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
227 tbuilder.build(), mbuilder.build(), !revoke);
228 if (portNextObjId == -1) {
229 // Warning log will come from getPortNextObjective method
230 return null;
231 }
232
233 return DefaultForwardingObjective.builder()
234 .withFlag(ForwardingObjective.Flag.SPECIFIC)
235 .withSelector(sbuilder.build())
236 .nextStep(portNextObjId)
237 .withPriority(100)
238 .fromApp(srManager.appId)
239 .makePermanent();
240 }
241
242 /**
243 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
244 * and hostMAC connected to given port, and output to given port only when
245 * vlan information is valid.
246 *
247 * @param deviceId device ID that host attaches to
248 * @param portNum port number that host attaches to
249 * @param hostMac mac address of the host connected to the switch port
250 * @param vlanId Vlan ID configured on the switch port
251 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
252 * @param install true to populate the objective, false to revoke
253 */
254 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
255 // revokeBridging and bridgingFwdObjBuilder.
256 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
257 VlanId vlanId, boolean popVlan, boolean install) {
258 // Create host selector
259 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
260 sbuilder.matchEthDst(hostMac);
261
262 // Create host meta
263 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
264
265 sbuilder.matchVlanId(vlanId);
266 mbuilder.matchVlanId(vlanId);
267
268 // Create host treatment
269 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
270 tbuilder.immediate().setOutput(portNum);
271
272 if (popVlan) {
273 tbuilder.immediate().popVlan();
274 }
275
276 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
277 tbuilder.build(), mbuilder.build(), install);
278 if (portNextObjId != -1) {
279 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
280 .withFlag(ForwardingObjective.Flag.SPECIFIC)
281 .withSelector(sbuilder.build())
282 .nextStep(portNextObjId)
283 .withPriority(100)
284 .fromApp(srManager.appId)
285 .makePermanent();
286
287 ObjectiveContext context = new DefaultObjectiveContext(
288 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
289 install ? "populated" : "revoked"),
290 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
291 install ? "populate" : "revoke", hostMac, vlanId, error));
292 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
293 } else {
294 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
295 }
296 }
297
298 /**
299 * Populates IP rules for a route that has direct connection to the switch.
300 * This method should not be invoked directly without going through DefaultRoutingHandler.
sangho80f11cb2015-04-01 13:05:26 -0700301 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700302 * @param deviceId device ID of the device that next hop attaches to
303 * @param prefix IP prefix of the route
304 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800305 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700306 * @param outPort port where the next hop attaches to
sangho80f11cb2015-04-01 13:05:26 -0700307 */
Charles Chan910be6a2017-08-23 14:46:43 -0700308 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan90772a72017-02-08 15:52:08 -0800309 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Saurav Das261c3002017-06-13 15:35:54 -0700310 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chanddac7fd2016-10-27 14:19:48 -0700311 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800312 ForwardingObjective.Builder fwdBuilder;
Charles Chan319d1a22015-11-03 10:42:14 -0800313 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700314 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
315 hostVlanId, outPort, false);
Charles Chan319d1a22015-11-03 10:42:14 -0800316 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -0700317 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan319d1a22015-11-03 10:42:14 -0800318 return;
319 }
Saurav Das07c74602016-04-27 18:35:50 -0700320 if (fwdBuilder == null) {
Saurav Das368cf212017-03-15 15:15:14 -0700321 log.warn("Aborting host routing table entry due "
Charles Chanddac7fd2016-10-27 14:19:48 -0700322 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das07c74602016-04-27 18:35:50 -0700323 return;
324 }
Charles Chan910be6a2017-08-23 14:46:43 -0700325
326 int nextId = fwdBuilder.add().nextId();
Charles Chan1eaf4802016-04-18 13:44:03 -0700327 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan910be6a2017-08-23 14:46:43 -0700328 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
329 prefix, nextId),
Charles Chan1eaf4802016-04-18 13:44:03 -0700330 (objective, error) ->
Saurav Das261c3002017-06-13 15:35:54 -0700331 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das368cf212017-03-15 15:15:14 -0700332 prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700333 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chanf4586112015-11-09 16:37:23 -0800334 rulePopulationCounter.incrementAndGet();
335 }
336
Charles Chanb7f75ac2016-01-11 18:28:54 -0800337 /**
Charles Chanddac7fd2016-10-27 14:19:48 -0700338 * Removes IP rules for a route when the next hop is gone.
Charles Chand66d6712018-03-29 16:03:41 -0700339 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800340 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700341 * @param deviceId device ID of the device that next hop attaches to
342 * @param prefix IP prefix of the route
343 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800344 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700345 * @param outPort port that next hop attaches to
Charles Chanb7f75ac2016-01-11 18:28:54 -0800346 */
Charles Chan910be6a2017-08-23 14:46:43 -0700347 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan90772a72017-02-08 15:52:08 -0800348 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Charles Chanddac7fd2016-10-27 14:19:48 -0700349 log.debug("Revoke IP table entry for route {} at {}:{}",
350 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800351 ForwardingObjective.Builder fwdBuilder;
352 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700353 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
354 hostVlanId, outPort, true);
Charles Chanf4586112015-11-09 16:37:23 -0800355 } catch (DeviceConfigNotFoundException e) {
356 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
357 return;
358 }
Charles Chanea702b12016-11-30 11:55:05 -0800359 if (fwdBuilder == null) {
360 log.warn("Aborting host routing table entries due "
361 + "to error for dev:{} route:{}", deviceId, prefix);
362 return;
363 }
Charles Chan1eaf4802016-04-18 13:44:03 -0700364 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chanddac7fd2016-10-27 14:19:48 -0700365 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chan1eaf4802016-04-18 13:44:03 -0700366 (objective, error) ->
Charles Chanddac7fd2016-10-27 14:19:48 -0700367 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700368 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chanf4586112015-11-09 16:37:23 -0800369 }
370
Charles Chanddac7fd2016-10-27 14:19:48 -0700371 /**
Charles Chan18fa4252017-02-08 16:10:40 -0800372 * Returns a forwarding objective builder for routing rules.
373 * <p>
374 * The forwarding objective routes packets destined to a given prefix to
375 * given port on given device with given destination MAC.
Charles Chanddac7fd2016-10-27 14:19:48 -0700376 *
377 * @param deviceId device ID
378 * @param prefix prefix that need to be routed
379 * @param hostMac MAC address of the nexthop
Charles Chan90772a72017-02-08 15:52:08 -0800380 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700381 * @param outPort port where the nexthop attaches to
Saurav Das2cb38292017-03-29 19:09:17 -0700382 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Charles Chanddac7fd2016-10-27 14:19:48 -0700383 * @return forwarding objective builder
384 * @throws DeviceConfigNotFoundException if given device is not configured
385 */
Charles Chan18fa4252017-02-08 16:10:40 -0800386 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700387 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700388 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
389 boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800390 throws DeviceConfigNotFoundException {
391 MacAddress deviceMac;
392 deviceMac = config.getDeviceMac(deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800393
Charles Chan90772a72017-02-08 15:52:08 -0800394 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700395 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
396 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
397 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700398
Charles Chan90772a72017-02-08 15:52:08 -0800399 // Create route selector
400 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
401
402 // Create route treatment
Charles Chanddac7fd2016-10-27 14:19:48 -0700403 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho27462c62015-05-14 00:39:53 -0700404 tbuilder.deferred()
405 .setEthDst(hostMac)
Charles Chan319d1a22015-11-03 10:42:14 -0800406 .setEthSrc(deviceMac)
sangho80f11cb2015-04-01 13:05:26 -0700407 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800408
Charles Chan90772a72017-02-08 15:52:08 -0800409 // Create route meta
410 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800411
Charles Chan90772a72017-02-08 15:52:08 -0800412 // Adjust the meta according to VLAN configuration
413 if (taggedVlans.contains(hostVlanId)) {
414 tbuilder.setVlanId(hostVlanId);
415 } else if (hostVlanId.equals(VlanId.NONE)) {
416 if (untaggedVlan != null) {
417 mbuilder.matchVlanId(untaggedVlan);
418 } else if (nativeVlan != null) {
419 mbuilder.matchVlanId(nativeVlan);
420 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700421 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
422 hostMac, hostVlanId, connectPoint);
423 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800424 }
425 } else {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700426 // Internally-assigned dummy VLAN id will be given as hostVlanId
427 // when destination is double-tagged.
428 VlanId vlanId = srManager.dummyVlanIdStore().get(
429 new DummyVlanIdStoreKey(connectPoint, prefix.address()));
430 if (vlanId != null && vlanId.equals(hostVlanId)) {
431 tbuilder.setVlanId(hostVlanId);
432 mbuilder.matchVlanId(VlanId.ANY);
433 } else {
434 log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
435 + " in tagged vlan", hostMac, hostVlanId, connectPoint);
436 return null;
437 }
Saurav Das07c74602016-04-27 18:35:50 -0700438 }
Saurav Das2cb38292017-03-29 19:09:17 -0700439 // if the objective is to revoke an existing rule, and for some reason
440 // the next-objective does not exist, then a new one should not be created
Charles Chan90772a72017-02-08 15:52:08 -0800441 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
Saurav Das2cb38292017-03-29 19:09:17 -0700442 tbuilder.build(), mbuilder.build(), !revoke);
Charles Chan90772a72017-02-08 15:52:08 -0800443 if (portNextObjId == -1) {
444 // Warning log will come from getPortNextObjective method
445 return null;
446 }
447
Charles Chanf4586112015-11-09 16:37:23 -0800448 return DefaultForwardingObjective.builder()
Charles Chan90772a72017-02-08 15:52:08 -0800449 .withSelector(sbuilder.build())
Saurav Das2d94d312015-11-24 23:21:05 -0800450 .nextStep(portNextObjId)
Charles Chanf4586112015-11-09 16:37:23 -0800451 .fromApp(srManager.appId).makePermanent()
Charles Chanddac7fd2016-10-27 14:19:48 -0700452 .withPriority(getPriorityFromPrefix(prefix))
Charles Chan82ab1932016-01-30 23:22:37 -0800453 .withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700454 }
455
456 /**
Saurav Das261c3002017-06-13 15:35:54 -0700457 * Populates IP flow rules for all the given prefixes reachable from the
458 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700459 *
Saurav Das261c3002017-06-13 15:35:54 -0700460 * @param targetSw switch where rules are to be programmed
461 * @param subnets subnets/prefixes being added
462 * @param destSw1 destination switch where the prefixes are reachable
463 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
464 * Should be null if there is no paired destination switch (by config)
465 * or if the given prefixes are reachable only via destSw1
466 * @param nextHops a map containing a set of next-hops for each destination switch.
467 * If destSw2 is not null, then this map must contain an
468 * entry for destSw2 with its next-hops from the targetSw
469 * (although the next-hop set may be empty in certain scenarios).
470 * If destSw2 is null, there should not be an entry in this
471 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700472 * @return true if all rules are set successfully, false otherwise
473 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700474 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700475 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700476 for (IpPrefix subnet : subnets) {
Saurav Das261c3002017-06-13 15:35:54 -0700477 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
sangho80f11cb2015-04-01 13:05:26 -0700478 return false;
479 }
480 }
Charles Chanc22cef32016-04-29 14:38:22 -0700481 return true;
482 }
sangho80f11cb2015-04-01 13:05:26 -0700483
Charles Chanc22cef32016-04-29 14:38:22 -0700484 /**
Charles Chand66d6712018-03-29 16:03:41 -0700485 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700486 *
Charles Chand66d6712018-03-29 16:03:41 -0700487 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700488 * @param subnets subnet being removed
489 * @return true if all rules are removed successfully, false otherwise
490 */
Charles Chand66d6712018-03-29 16:03:41 -0700491 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700492 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700493 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700494 return false;
495 }
496 }
sangho80f11cb2015-04-01 13:05:26 -0700497 return true;
498 }
499
500 /**
Saurav Dase0237a32016-05-27 13:54:07 -0700501 * Populates IP flow rules for an IP prefix in the target device. The prefix
Saurav Das261c3002017-06-13 15:35:54 -0700502 * is reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700503 *
Saurav Das261c3002017-06-13 15:35:54 -0700504 * @param targetSw target device ID to set the rules
505 * @param ipPrefix the IP prefix
506 * @param destSw1 destination switch where the prefixes are reachable
507 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
508 * Should be null if there is no paired destination switch (by config)
509 * or if the given prefixes are reachable only via destSw1
510 * @param nextHops map of destination switches and their next-hops.
511 * Should only contain destination switches that are
512 * actually meant to be routed to. If destSw2 is null, there
513 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700514 * @return true if all rules are set successfully, false otherwise
515 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700516 private boolean populateIpRuleForRouter(DeviceId targetSw,
Saurav Das261c3002017-06-13 15:35:54 -0700517 IpPrefix ipPrefix, DeviceId destSw1,
518 DeviceId destSw2,
519 Map<DeviceId, Set<DeviceId>> nextHops) {
520 int segmentId1, segmentId2 = -1;
Charles Chan319d1a22015-11-03 10:42:14 -0800521 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800522 if (ipPrefix.isIp4()) {
Saurav Das261c3002017-06-13 15:35:54 -0700523 segmentId1 = config.getIPv4SegmentId(destSw1);
524 if (destSw2 != null) {
525 segmentId2 = config.getIPv4SegmentId(destSw2);
526 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800527 } else {
Saurav Das261c3002017-06-13 15:35:54 -0700528 segmentId1 = config.getIPv6SegmentId(destSw1);
529 if (destSw2 != null) {
530 segmentId2 = config.getIPv6SegmentId(destSw2);
531 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800532 }
Charles Chan319d1a22015-11-03 10:42:14 -0800533 } catch (DeviceConfigNotFoundException e) {
534 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
535 return false;
536 }
sangho80f11cb2015-04-01 13:05:26 -0700537
Pier Ventreadb4ae62016-11-23 09:57:42 -0800538 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanf4586112015-11-09 16:37:23 -0800539 TrafficSelector selector = sbuilder.build();
sangho80f11cb2015-04-01 13:05:26 -0700540
Charles Chanf4586112015-11-09 16:37:23 -0800541 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das261c3002017-06-13 15:35:54 -0700542 DestinationSet ds;
Charles Chanf4586112015-11-09 16:37:23 -0800543 TrafficTreatment treatment;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700544 DestinationSet.DestinationSetType dsType;
sangho80f11cb2015-04-01 13:05:26 -0700545
Saurav Das261c3002017-06-13 15:35:54 -0700546 if (destSw2 == null) {
547 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800548 // If the next hop is the same as the final destination, then MPLS
549 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700550 Set<DeviceId> nhd1 = nextHops.get(destSw1);
551 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
552 tbuilder.immediate().decNwTtl();
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700553 ds = DestinationSet.createTypePushNone(destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700554 treatment = tbuilder.build();
555 } else {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700556 ds = DestinationSet.createTypePushBos(segmentId1, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700557 treatment = null;
558 }
559 } else {
560 // dst pair - IP rules for dst-pairs are always from other edge nodes
561 // the destination set needs to have both destinations, even if there
562 // are no next hops to one of them
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700563 ds = DestinationSet.createTypePushBos(segmentId1, destSw1, segmentId2, destSw2);
Charles Chanf4586112015-11-09 16:37:23 -0800564 treatment = null;
sangho80f11cb2015-04-01 13:05:26 -0700565 }
566
Saurav Das4c35fc42015-11-20 15:27:53 -0800567 // setup metadata to pass to nextObjective - indicate the vlan on egress
568 // if needed by the switch pipeline. Since neighbor sets are always to
569 // other neighboring routers, there is no subnet assigned on those ports.
570 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Charles Chan10b0fb72017-02-02 16:20:42 -0800571 metabuilder.matchVlanId(SegmentRoutingManager.INTERNAL_VLAN);
Saurav Das261c3002017-06-13 15:35:54 -0700572 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700573 if (grpHandler == null) {
574 log.warn("populateIPRuleForRouter: groupHandler for device {} "
Saurav Das261c3002017-06-13 15:35:54 -0700575 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700576 return false;
577 }
Saurav Das4c35fc42015-11-20 15:27:53 -0800578
Saurav Das261c3002017-06-13 15:35:54 -0700579 int nextId = grpHandler.getNextObjectiveId(ds, nextHops,
Saurav Das97241862018-02-14 14:14:54 -0800580 metabuilder.build(), false);
Saurav Das4c35fc42015-11-20 15:27:53 -0800581 if (nextId <= 0) {
Saurav Das261c3002017-06-13 15:35:54 -0700582 log.warn("No next objective in {} for ds: {}", targetSw, ds);
sangho2165d222015-05-01 09:38:25 -0700583 return false;
584 }
585
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700586 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
587 .builder()
588 .fromApp(srManager.appId)
589 .makePermanent()
Saurav Das4c35fc42015-11-20 15:27:53 -0800590 .nextStep(nextId)
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700591 .withSelector(selector)
Charles Chan82ab1932016-01-30 23:22:37 -0800592 .withPriority(getPriorityFromPrefix(ipPrefix))
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700593 .withFlag(ForwardingObjective.Flag.SPECIFIC);
Charles Chanf4586112015-11-09 16:37:23 -0800594 if (treatment != null) {
595 fwdBuilder.withTreatment(treatment);
596 }
Saurav Das62ae6792017-05-15 15:34:25 -0700597 log.debug("Installing IPv4 forwarding objective for router IP/subnet {} "
Saurav Das261c3002017-06-13 15:35:54 -0700598 + "in switch {} with nextId: {}", ipPrefix, targetSw, nextId);
Charles Chan1eaf4802016-04-18 13:44:03 -0700599 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Dase0237a32016-05-27 13:54:07 -0700600 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700601 ipPrefix, targetSw),
Charles Chan1eaf4802016-04-18 13:44:03 -0700602 (objective, error) ->
Saurav Dase0237a32016-05-27 13:54:07 -0700603 log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700604 ipPrefix, error, targetSw));
605 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
sanghofb7c7292015-04-13 15:15:58 -0700606 rulePopulationCounter.incrementAndGet();
sangho80f11cb2015-04-01 13:05:26 -0700607
608 return true;
609 }
610
sangho80f11cb2015-04-01 13:05:26 -0700611 /**
Charles Chand66d6712018-03-29 16:03:41 -0700612 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700613 *
Charles Chand66d6712018-03-29 16:03:41 -0700614 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700615 * @param ipPrefix the IP address of the destination router
616 * @return true if all rules are removed successfully, false otherwise
617 */
Charles Chand66d6712018-03-29 16:03:41 -0700618 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800619 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700620 TrafficSelector selector = sbuilder.build();
621 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
622
623 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
624 .builder()
625 .fromApp(srManager.appId)
626 .makePermanent()
627 .withSelector(selector)
628 .withTreatment(dummyTreatment)
629 .withPriority(getPriorityFromPrefix(ipPrefix))
630 .withFlag(ForwardingObjective.Flag.SPECIFIC);
631
Charles Chand66d6712018-03-29 16:03:41 -0700632 ObjectiveContext context = new DefaultObjectiveContext(
633 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
634 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
635 ipPrefix, targetSw, error));
636 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700637
638 return true;
639 }
640
641 /**
Saurav Das97241862018-02-14 14:14:54 -0800642 * Populates MPLS flow rules in the target device to point towards the
643 * destination device.
644 *
645 * @param targetSwId target device ID of the switch to set the rules
646 * @param destSwId destination switch device ID
647 * @param nextHops next hops switch ID list
648 * @param routerIp the router ip of the destination switch
649 * @return true if all rules are set successfully, false otherwise
650 */
651 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
652 Set<DeviceId> nextHops, IpAddress routerIp) {
653 int segmentId;
654 try {
655 if (routerIp.isIp4()) {
656 segmentId = config.getIPv4SegmentId(destSwId);
657 } else {
658 segmentId = config.getIPv6SegmentId(destSwId);
659 }
660 } catch (DeviceConfigNotFoundException e) {
661 log.warn(e.getMessage() + " Aborting populateMplsRule.");
662 return false;
663 }
664
665 List<ForwardingObjective> fwdObjs = new ArrayList<>();
666 Collection<ForwardingObjective> fwdObjsMpls;
667 // Generates the transit rules used by the standard "routing".
668 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
669 routerIp, true);
670 if (fwdObjsMpls.isEmpty()) {
671 return false;
672 }
673 fwdObjs.addAll(fwdObjsMpls);
674
675 // Generates the transit rules used by the MPLS Pwaas.
676 int pwSrLabel;
677 try {
678 pwSrLabel = config.getPWRoutingLabel(destSwId);
679 } catch (DeviceConfigNotFoundException e) {
680 log.warn(e.getMessage()
681 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
682 return false;
683 }
684 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
685 routerIp, false);
686 if (fwdObjsMpls.isEmpty()) {
687 return false;
688 }
689 fwdObjs.addAll(fwdObjsMpls);
690
691 for (ForwardingObjective fwdObj : fwdObjs) {
692 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
693 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
694 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
695 rulePopulationCounter.incrementAndGet();
696 }
697
698 return true;
699 }
700
701 /**
702 * Differentiates between popping and swapping labels when building an MPLS
703 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700704 *
705 * @param targetSwId the target sw
706 * @param destSwId the destination sw
707 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800708 * @param segmentId the segmentId to match representing the destination
709 * switch
710 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700711 * @return a collection of fwdobjective
712 */
Saurav Das261c3002017-06-13 15:35:54 -0700713 private Collection<ForwardingObjective> handleMpls(
714 DeviceId targetSwId,
715 DeviceId destSwId,
716 Set<DeviceId> nextHops,
717 int segmentId,
718 IpAddress routerIp,
719 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700720
721 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
722 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800723 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700724 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
725 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
726 sbuilder.matchMplsBos(isMplsBos);
727 TrafficSelector selector = sbuilder.build();
728
729 // setup metadata to pass to nextObjective - indicate the vlan on egress
730 // if needed by the switch pipeline. Since mpls next-hops are always to
731 // other neighboring routers, there is no subnet assigned on those ports.
732 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Charles Chan10b0fb72017-02-02 16:20:42 -0800733 metabuilder.matchVlanId(SegmentRoutingManager.INTERNAL_VLAN);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700734
735 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
736 // If the next hop is the destination router for the segment, do pop
737 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700738 + "label {} in switch {} with pop to next-hops {}",
739 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700740 ForwardingObjective.Builder fwdObjNoBosBuilder =
741 getMplsForwardingObjective(targetSwId,
742 nextHops,
743 true,
744 isMplsBos,
745 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700746 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800747 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700748 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700749 // Error case, we cannot handle, exit.
750 if (fwdObjNoBosBuilder == null) {
751 return Collections.emptyList();
752 }
753 fwdObjBuilders.add(fwdObjNoBosBuilder);
754
755 } else {
Saurav Das97241862018-02-14 14:14:54 -0800756 // next hop is not destination, irrespective of the number of next
757 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700758 log.debug("Installing MPLS forwarding objective for "
759 + "label {} in switch {} without pop to next-hops {}",
760 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700761 ForwardingObjective.Builder fwdObjNoBosBuilder =
762 getMplsForwardingObjective(targetSwId,
763 nextHops,
764 false,
765 isMplsBos,
766 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700767 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800768 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700769 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700770 // Error case, we cannot handle, exit.
771 if (fwdObjNoBosBuilder == null) {
772 return Collections.emptyList();
773 }
774 fwdObjBuilders.add(fwdObjNoBosBuilder);
775
776 }
777
778 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
779 // We add the final property to the fwdObjs.
780 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700781 ((Builder) ((Builder) fwdObjBuilder
782 .fromApp(srManager.appId)
783 .makePermanent())
784 .withSelector(selector)
785 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
786 .withFlag(ForwardingObjective.Flag.SPECIFIC);
787
788 ObjectiveContext context = new DefaultObjectiveContext(
789 (objective) ->
790 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
791 objective.id(), segmentId, targetSwId),
792 (objective, error) ->
793 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
794 objective.id(), segmentId, error, targetSwId));
795
796 ForwardingObjective fob = fwdObjBuilder.add(context);
797 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700798 }
799
800 return fwdObjs;
801 }
802
803 /**
Saurav Das97241862018-02-14 14:14:54 -0800804 * Returns a Forwarding Objective builder for the MPLS rule that references
805 * the desired Next Objective. Creates a DestinationSet that allows the
806 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700807 *
Saurav Das97241862018-02-14 14:14:54 -0800808 * @param targetSw the target sw
809 * @param nextHops the set of next hops
810 * @param phpRequired true if penultimate-hop-popping is required
811 * @param isBos true if matched label is bottom-of-stack
812 * @param meta metadata for creating next objective
813 * @param routerIp the router ip representing the destination switch
814 * @param destSw the destination sw
815 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700816 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800817 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700818 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800819 Set<DeviceId> nextHops,
820 boolean phpRequired,
821 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800822 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700823 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800824 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700825 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800826
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700827 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
828 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700829
830 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800831 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700832 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800833 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700834 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800835 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700836 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700837 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700838 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800839 if (routerIp.isIp4()) {
840 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
841 } else {
842 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
843 }
844 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800845 // standard case -> BoS == True; pop results in IP packet and forwarding
846 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700847 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700848 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800849 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
850 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800851 // double-label case -> BoS == False, pop results in MPLS packet
852 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700853 ds = DestinationSet.createTypePopNotBos(destSw);
854 if (!srManager.getMplsEcmp()) {
855 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800856 }
sangho80f11cb2015-04-01 13:05:26 -0700857 }
858 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800859 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800860 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700861 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800862 // swap results in MPLS packet with same BoS bit regardless of bit value
863 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700864 // differentiate here between swap with not bos or swap with bos
865 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
866 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
867 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800868 simple = true;
869 }
sangho80f11cb2015-04-01 13:05:26 -0700870 }
871
Saurav Das4c35fc42015-11-20 15:27:53 -0800872 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800873 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
874 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700875 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
876 if (gh == null) {
877 log.warn("getNextObjectiveId query - groupHandler for device {} "
878 + "not found", targetSw);
879 return null;
880 }
Saurav Das97241862018-02-14 14:14:54 -0800881
Saurav Das261c3002017-06-13 15:35:54 -0700882 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
883 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800884 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800885 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800886 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800887 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700888 } else {
Saurav Das97241862018-02-14 14:14:54 -0800889 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
890 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -0700891 }
892
Saurav Das4c35fc42015-11-20 15:27:53 -0800893 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700894 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -0700895 }
896
897 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -0700898 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -0700899 * dstMac corresponding to the router's MAC address. For those pipelines
900 * that need to internally assign vlans to untagged packets, this method
901 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -0700902 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -0800903 * Note that the vlan assignment and filter programming should only be done by
904 * the master for a switch. This method is typically called at deviceAdd and
905 * programs filters only for the enabled ports of the device. For port-updates,
906 * that enable/disable ports after device add, singlePortFilter methods should
907 * be called.
sangho80f11cb2015-04-01 13:05:26 -0700908 *
Saurav Das9f1c42e2015-10-23 10:51:11 -0700909 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -0800910 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -0700911 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700912 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -0700913 log.debug("Installing per-port filtering objective for untagged "
914 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800915
Saurav Das07c74602016-04-27 18:35:50 -0700916 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -0800917 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -0700918 log.warn("Device {} ports not available. Unable to add MacVlan filters",
919 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -0800920 return null;
Saurav Das07c74602016-04-27 18:35:50 -0700921 }
Saurav Dasf9332192017-02-18 14:05:44 -0800922 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -0700923 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -0700924 if (!port.isEnabled()) {
925 disabledPorts++;
926 continue;
927 }
Charles Chan43be46b2017-02-26 22:59:35 -0800928 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -0800929 filteredPorts++;
930 } else {
931 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -0700932 }
Saurav Das7c305372015-10-28 12:39:42 -0700933 }
Charles Chan077314e2017-06-22 14:27:17 -0700934 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -0800935 deviceId, disabledPorts, errorPorts, filteredPorts);
Saurav Dasd1872b02016-12-02 15:43:47 -0800936 return srManager.defaultRoutingHandler.new PortFilterInfo(disabledPorts,
Saurav Dasf9332192017-02-18 14:05:44 -0800937 errorPorts, filteredPorts);
938 }
939
940 /**
Charles Chan43be46b2017-02-26 22:59:35 -0800941 * Creates or removes filtering objectives for a single port. Should only be
942 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -0800943 *
944 * @param deviceId device identifier
945 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -0800946 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -0800947 * @return true if no errors occurred during the build of the filtering objective
948 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700949 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -0800950 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -0700951 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
952 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
953 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -0800954
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700955 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -0800956 if (taggedVlans.size() != 0) {
957 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -0700958 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan43be46b2017-02-26 22:59:35 -0800959 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan90772a72017-02-08 15:52:08 -0800960 return false;
961 }
962 if (nativeVlan != null) {
963 // Filter for native vlan
Charles Chan43be46b2017-02-26 22:59:35 -0800964 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -0800965 return false;
966 }
967 }
968 } else if (untaggedVlan != null) {
969 // Filter for untagged vlan
Charles Chan43be46b2017-02-26 22:59:35 -0800970 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -0800971 return false;
972 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -0700973 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700974 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Charles Chan43be46b2017-02-26 22:59:35 -0800975 if (!processSinglePortFiltersInternal(deviceId, portnum, true, INTERNAL_VLAN, install)) {
Charles Chan90772a72017-02-08 15:52:08 -0800976 return false;
977 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700978 // Filter for receiveing pseudowire traffic
979 if (!processSinglePortFiltersInternal(deviceId, portnum, false, PSEUDOWIRE_VLAN, install)) {
980 return false;
981 }
Charles Chan90772a72017-02-08 15:52:08 -0800982 }
983 return true;
984 }
985
Jonghwan Hyune5ef7622017-08-25 17:48:36 -0700986 /**
987 * Updates filtering objectives for a single port. Should only be called by
988 * the master for a switch
989 * @param deviceId device identifier
990 * @param portNum port identifier for port to be filtered
991 * @param pushVlan true to push vlan, false otherwise
992 * @param vlanId vlan identifier
993 * @param install true to install the filtering objective, false to remove
994 */
995 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
996 boolean pushVlan, VlanId vlanId, boolean install) {
997 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
998 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
999 deviceId, portNum, vlanId);
1000 }
1001 }
1002
Charles Chan43be46b2017-02-26 22:59:35 -08001003 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1004 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001005 boolean doTMAC = true;
1006
1007 if (!pushVlan) {
1008 // Skip the tagged vlans belonging to an interface without an IP address
1009 Set<Interface> ifaces = srManager.interfaceService
1010 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1011 .stream()
1012 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1013 .collect(Collectors.toSet());
1014 if (!ifaces.isEmpty()) {
1015 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1016 vlanId, deviceId, portnum);
1017 doTMAC = false;
1018 }
1019 }
1020
1021 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Dasf9332192017-02-18 14:05:44 -08001022 if (fob == null) {
1023 // error encountered during build
1024 return false;
1025 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001026 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001027 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001028 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001029 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001030 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001031 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001032 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001033 if (install) {
1034 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1035 } else {
1036 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001037 }
Charles Chan90772a72017-02-08 15:52:08 -08001038 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001039 }
1040
Charles Chan90772a72017-02-08 15:52:08 -08001041 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001042 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Dasf9332192017-02-18 14:05:44 -08001043 MacAddress deviceMac;
1044 try {
1045 deviceMac = config.getDeviceMac(deviceId);
1046 } catch (DeviceConfigNotFoundException e) {
1047 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1048 return null;
1049 }
Saurav Dasf9332192017-02-18 14:05:44 -08001050 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001051
1052 if (doTMAC) {
1053 fob.withKey(Criteria.matchInPort(portnum))
1054 .addCondition(Criteria.matchEthDst(deviceMac))
1055 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1056 } else {
1057 fob.withKey(Criteria.matchInPort(portnum))
1058 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1059 }
Charles Chan90772a72017-02-08 15:52:08 -08001060
Charles Chan17ca2202017-12-19 19:55:57 -08001061 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1062
Charles Chan90772a72017-02-08 15:52:08 -08001063 if (pushVlan) {
1064 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001065 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001066 } else {
1067 fob.addCondition(Criteria.matchVlanId(vlanId));
1068 }
1069
Charles Chan17ca2202017-12-19 19:55:57 -08001070 // NOTE: Some switch hardware share the same filtering flow among different ports.
1071 // We use this metadata to let the driver know that there is no more enabled port
1072 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001073 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001074 tBuilder.wipeDeferred();
1075 }
1076
1077 fob.withMeta(tBuilder.build());
1078
Saurav Dasf9332192017-02-18 14:05:44 -08001079 fob.permit().fromApp(srManager.appId);
1080 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001081 }
1082
1083 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001084 * Creates or removes filtering objectives for a double-tagged host on a port.
1085 *
1086 * @param deviceId device identifier
1087 * @param portNum port identifier for port to be filtered
1088 * @param outerVlan outer VLAN ID
1089 * @param innerVlan inner VLAN ID
1090 * @param install true to install the filtering objective, false to remove
1091 */
1092 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1093 VlanId innerVlan, boolean install) {
1094 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum, outerVlan, innerVlan);
1095 if (fob == null) {
1096 // error encountered during build
1097 return;
1098 }
1099 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1100 install ? "Installing" : "Removing", deviceId, portNum);
1101 ObjectiveContext context = new DefaultObjectiveContext(
1102 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1103 install ? "installed" : "removed"),
1104 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1105 install ? "install" : "remove", deviceId, portNum, error));
1106 if (install) {
1107 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1108 } else {
1109 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1110 }
1111 }
1112
1113 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
1114 VlanId outerVlan, VlanId innerVlan) {
1115 MacAddress deviceMac;
1116 try {
1117 deviceMac = config.getDeviceMac(deviceId);
1118 } catch (DeviceConfigNotFoundException e) {
1119 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1120 return null;
1121 }
1122 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1123 // Outer vlan id match should be appeared before inner vlan id match.
1124 fob.withKey(Criteria.matchInPort(portNum))
1125 .addCondition(Criteria.matchEthDst(deviceMac))
1126 .addCondition(Criteria.matchVlanId(outerVlan))
1127 .addCondition(Criteria.matchVlanId(innerVlan))
1128 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1129
1130 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1131 // Pop outer vlan
1132 tBuilder.popVlan();
1133
1134 // NOTE: Some switch hardware share the same filtering flow among different ports.
1135 // We use this metadata to let the driver know that there is no more enabled port
1136 // within the same VLAN on this device.
1137 if (noMoreEnabledPort(deviceId, outerVlan)) {
1138 tBuilder.wipeDeferred();
1139 }
1140
1141 fob.withMeta(tBuilder.build());
1142
1143 fob.permit().fromApp(srManager.appId);
1144 return fob;
1145 }
1146
1147 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001148 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001149 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001150 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001151 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001152 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001153 * @param deviceId the switch dpid for the router
sangho80f11cb2015-04-01 13:05:26 -07001154 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001155 void populateIpPunts(DeviceId deviceId) {
Saurav Das261c3002017-06-13 15:35:54 -07001156 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001157 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001158 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001159 routerIpv4 = config.getRouterIpv4(deviceId);
1160 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001161 routerLinkLocalIpv6 = Ip6Address.valueOf(
1162 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1163
Saurav Das261c3002017-06-13 15:35:54 -07001164 if (config.isPairedEdge(deviceId)) {
1165 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1166 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1167 }
Charles Chan319d1a22015-11-03 10:42:14 -08001168 } catch (DeviceConfigNotFoundException e) {
Charles Chan18fa4252017-02-08 16:10:40 -08001169 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001170 return;
1171 }
1172
Saurav Dasc28b3432015-10-30 17:45:38 -07001173 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1174 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1175 deviceId);
1176 return;
1177 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001178 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1179 allIps.add(routerIpv4);
Charles Chanef8d12e2017-12-05 21:07:38 -08001180 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001181 if (routerIpv6 != null) {
1182 allIps.add(routerIpv6);
1183 }
Saurav Das261c3002017-06-13 15:35:54 -07001184 if (pairRouterIpv4 != null) {
1185 allIps.add(pairRouterIpv4);
1186 }
1187 if (pairRouterIpv6 != null) {
1188 allIps.add(pairRouterIpv6);
1189 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001190 for (IpAddress ipaddr : allIps) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001191 populateSingleIpPunts(deviceId, ipaddr);
1192 }
1193 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001194
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001195 /**
1196 * Creates a forwarding objective to punt all IP packets, destined to the
1197 * specified IP address, which should be router's port IP address.
1198 *
1199 * @param deviceId the switch dpid for the router
1200 * @param ipAddress the IP address of the router's port
1201 */
1202 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1203 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1204 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1205
1206 srManager.packetService.requestPackets(sbuilder.build(),
1207 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1208 }
1209
1210 /**
1211 * Removes a forwarding objective to punt all IP packets, destined to the
1212 * specified IP address, which should be router's port IP address.
1213 *
1214 * @param deviceId the switch dpid for the router
1215 * @param ipAddress the IP address of the router's port
1216 */
1217 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1218 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1219 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1220
1221 try {
1222 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1223 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1224 srManager.packetService.cancelPackets(sbuilder.build(),
1225 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1226 }
1227 } catch (DeviceConfigNotFoundException e) {
1228 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das9f1c42e2015-10-23 10:51:11 -07001229 }
sangho80f11cb2015-04-01 13:05:26 -07001230 }
1231
Charles Chanf4586112015-11-09 16:37:23 -08001232 /**
Pier Ventreadb4ae62016-11-23 09:57:42 -08001233 * Method to build IPv4 or IPv6 selector.
1234 *
1235 * @param addressToMatch the address to match
1236 */
1237 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1238 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1239 }
1240
1241 /**
1242 * Method to build IPv4 or IPv6 selector.
1243 *
1244 * @param prefixToMatch the prefix to match
1245 */
1246 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1247 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001248 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001249 if (prefixToMatch.isIp4()) {
1250 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1251 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1252 return selectorBuilder;
1253 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001254 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001255 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1256 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1257 return selectorBuilder;
1258 }
1259
1260 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001261 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1262 * Furthermore, these are applied only by the master instance. Deferred actions
1263 * are not cleared such that packets can be flooded in the cross connect use case
1264 *
1265 * @param deviceId the switch dpid for the router
1266 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001267 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001268 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001269 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1270 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1271 deviceId);
1272 return;
1273 }
1274
Charles Chan3ed34d82017-06-22 18:03:14 -07001275 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001276 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001277 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001278 .add(new ObjectiveContext() {
1279 @Override
1280 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001281 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001282 deviceId, error);
1283 }
1284 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001285 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001286
Pier Luigib9632ba2017-01-12 18:14:58 -08001287 // We punt all NDP packets towards the controller.
Charles Chan051490d2018-01-11 11:48:18 -08001288 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1289 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1290 @Override
1291 public void onError(Objective objective, ObjectiveError error) {
1292 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1293 deviceId, error);
1294 }
1295 });
1296 srManager.flowObjectiveService.forward(deviceId, obj);
1297 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001298
Saurav Dasec683dc2018-04-27 18:42:30 -07001299 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001300 ForwardingObjective pairFwdObj;
1301 // Do not punt ARP packets from pair port
1302 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1303 .add(new ObjectiveContext() {
1304 @Override
1305 public void onError(Objective objective, ObjectiveError error) {
1306 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1307 deviceId, error);
1308 }
1309 });
1310 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1311
1312 // Do not punt NDP packets from pair port
Charles Chan051490d2018-01-11 11:48:18 -08001313 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1314 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1315 @Override
1316 public void onError(Objective objective, ObjectiveError error) {
1317 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1318 deviceId, error);
1319 }
1320 });
1321 srManager.flowObjectiveService.forward(deviceId, obj);
1322 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001323
1324 // Do not forward DAD packets from pair port
1325 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1326 .add(new ObjectiveContext() {
1327 @Override
1328 public void onError(Objective objective, ObjectiveError error) {
1329 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1330 deviceId, error);
1331 }
1332 });
1333 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1334 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001335 }
1336
Charles Chan3ed34d82017-06-22 18:03:14 -07001337 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1338 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001339 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001340 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001341 .withSelector(selector)
1342 .fromApp(srManager.appId)
1343 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001344 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001345 .makePermanent();
1346 }
1347
Charles Chan3ed34d82017-06-22 18:03:14 -07001348 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001349 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1350 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001351 if (port != null) {
1352 sBuilder.matchInPort(port);
1353 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001354
Charles Chan3ed34d82017-06-22 18:03:14 -07001355 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1356 if (punt) {
1357 tBuilder.punt();
1358 }
1359 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001360 }
1361
Charles Chan051490d2018-01-11 11:48:18 -08001362 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1363 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001364
Charles Chan051490d2018-01-11 11:48:18 -08001365 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1366 .forEach(type -> {
1367 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1368 sBuilder.matchEthType(TYPE_IPV6)
1369 .matchIPProtocol(PROTOCOL_ICMP6)
1370 .matchIcmpv6Type(type);
1371 if (port != null) {
1372 sBuilder.matchInPort(port);
1373 }
1374
1375 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1376 if (punt) {
1377 tBuilder.punt();
1378 }
1379
1380 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1381 });
1382
1383 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001384 }
1385
1386 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1387 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1388 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001389 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1390 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1391 // .matchIPProtocol(PROTOCOL_ICMP6)
1392 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001393 if (port != null) {
1394 sBuilder.matchInPort(port);
1395 }
1396
1397 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1398 tBuilder.wipeDeferred();
1399 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001400 }
1401
1402 /**
Charles Chanf4586112015-11-09 16:37:23 -08001403 * Populates a forwarding objective to send packets that miss other high
1404 * priority Bridging Table entries to a group that contains all ports of
1405 * its subnet.
1406 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001407 * @param address the address to block
1408 * @param deviceId switch ID to set the rules
1409 */
1410 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1411 updateDefaultRouteBlackhole(deviceId, address, true);
1412 }
1413
1414 /**
1415 * Populates a forwarding objective to send packets that miss other high
1416 * priority Bridging Table entries to a group that contains all ports of
1417 * its subnet.
1418 *
1419 * @param address the address to block
1420 * @param deviceId switch ID to set the rules
1421 */
1422 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1423 updateDefaultRouteBlackhole(deviceId, address, false);
1424 }
1425
1426 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1427 try {
1428 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1429
1430 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1431 if (address.isIp4()) {
1432 sbuilder.matchIPDst(address);
1433 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1434 } else {
1435 sbuilder.matchIPv6Dst(address);
1436 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1437 }
1438
1439 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1440
1441 tBuilder.transition(60);
1442 tBuilder.wipeDeferred();
1443
1444 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1445 fob.withFlag(Flag.SPECIFIC)
1446 .withSelector(sbuilder.build())
1447 .withTreatment(tBuilder.build())
1448 .withPriority(getPriorityFromPrefix(address))
1449 .fromApp(srManager.appId)
1450 .makePermanent();
1451
1452 log.debug("{} blackhole forwarding objectives for dev: {}",
1453 install ? "Installing" : "Removing", deviceId);
1454 ObjectiveContext context = new DefaultObjectiveContext(
1455 (objective) -> log.debug("Forward for {} {}", deviceId,
1456 install ? "installed" : "removed"),
1457 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1458 install ? "install" : "remove", deviceId, error));
1459 if (install) {
1460 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1461 } else {
1462 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1463 }
1464 }
1465 } catch (DeviceConfigNotFoundException e) {
1466 log.info("Not populating blackhole for un-configured device {}", deviceId);
1467 }
1468
1469 }
1470
1471 /**
1472 * Populates a forwarding objective to send packets that miss other high
1473 * priority Bridging Table entries to a group that contains all ports of
1474 * its subnet.
1475 *
Charles Chanf4586112015-11-09 16:37:23 -08001476 * @param deviceId switch ID to set the rules
1477 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001478 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001479 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001480 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001481 });
1482 }
1483
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001484 /**
1485 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1486 * @param deviceId switch ID to set the rule
1487 * @param vlanId vlan ID to specify the subnet
1488 * @param install true to install the rule, false to revoke the rule
1489 */
1490 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1491 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1492
1493 if (nextId < 0) {
1494 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1495 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1496 return;
1497 }
1498
1499 // Driver should treat objective with MacAddress.NONE as the
1500 // subnet broadcast rule
1501 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1502 sbuilder.matchVlanId(vlanId);
1503 sbuilder.matchEthDst(MacAddress.NONE);
1504
1505 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1506 fob.withFlag(Flag.SPECIFIC)
1507 .withSelector(sbuilder.build())
1508 .nextStep(nextId)
1509 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1510 .fromApp(srManager.appId)
1511 .makePermanent();
1512 ObjectiveContext context = new DefaultObjectiveContext(
1513 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1514 (objective, error) ->
1515 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1516
1517 if (install) {
1518 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1519 } else {
1520 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1521 }
1522 }
1523
Charles Chan82ab1932016-01-30 23:22:37 -08001524 private int getPriorityFromPrefix(IpPrefix prefix) {
1525 return (prefix.isIp4()) ?
1526 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1527 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001528 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001529
1530 /**
1531 * Update Forwarding objective for each host and IP address connected to given port.
1532 * And create corresponding Simple Next objective if it does not exist.
1533 * Applied only when populating Forwarding objective
1534 * @param deviceId switch ID to set the rule
1535 * @param portNumber port number
1536 * @param prefix IP prefix of the route
1537 * @param hostMac MAC address of the next hop
1538 * @param vlanId Vlan ID of the port
1539 * @param popVlan true to pop vlan tag in TrafficTreatment
1540 * @param install true to populate the forwarding objective, false to revoke
1541 */
1542 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1543 VlanId vlanId, boolean popVlan, boolean install) {
1544 ForwardingObjective.Builder fob;
1545 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1546 MacAddress deviceMac;
1547 try {
1548 deviceMac = config.getDeviceMac(deviceId);
1549 } catch (DeviceConfigNotFoundException e) {
1550 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1551 return;
1552 }
1553
1554 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1555 tbuilder.deferred()
1556 .setEthDst(hostMac)
1557 .setEthSrc(deviceMac)
1558 .setOutput(portNumber);
1559
1560 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1561
1562 if (!popVlan) {
1563 tbuilder.setVlanId(vlanId);
1564 } else {
1565 mbuilder.matchVlanId(vlanId);
1566 }
1567
1568 // if the objective is to revoke an existing rule, and for some reason
1569 // the next-objective does not exist, then a new one should not be created
1570 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1571 tbuilder.build(), mbuilder.build(), install);
1572 if (portNextObjId == -1) {
1573 // Warning log will come from getPortNextObjective method
1574 return;
1575 }
1576
1577 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1578 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1579 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1580
1581 ObjectiveContext context = new DefaultObjectiveContext(
1582 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1583 (objective, error) ->
1584 log.warn("Failed to {} IP rule for route {}: {}",
1585 install ? "install" : "revoke", prefix, error));
1586 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1587
1588 if (!install) {
1589 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1590 if (grpHandler == null) {
1591 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1592 } else {
1593 // Remove L3UG for the given port and host
1594 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1595 }
1596 }
1597 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001598
1599 /**
1600 * Checks if there is other enabled port within the given VLAN on the given device.
1601 *
1602 * @param deviceId device ID
1603 * @param vlanId VLAN ID
1604 * @return true if there is no more port enabled within the given VLAN on the given device
1605 */
1606 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1607 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1608 .filter(Port::isEnabled)
1609 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1610 .collect(Collectors.toSet());
1611
1612 return enabledPorts.stream().noneMatch(cp ->
1613 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001614 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001615 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001616 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Charles Chanf17f66b2018-02-26 21:33:25 -08001617 vlanId.equals(INTERNAL_VLAN)) ||
1618 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1619 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1620 );
1621 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001622
1623 /**
1624 * Returns a forwarding objective builder for egress forwarding rules.
1625 * <p>
1626 * The forwarding objective installs flow rules to egress pipeline to push
1627 * two vlan headers with given inner, outer vlan ids and outer tpid.
1628 *
1629 * @param portNumber port where the next hop attaches to
1630 * @param dummyVlanId vlan ID of the packet to match
1631 * @param innerVlan inner vlan ID of the next hop
1632 * @param outerVlan outer vlan ID of the next hop
1633 * @param outerTpid outer TPID of the next hop
1634 * @return forwarding objective builder
1635 */
1636 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1637 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1638 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1639 sbuilder.matchVlanId(dummyVlanId);
1640 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1641 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1642
1643 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1644 tbuilder.pushVlan(outerTpid);
1645 } else {
1646 tbuilder.pushVlan();
1647 }
1648
1649 tbuilder.setVlanId(outerVlan);
1650 return DefaultForwardingObjective.builder()
1651 .withSelector(sbuilder.build())
1652 .withTreatment(tbuilder.build())
1653 .fromApp(srManager.appId)
1654 .makePermanent()
1655 .withPriority(DEFAULT_PRIORITY)
1656 .withFlag(ForwardingObjective.Flag.EGRESS);
1657 }
1658
1659 /**
1660 * Populates IP rules for a route that has double-tagged next hop.
1661 *
1662 * @param deviceId device ID of the device that next hop attaches to
1663 * @param prefix IP prefix of the route
1664 * @param hostMac MAC address of the next hop
1665 * @param dummyVlan Dummy Vlan ID allocated for this route
1666 * @param innerVlan inner Vlan ID of the next hop
1667 * @param outerVlan outer Vlan ID of the next hop
1668 * @param outerTpid outer TPID of the next hop
1669 * @param outPort port where the next hop attaches to
1670 */
1671 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId dummyVlan,
1672 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1673 ForwardingObjective.Builder fwdBuilder;
1674 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1675 prefix, deviceId, outPort);
1676
1677 ForwardingObjective.Builder egressFwdBuilder = egressFwdObjBuilder(
1678 outPort, dummyVlan, innerVlan, outerVlan, outerTpid);
1679 DefaultObjectiveContext egressFwdContext = new DefaultObjectiveContext(
1680 objective -> log.debug("Egress rule for IP {} is populated", prefix.address()),
1681 (objective, error) -> {
1682 log.warn("Failed to populate egress rule for IP {}: {}", prefix.address(), error);
1683 srManager.dummyVlanIdStore().remove(new DummyVlanIdStoreKey(
1684 new ConnectPoint(deviceId, outPort), prefix.address()
1685 ));
1686 });
1687 try {
1688 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, dummyVlan, outPort, false);
1689 } catch (DeviceConfigNotFoundException e) {
1690 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1691 return;
1692 }
1693 if (fwdBuilder == null) {
1694 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1695 deviceId, prefix);
1696 return;
1697 }
1698
1699 // Egress forwarding objective should be installed after the nextObjective for the output port is installed.
1700 // Installation of routingFwdObj will ensure the installation of the nextObjective.
1701 int nextId = fwdBuilder.add().nextId();
1702 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1703 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
1704 srManager.flowObjectiveService.forward(deviceId, egressFwdBuilder.add(egressFwdContext));
1705 }, (objective, error) ->
1706 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1707 );
1708 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1709 rulePopulationCounter.incrementAndGet();
1710 }
1711
1712 /**
1713 * Revokes IP rules for a route that has double-tagged next hop.
1714 *
1715 * @param deviceId device ID of the device that next hop attaches to
1716 * @param prefix IP prefix of the route
1717 * @param hostMac MAC address of the next hop
1718 * @param hostVlan Vlan ID of the next hop
1719 * @param innerVlan inner Vlan ID of the next hop
1720 * @param outerVlan outer Vlan ID of the next hop
1721 * @param outerTpid outer TPID of the next hop
1722 * @param outPort port where the next hop attaches to
1723 */
1724 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
1725 VlanId hostVlan, VlanId innerVlan, VlanId outerVlan,
1726 EthType outerTpid, PortNumber outPort) {
1727 revokeRoute(deviceId, prefix, hostMac, hostVlan, outPort);
1728
1729 DummyVlanIdStoreKey key = new DummyVlanIdStoreKey(
1730 new ConnectPoint(deviceId, outPort), prefix.address());
1731 VlanId dummyVlanId = srManager.dummyVlanIdStore().get(key);
1732 if (dummyVlanId == null) {
1733 log.warn("Failed to retrieve dummy VLAN ID for {}/{} and {}",
1734 deviceId, outPort, prefix.address());
1735 return;
1736 }
1737 ForwardingObjective.Builder fob = egressFwdObjBuilder(
1738 outPort, dummyVlanId, innerVlan, outerVlan, outerTpid);
1739 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1740 log.debug("Egress rule for IP {} revoked", prefix.address());
1741 srManager.dummyVlanIdStore().remove(key);
1742 }, (objective, error) -> {
1743 log.warn("Failed to revoke egress rule for IP {}: {}", prefix.address(), error);
1744 });
1745 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1746 }
1747
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001748 /**
1749 * Checks whether the specified port has IP configuration or not.
1750 *
1751 * @param cp ConnectPoint to check the existance of IP configuration
1752 * @return true if the port has IP configuration; false otherwise.
1753 */
1754 private boolean hasIPConfiguration(ConnectPoint cp) {
1755 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1756 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1757 }
sangho80f11cb2015-04-01 13:05:26 -07001758}