blob: e4eafb5e9d8b9c6c9784fa93155849531278dac7 [file] [log] [blame]
Thomas Vachuska781d18b2014-10-27 10:31:25 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska781d18b2014-10-27 10:31:25 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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
Thomas Vachuska781d18b2014-10-27 10:31:25 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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.
Thomas Vachuska781d18b2014-10-27 10:31:25 -070015 */
Jonathan Hart335ef462014-10-16 08:20:46 -070016package org.onlab.onos.sdnip;
17
Pingping3855f312014-10-22 12:50:37 -070018import java.util.Collection;
19import java.util.HashMap;
20import java.util.HashSet;
21import java.util.Iterator;
22import java.util.LinkedList;
23import java.util.List;
24import java.util.Map;
25import java.util.Set;
26import java.util.concurrent.BlockingQueue;
27import java.util.concurrent.ConcurrentHashMap;
28import java.util.concurrent.ExecutorService;
29import java.util.concurrent.Executors;
30import java.util.concurrent.LinkedBlockingQueue;
31import java.util.concurrent.Semaphore;
32
Thomas Vachuskab97cf282014-10-20 23:31:12 -070033import org.apache.commons.lang3.tuple.Pair;
Thomas Vachuskae0f804a2014-10-27 23:40:48 -070034import org.onlab.onos.core.ApplicationId;
Thomas Vachuskab97cf282014-10-20 23:31:12 -070035import org.onlab.onos.net.ConnectPoint;
36import org.onlab.onos.net.Host;
37import org.onlab.onos.net.flow.DefaultTrafficSelector;
38import org.onlab.onos.net.flow.DefaultTrafficTreatment;
39import org.onlab.onos.net.flow.TrafficSelector;
40import org.onlab.onos.net.flow.TrafficTreatment;
41import org.onlab.onos.net.flow.criteria.Criteria.IPCriterion;
42import org.onlab.onos.net.flow.criteria.Criterion;
43import org.onlab.onos.net.flow.criteria.Criterion.Type;
44import org.onlab.onos.net.host.HostEvent;
45import org.onlab.onos.net.host.HostListener;
46import org.onlab.onos.net.host.HostService;
47import org.onlab.onos.net.intent.Intent;
48import org.onlab.onos.net.intent.IntentService;
Jonathan Hartec2df012014-10-23 16:40:24 -070049import org.onlab.onos.net.intent.IntentState;
Thomas Vachuskab97cf282014-10-20 23:31:12 -070050import org.onlab.onos.net.intent.MultiPointToSinglePointIntent;
51import org.onlab.onos.sdnip.config.BgpPeer;
52import org.onlab.onos.sdnip.config.Interface;
53import org.onlab.onos.sdnip.config.SdnIpConfigService;
54import org.onlab.packet.Ethernet;
55import org.onlab.packet.IpAddress;
56import org.onlab.packet.IpPrefix;
57import org.onlab.packet.MacAddress;
58import org.slf4j.Logger;
59import org.slf4j.LoggerFactory;
60
Pingping3855f312014-10-22 12:50:37 -070061import com.google.common.base.Objects;
62import com.google.common.collect.HashMultimap;
63import com.google.common.collect.Multimaps;
64import com.google.common.collect.SetMultimap;
65import com.google.common.util.concurrent.ThreadFactoryBuilder;
66import com.googlecode.concurrenttrees.common.KeyValuePair;
67import com.googlecode.concurrenttrees.radix.node.concrete.DefaultByteArrayNodeFactory;
68import com.googlecode.concurrenttrees.radixinverted.ConcurrentInvertedRadixTree;
69import com.googlecode.concurrenttrees.radixinverted.InvertedRadixTree;
Jonathan Hart335ef462014-10-16 08:20:46 -070070
Jonathan Hart335ef462014-10-16 08:20:46 -070071/**
72 * This class processes BGP route update, translates each update into a intent
73 * and submits the intent.
Jonathan Hart335ef462014-10-16 08:20:46 -070074 */
75public class Router implements RouteListener {
76
77 private static final Logger log = LoggerFactory.getLogger(Router.class);
78
Jonathan Hart0b04bed2014-10-16 16:39:19 -070079 // Store all route updates in a radix tree.
80 // The key in this tree is the binary string of prefix of the route.
Jonathan Hart335ef462014-10-16 08:20:46 -070081 private InvertedRadixTree<RouteEntry> bgpRoutes;
82
83 // Stores all incoming route updates in a queue.
84 private BlockingQueue<RouteUpdate> routeUpdates;
85
Jonathan Hart31582d12014-10-22 13:52:41 -070086 // The IpAddress is the next hop address of each route update.
Jonathan Hart335ef462014-10-16 08:20:46 -070087 private SetMultimap<IpAddress, RouteEntry> routesWaitingOnArp;
88 private ConcurrentHashMap<IpPrefix, MultiPointToSinglePointIntent> pushedRouteIntents;
89
90 private IntentService intentService;
Jonathan Hart335ef462014-10-16 08:20:46 -070091 private HostService hostService;
Jonathan Hart31582d12014-10-22 13:52:41 -070092 private SdnIpConfigService configService;
Jonathan Hart335ef462014-10-16 08:20:46 -070093 private InterfaceService interfaceService;
94
95 private ExecutorService bgpUpdatesExecutor;
96 private ExecutorService bgpIntentsSynchronizerExecutor;
97
Thomas Vachuskab97cf282014-10-20 23:31:12 -070098 private final ApplicationId appId;
Jonathan Hart335ef462014-10-16 08:20:46 -070099
100 //
101 // State to deal with SDN-IP Leader election and pushing Intents
102 //
103 private Semaphore intentsSynchronizerSemaphore = new Semaphore(0);
104 private volatile boolean isElectedLeader = false;
105 private volatile boolean isActivatedLeader = false;
106
Jonathan Hartbcae7bd2014-10-16 10:24:41 -0700107 // For routes announced by local BGP daemon in SDN network,
Jonathan Hart335ef462014-10-16 08:20:46 -0700108 // the next hop will be 0.0.0.0.
109 public static final IpAddress LOCAL_NEXT_HOP = IpAddress.valueOf("0.0.0.0");
110
111 /**
112 * Class constructor.
113 *
Jonathan Hart31582d12014-10-22 13:52:41 -0700114 * @param appId the application ID
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700115 * @param intentService the intent service
116 * @param hostService the host service
Jonathan Hart31582d12014-10-22 13:52:41 -0700117 * @param configService the configuration service
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700118 * @param interfaceService the interface service
Jonathan Hart335ef462014-10-16 08:20:46 -0700119 */
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700120 public Router(ApplicationId appId, IntentService intentService,
Jonathan Hart31582d12014-10-22 13:52:41 -0700121 HostService hostService, SdnIpConfigService configService,
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700122 InterfaceService interfaceService) {
123 this.appId = appId;
Jonathan Hart335ef462014-10-16 08:20:46 -0700124 this.intentService = intentService;
125 this.hostService = hostService;
Jonathan Hart31582d12014-10-22 13:52:41 -0700126 this.configService = configService;
Jonathan Hart335ef462014-10-16 08:20:46 -0700127 this.interfaceService = interfaceService;
128
129 bgpRoutes = new ConcurrentInvertedRadixTree<>(
130 new DefaultByteArrayNodeFactory());
131 routeUpdates = new LinkedBlockingQueue<>();
132 routesWaitingOnArp = Multimaps.synchronizedSetMultimap(
133 HashMultimap.<IpAddress, RouteEntry>create());
134 pushedRouteIntents = new ConcurrentHashMap<>();
135
136 bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
137 new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
138 bgpIntentsSynchronizerExecutor = Executors.newSingleThreadExecutor(
139 new ThreadFactoryBuilder()
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700140 .setNameFormat("bgp-intents-synchronizer-%d").build());
Jonathan Hartab63aac2014-10-16 08:52:55 -0700141
142 this.hostService.addListener(new InternalHostListener());
Jonathan Hart335ef462014-10-16 08:20:46 -0700143 }
144
145 /**
146 * Starts the Router.
147 */
148 public void start() {
Jonathan Hart335ef462014-10-16 08:20:46 -0700149 bgpUpdatesExecutor.execute(new Runnable() {
150 @Override
151 public void run() {
152 doUpdatesThread();
153 }
154 });
155
156 bgpIntentsSynchronizerExecutor.execute(new Runnable() {
157 @Override
158 public void run() {
159 doIntentSynchronizationThread();
160 }
161 });
162 }
163
164 //@Override TODO hook this up to something
165 public void leaderChanged(boolean isLeader) {
166 log.debug("Leader changed: {}", isLeader);
167
168 if (!isLeader) {
169 this.isElectedLeader = false;
170 this.isActivatedLeader = false;
171 return; // Nothing to do
172 }
173 this.isActivatedLeader = false;
174 this.isElectedLeader = true;
175
176 //
177 // Tell the Intents Synchronizer thread to start the synchronization
178 //
179 intentsSynchronizerSemaphore.release();
180 }
181
182 @Override
183 public void update(RouteUpdate routeUpdate) {
Jonathan Hart31582d12014-10-22 13:52:41 -0700184 log.debug("Received new route update: {}", routeUpdate);
Jonathan Hart335ef462014-10-16 08:20:46 -0700185
186 try {
187 routeUpdates.put(routeUpdate);
188 } catch (InterruptedException e) {
189 log.debug("Interrupted while putting on routeUpdates queue", e);
190 Thread.currentThread().interrupt();
191 }
192 }
193
194 /**
195 * Thread for Intent Synchronization.
196 */
197 private void doIntentSynchronizationThread() {
198 boolean interrupted = false;
199 try {
200 while (!interrupted) {
201 try {
202 intentsSynchronizerSemaphore.acquire();
203 //
204 // Drain all permits, because a single synchronization is
205 // sufficient.
206 //
207 intentsSynchronizerSemaphore.drainPermits();
208 } catch (InterruptedException e) {
209 log.debug("Interrupted while waiting to become " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700210 "Intent Synchronization leader");
Jonathan Hart335ef462014-10-16 08:20:46 -0700211 interrupted = true;
212 break;
213 }
214 syncIntents();
215 }
216 } finally {
217 if (interrupted) {
218 Thread.currentThread().interrupt();
219 }
220 }
221 }
222
223 /**
224 * Thread for handling route updates.
225 */
226 private void doUpdatesThread() {
227 boolean interrupted = false;
228 try {
229 while (!interrupted) {
230 try {
231 RouteUpdate update = routeUpdates.take();
232 switch (update.type()) {
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700233 case UPDATE:
234 processRouteAdd(update.routeEntry());
235 break;
236 case DELETE:
237 processRouteDelete(update.routeEntry());
238 break;
239 default:
240 log.error("Unknown update Type: {}", update.type());
241 break;
Jonathan Hart335ef462014-10-16 08:20:46 -0700242 }
243 } catch (InterruptedException e) {
244 log.debug("Interrupted while taking from updates queue", e);
245 interrupted = true;
246 } catch (Exception e) {
247 log.debug("exception", e);
248 }
249 }
250 } finally {
251 if (interrupted) {
252 Thread.currentThread().interrupt();
253 }
254 }
255 }
256
257 /**
258 * Performs Intents Synchronization between the internally stored Route
259 * Intents and the installed Route Intents.
260 */
261 private void syncIntents() {
262 synchronized (this) {
263 if (!isElectedLeader) {
264 return; // Nothing to do: not the leader anymore
265 }
266 log.debug("Syncing SDN-IP Route Intents...");
267
268 Map<IpPrefix, MultiPointToSinglePointIntent> fetchedIntents =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700269 new HashMap<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700270
271 //
272 // Fetch all intents, and classify the Multi-Point-to-Point Intents
273 // based on the matching prefix.
274 //
275 for (Intent intent : intentService.getIntents()) {
Jonathan Hartec2df012014-10-23 16:40:24 -0700276
277 if (!(intent instanceof MultiPointToSinglePointIntent)
278 || !intent.appId().equals(appId)) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700279 continue;
280 }
281 MultiPointToSinglePointIntent mp2pIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700282 (MultiPointToSinglePointIntent) intent;
Jonathan Hartec2df012014-10-23 16:40:24 -0700283
284 Criterion c = mp2pIntent.selector().getCriterion(Type.IPV4_DST);
285 if (c != null && c instanceof IPCriterion) {
286 IPCriterion ipCriterion = (IPCriterion) c;
287 fetchedIntents.put(ipCriterion.ip(), mp2pIntent);
288 } else {
289 log.warn("No IPV4_DST criterion found for intent {}",
290 mp2pIntent.id());
Jonathan Hart335ef462014-10-16 08:20:46 -0700291 }
292
293 }
294
295 //
296 // Compare for each prefix the local IN-MEMORY Intents with the
297 // FETCHED Intents:
298 // - If the IN-MEMORY Intent is same as the FETCHED Intent, store
299 // the FETCHED Intent in the local memory (i.e., override the
300 // IN-MEMORY Intent) to preserve the original Intent ID
301 // - if the IN-MEMORY Intent is not same as the FETCHED Intent,
302 // delete the FETCHED Intent, and push/install the IN-MEMORY
303 // Intent.
304 // - If there is an IN-MEMORY Intent for a prefix, but no FETCHED
305 // Intent for same prefix, then push/install the IN-MEMORY
306 // Intent.
307 // - If there is a FETCHED Intent for a prefix, but no IN-MEMORY
308 // Intent for same prefix, then delete/withdraw the FETCHED
309 // Intent.
310 //
311 Collection<Pair<IpPrefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700312 storeInMemoryIntents = new LinkedList<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700313 Collection<Pair<IpPrefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700314 addIntents = new LinkedList<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700315 Collection<Pair<IpPrefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700316 deleteIntents = new LinkedList<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700317 for (Map.Entry<IpPrefix, MultiPointToSinglePointIntent> entry :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700318 pushedRouteIntents.entrySet()) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700319 IpPrefix prefix = entry.getKey();
320 MultiPointToSinglePointIntent inMemoryIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700321 entry.getValue();
Jonathan Hart335ef462014-10-16 08:20:46 -0700322 MultiPointToSinglePointIntent fetchedIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700323 fetchedIntents.get(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700324
325 if (fetchedIntent == null) {
326 //
327 // No FETCHED Intent for same prefix: push the IN-MEMORY
328 // Intent.
329 //
330 addIntents.add(Pair.of(prefix, inMemoryIntent));
331 continue;
332 }
333
Jonathan Hartec2df012014-10-23 16:40:24 -0700334 IntentState state = intentService.getIntentState(fetchedIntent.id());
335 if (state == IntentState.WITHDRAWING ||
336 state == IntentState.WITHDRAWN) {
337 // The intent has been withdrawn but according to our route
338 // table it should be installed. We'll reinstall it.
339 addIntents.add(Pair.of(prefix, inMemoryIntent));
340 }
341
Jonathan Hart335ef462014-10-16 08:20:46 -0700342 //
343 // If IN-MEMORY Intent is same as the FETCHED Intent,
344 // store the FETCHED Intent in the local memory.
345 //
346 if (compareMultiPointToSinglePointIntents(inMemoryIntent,
347 fetchedIntent)) {
348 storeInMemoryIntents.add(Pair.of(prefix, fetchedIntent));
349 } else {
350 //
351 // The IN-MEMORY Intent is not same as the FETCHED Intent,
352 // hence delete the FETCHED Intent, and install the
353 // IN-MEMORY Intent.
354 //
355 deleteIntents.add(Pair.of(prefix, fetchedIntent));
356 addIntents.add(Pair.of(prefix, inMemoryIntent));
357 }
358 fetchedIntents.remove(prefix);
359 }
360
361 //
362 // Any remaining FETCHED Intents have to be deleted/withdrawn
363 //
364 for (Map.Entry<IpPrefix, MultiPointToSinglePointIntent> entry :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700365 fetchedIntents.entrySet()) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700366 IpPrefix prefix = entry.getKey();
367 MultiPointToSinglePointIntent fetchedIntent = entry.getValue();
368 deleteIntents.add(Pair.of(prefix, fetchedIntent));
369 }
370
371 //
372 // Perform the actions:
373 // 1. Store in memory fetched intents that are same. Can be done
374 // even if we are not the leader anymore
375 // 2. Delete intents: check if the leader before each operation
376 // 3. Add intents: check if the leader before each operation
377 //
378 for (Pair<IpPrefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700379 storeInMemoryIntents) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700380 IpPrefix prefix = pair.getLeft();
381 MultiPointToSinglePointIntent intent = pair.getRight();
382 log.debug("Intent synchronization: updating in-memory " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700383 "Intent for prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700384 pushedRouteIntents.put(prefix, intent);
385 }
386 //
387 isActivatedLeader = true; // Allow push of Intents
388 for (Pair<IpPrefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700389 deleteIntents) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700390 IpPrefix prefix = pair.getLeft();
391 MultiPointToSinglePointIntent intent = pair.getRight();
392 if (!isElectedLeader) {
393 isActivatedLeader = false;
394 return;
395 }
396 log.debug("Intent synchronization: deleting Intent for " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700397 "prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700398 intentService.withdraw(intent);
399 }
400 //
401 for (Pair<IpPrefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700402 addIntents) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700403 IpPrefix prefix = pair.getLeft();
404 MultiPointToSinglePointIntent intent = pair.getRight();
405 if (!isElectedLeader) {
406 isActivatedLeader = false;
407 return;
408 }
409 log.debug("Intent synchronization: adding Intent for " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700410 "prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700411 intentService.submit(intent);
412 }
413 if (!isElectedLeader) {
414 isActivatedLeader = false;
415 }
416 log.debug("Syncing SDN-IP routes completed.");
417 }
418 }
419
420 /**
421 * Compares two Multi-point to Single Point Intents whether they represent
422 * same logical intention.
423 *
424 * @param intent1 the first Intent to compare
425 * @param intent2 the second Intent to compare
426 * @return true if both Intents represent same logical intention, otherwise
427 * false
428 */
429 private boolean compareMultiPointToSinglePointIntents(
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700430 MultiPointToSinglePointIntent intent1,
431 MultiPointToSinglePointIntent intent2) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700432
Pingpingf5d90932014-10-27 10:50:04 -0700433 return Objects.equal(intent1.appId(), intent2.appId()) &&
434 Objects.equal(intent1.selector(), intent2.selector()) &&
Jonathan Hart335ef462014-10-16 08:20:46 -0700435 Objects.equal(intent1.treatment(), intent2.treatment()) &&
436 Objects.equal(intent1.ingressPoints(), intent2.ingressPoints()) &&
437 Objects.equal(intent1.egressPoint(), intent2.egressPoint());
438 }
439
440 /**
441 * Processes adding a route entry.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700442 * <p>
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700443 * Put new route entry into the radix tree. If there was an existing
444 * next hop for this prefix, but the next hop was different, then execute
Jonathan Hart335ef462014-10-16 08:20:46 -0700445 * deleting old route entry. If the next hop is the SDN domain, we do not
446 * handle it at the moment. Otherwise, execute adding a route.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700447 * </p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700448 *
449 * @param routeEntry the route entry to add
450 */
451 protected void processRouteAdd(RouteEntry routeEntry) {
452 synchronized (this) {
453 log.debug("Processing route add: {}", routeEntry);
454
455 IpPrefix prefix = routeEntry.prefix();
456 IpAddress nextHop = null;
457 RouteEntry foundRouteEntry =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700458 bgpRoutes.put(RouteEntry.createBinaryString(prefix),
459 routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700460 if (foundRouteEntry != null) {
461 nextHop = foundRouteEntry.nextHop();
462 }
463
464 if (nextHop != null && !nextHop.equals(routeEntry.nextHop())) {
465 // There was an existing nexthop for this prefix. This update
466 // supersedes that, so we need to remove the old flows for this
467 // prefix from the switches
468 executeRouteDelete(routeEntry);
469 }
470 if (nextHop != null && nextHop.equals(routeEntry.nextHop())) {
471 return;
472 }
473
474 if (routeEntry.nextHop().equals(LOCAL_NEXT_HOP)) {
475 // Route originated by SDN domain
476 // We don't handle these at the moment
477 log.debug("Own route {} to {}",
478 routeEntry.prefix(), routeEntry.nextHop());
479 return;
480 }
481
482 executeRouteAdd(routeEntry);
483 }
484 }
485
486 /**
487 * Executes adding a route entry.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700488 * <p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700489 * Find out the egress Interface and MAC address of next hop router for
490 * this route entry. If the MAC address can not be found in ARP cache,
491 * then this prefix will be put in routesWaitingOnArp queue. Otherwise,
492 * new route intent will be created and installed.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700493 * </p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700494 *
495 * @param routeEntry the route entry to add
496 */
497 private void executeRouteAdd(RouteEntry routeEntry) {
498 log.debug("Executing route add: {}", routeEntry);
499
Jonathan Hart31582d12014-10-22 13:52:41 -0700500 // Monitor the IP address so we'll get notified of updates to the MAC
501 // address.
502 hostService.startMonitoringIp(routeEntry.nextHop());
503
Jonathan Hart335ef462014-10-16 08:20:46 -0700504 // See if we know the MAC address of the next hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700505 MacAddress nextHopMacAddress = null;
Pavlin Radoslavov33f228a2014-10-27 19:33:16 -0700506 Set<Host> hosts = hostService.getHostsByIp(routeEntry.nextHop());
Jonathan Hart335ef462014-10-16 08:20:46 -0700507 if (!hosts.isEmpty()) {
508 // TODO how to handle if multiple hosts are returned?
509 nextHopMacAddress = hosts.iterator().next().mac();
510 }
511
512 if (nextHopMacAddress == null) {
513 routesWaitingOnArp.put(routeEntry.nextHop(), routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700514 return;
515 }
516
517 addRouteIntentToNextHop(routeEntry.prefix(),
518 routeEntry.nextHop(),
519 nextHopMacAddress);
520 }
521
522 /**
523 * Adds a route intent given a prefix and a next hop IP address. This
524 * method will find the egress interface for the intent.
525 *
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700526 * @param prefix IP prefix of the route to add
527 * @param nextHopIpAddress IP address of the next hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700528 * @param nextHopMacAddress MAC address of the next hop
529 */
530 private void addRouteIntentToNextHop(IpPrefix prefix,
531 IpAddress nextHopIpAddress,
532 MacAddress nextHopMacAddress) {
533
534 // Find the attachment point (egress interface) of the next hop
535 Interface egressInterface;
Jonathan Hart31582d12014-10-22 13:52:41 -0700536 if (configService.getBgpPeers().containsKey(nextHopIpAddress)) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700537 // Route to a peer
538 log.debug("Route to peer {}", nextHopIpAddress);
539 BgpPeer peer =
Jonathan Hart31582d12014-10-22 13:52:41 -0700540 configService.getBgpPeers().get(nextHopIpAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700541 egressInterface =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700542 interfaceService.getInterface(peer.connectPoint());
Jonathan Hart335ef462014-10-16 08:20:46 -0700543 } else {
544 // Route to non-peer
545 log.debug("Route to non-peer {}", nextHopIpAddress);
546 egressInterface =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700547 interfaceService.getMatchingInterface(nextHopIpAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700548 if (egressInterface == null) {
549 log.warn("No outgoing interface found for {}",
550 nextHopIpAddress);
551 return;
552 }
553 }
554
555 doAddRouteIntent(prefix, egressInterface, nextHopMacAddress);
556 }
557
558 /**
559 * Installs a route intent for a prefix.
560 * <p/>
561 * Intent will match dst IP prefix and rewrite dst MAC address at all other
562 * border switches, then forward packets according to dst MAC address.
563 *
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700564 * @param prefix IP prefix from route
565 * @param egressInterface egress Interface connected to next hop router
Jonathan Hart335ef462014-10-16 08:20:46 -0700566 * @param nextHopMacAddress MAC address of next hop router
567 */
568 private void doAddRouteIntent(IpPrefix prefix, Interface egressInterface,
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700569 MacAddress nextHopMacAddress) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700570 log.debug("Adding intent for prefix {}, next hop mac {}",
571 prefix, nextHopMacAddress);
572
573 MultiPointToSinglePointIntent pushedIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700574 pushedRouteIntents.get(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700575
576 // Just for testing.
577 if (pushedIntent != null) {
578 log.error("There should not be a pushed intent: {}", pushedIntent);
579 }
580
581 ConnectPoint egressPort = egressInterface.connectPoint();
582
583 Set<ConnectPoint> ingressPorts = new HashSet<>();
584
585 for (Interface intf : interfaceService.getInterfaces()) {
586 if (!intf.equals(egressInterface)) {
587 ConnectPoint srcPort = intf.connectPoint();
588 ingressPorts.add(srcPort);
589 }
590 }
591
592 // Match the destination IP prefix at the first hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700593 TrafficSelector selector = DefaultTrafficSelector.builder()
594 .matchEthType(Ethernet.TYPE_IPV4)
595 .matchIPDst(prefix)
596 .build();
597
598 // Rewrite the destination MAC address
Jonathan Hart335ef462014-10-16 08:20:46 -0700599 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
600 .setEthDst(nextHopMacAddress)
601 .build();
602
603 MultiPointToSinglePointIntent intent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700604 new MultiPointToSinglePointIntent(appId, selector, treatment,
605 ingressPorts, egressPort);
Jonathan Hart335ef462014-10-16 08:20:46 -0700606
607 if (isElectedLeader && isActivatedLeader) {
608 log.debug("Intent installation: adding Intent for prefix: {}",
609 prefix);
610 intentService.submit(intent);
611 }
612
613 // Maintain the Intent
614 pushedRouteIntents.put(prefix, intent);
615 }
616
617 /**
618 * Executes deleting a route entry.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700619 * <p>
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700620 * Removes prefix from radix tree, and if successful, then try to delete
621 * the related intent.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700622 * </p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700623 *
624 * @param routeEntry the route entry to delete
625 */
626 protected void processRouteDelete(RouteEntry routeEntry) {
627 synchronized (this) {
628 log.debug("Processing route delete: {}", routeEntry);
629 IpPrefix prefix = routeEntry.prefix();
630
Jonathan Hart335ef462014-10-16 08:20:46 -0700631 if (bgpRoutes.remove(RouteEntry.createBinaryString(prefix))) {
632 //
633 // Only delete flows if an entry was actually removed from the
634 // tree. If no entry was removed, the <prefix, nexthop> wasn't
635 // there so it's probably already been removed and we don't
636 // need to do anything.
637 //
638 executeRouteDelete(routeEntry);
639 }
640
641 routesWaitingOnArp.remove(routeEntry.nextHop(), routeEntry);
642 // TODO cancel the request in the ARP manager as well
643 }
644 }
645
646 /**
647 * Executed deleting a route entry.
648 *
649 * @param routeEntry the route entry to delete
650 */
651 private void executeRouteDelete(RouteEntry routeEntry) {
652 log.debug("Executing route delete: {}", routeEntry);
653
654 IpPrefix prefix = routeEntry.prefix();
655
656 MultiPointToSinglePointIntent intent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700657 pushedRouteIntents.remove(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700658
659 if (intent == null) {
660 log.debug("There is no intent in pushedRouteIntents to delete " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700661 "for prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700662 } else {
663 if (isElectedLeader && isActivatedLeader) {
664 log.debug("Intent installation: deleting Intent for prefix: {}",
665 prefix);
666 intentService.withdraw(intent);
667 }
668 }
669 }
670
671 /**
Jonathan Hart31582d12014-10-22 13:52:41 -0700672 * Signals the Router that the MAC to IP mapping has potentially been
673 * updated. This has the effect of updating the MAC address for any
674 * installed prefixes if it has changed, as well as installing any pending
675 * prefixes that were waiting for MAC resolution.
Jonathan Hart335ef462014-10-16 08:20:46 -0700676 *
Jonathan Hart31582d12014-10-22 13:52:41 -0700677 * @param ipAddress the IP address that an event was received for
678 * @param macAddress the most recently known MAC address for the IP address
Jonathan Hart335ef462014-10-16 08:20:46 -0700679 */
Jonathan Hart31582d12014-10-22 13:52:41 -0700680 private void updateMac(IpAddress ipAddress, MacAddress macAddress) {
681 log.debug("Received updated MAC info: {} => {}", ipAddress, macAddress);
682
683 // TODO here we should check whether the next hop for any of our
684 // installed prefixes has changed, not just prefixes pending installation.
Jonathan Hart335ef462014-10-16 08:20:46 -0700685
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700686 // We synchronize on this to prevent changes to the radix tree
687 // while we're pushing intents. If the tree changes, the
688 // tree and intents could get out of sync.
Jonathan Hart335ef462014-10-16 08:20:46 -0700689 synchronized (this) {
690
691 Set<RouteEntry> routesToPush =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700692 routesWaitingOnArp.removeAll(ipAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700693
694 for (RouteEntry routeEntry : routesToPush) {
695 // These will always be adds
696 IpPrefix prefix = routeEntry.prefix();
697 String binaryString = RouteEntry.createBinaryString(prefix);
698 RouteEntry foundRouteEntry =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700699 bgpRoutes.getValueForExactKey(binaryString);
Jonathan Hart335ef462014-10-16 08:20:46 -0700700 if (foundRouteEntry != null &&
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700701 foundRouteEntry.nextHop().equals(routeEntry.nextHop())) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700702 // We only push prefix flows if the prefix is still in the
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700703 // radix tree and the next hop is the same as our
Jonathan Hart335ef462014-10-16 08:20:46 -0700704 // update.
705 // The prefix could have been removed while we were waiting
706 // for the ARP, or the next hop could have changed.
707 addRouteIntentToNextHop(prefix, ipAddress, macAddress);
708 } else {
Jonathan Hart31582d12014-10-22 13:52:41 -0700709 log.debug("{} has been revoked before the MAC was resolved",
710 routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700711 }
712 }
713 }
714 }
715
716 /**
717 * Gets the SDN-IP routes.
718 *
719 * @return the SDN-IP routes
720 */
721 public Collection<RouteEntry> getRoutes() {
722 Iterator<KeyValuePair<RouteEntry>> it =
723 bgpRoutes.getKeyValuePairsForKeysStartingWith("").iterator();
724
725 List<RouteEntry> routes = new LinkedList<>();
726
727 while (it.hasNext()) {
728 KeyValuePair<RouteEntry> entry = it.next();
729 routes.add(entry.getValue());
730 }
731
732 return routes;
733 }
734
735 /**
Pingping3855f312014-10-22 12:50:37 -0700736 * Gets the pushed route intents.
737 *
738 * @return the pushed route intents
739 */
740 public Collection<MultiPointToSinglePointIntent> getPushedRouteIntents() {
741 List<MultiPointToSinglePointIntent> pushedIntents = new LinkedList<>();
742
743 for (Map.Entry<IpPrefix, MultiPointToSinglePointIntent> entry :
744 pushedRouteIntents.entrySet()) {
745 pushedIntents.add(entry.getValue());
746 }
747 return pushedIntents;
748 }
749
750 /**
Jonathan Hart335ef462014-10-16 08:20:46 -0700751 * Listener for host events.
752 */
753 class InternalHostListener implements HostListener {
754 @Override
755 public void event(HostEvent event) {
756 if (event.type() == HostEvent.Type.HOST_ADDED ||
757 event.type() == HostEvent.Type.HOST_UPDATED) {
758 Host host = event.subject();
Pavlin Radoslavov33f228a2014-10-27 19:33:16 -0700759 for (IpAddress ip : host.ipAddresses()) {
760 updateMac(ip, host.mac());
Jonathan Hart335ef462014-10-16 08:20:46 -0700761 }
762 }
763 }
764 }
765}