blob: 945d725e4006016ddb31fe62bc8ed698fac0bc96 [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;
49import org.onlab.onos.net.intent.MultiPointToSinglePointIntent;
50import org.onlab.onos.sdnip.config.BgpPeer;
51import org.onlab.onos.sdnip.config.Interface;
52import org.onlab.onos.sdnip.config.SdnIpConfigService;
53import org.onlab.packet.Ethernet;
54import org.onlab.packet.IpAddress;
55import org.onlab.packet.IpPrefix;
56import org.onlab.packet.MacAddress;
57import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
Pingping3855f312014-10-22 12:50:37 -070060import com.google.common.base.Objects;
61import com.google.common.collect.HashMultimap;
62import com.google.common.collect.Multimaps;
63import com.google.common.collect.SetMultimap;
64import com.google.common.util.concurrent.ThreadFactoryBuilder;
65import com.googlecode.concurrenttrees.common.KeyValuePair;
66import com.googlecode.concurrenttrees.radix.node.concrete.DefaultByteArrayNodeFactory;
67import com.googlecode.concurrenttrees.radixinverted.ConcurrentInvertedRadixTree;
68import com.googlecode.concurrenttrees.radixinverted.InvertedRadixTree;
Jonathan Hart335ef462014-10-16 08:20:46 -070069
Jonathan Hart335ef462014-10-16 08:20:46 -070070/**
71 * This class processes BGP route update, translates each update into a intent
72 * and submits the intent.
Jonathan Hart335ef462014-10-16 08:20:46 -070073 */
74public class Router implements RouteListener {
75
76 private static final Logger log = LoggerFactory.getLogger(Router.class);
77
Jonathan Hart0b04bed2014-10-16 16:39:19 -070078 // Store all route updates in a radix tree.
79 // The key in this tree is the binary string of prefix of the route.
Jonathan Hart335ef462014-10-16 08:20:46 -070080 private InvertedRadixTree<RouteEntry> bgpRoutes;
81
82 // Stores all incoming route updates in a queue.
83 private BlockingQueue<RouteUpdate> routeUpdates;
84
Jonathan Hart31582d12014-10-22 13:52:41 -070085 // The IpAddress is the next hop address of each route update.
Jonathan Hart335ef462014-10-16 08:20:46 -070086 private SetMultimap<IpAddress, RouteEntry> routesWaitingOnArp;
87 private ConcurrentHashMap<IpPrefix, MultiPointToSinglePointIntent> pushedRouteIntents;
88
89 private IntentService intentService;
Jonathan Hart335ef462014-10-16 08:20:46 -070090 private HostService hostService;
Jonathan Hart31582d12014-10-22 13:52:41 -070091 private SdnIpConfigService configService;
Jonathan Hart335ef462014-10-16 08:20:46 -070092 private InterfaceService interfaceService;
93
94 private ExecutorService bgpUpdatesExecutor;
95 private ExecutorService bgpIntentsSynchronizerExecutor;
96
Thomas Vachuskab97cf282014-10-20 23:31:12 -070097 private final ApplicationId appId;
Jonathan Hart335ef462014-10-16 08:20:46 -070098
99 //
100 // State to deal with SDN-IP Leader election and pushing Intents
101 //
102 private Semaphore intentsSynchronizerSemaphore = new Semaphore(0);
103 private volatile boolean isElectedLeader = false;
104 private volatile boolean isActivatedLeader = false;
105
Jonathan Hartbcae7bd2014-10-16 10:24:41 -0700106 // For routes announced by local BGP daemon in SDN network,
Jonathan Hart335ef462014-10-16 08:20:46 -0700107 // the next hop will be 0.0.0.0.
108 public static final IpAddress LOCAL_NEXT_HOP = IpAddress.valueOf("0.0.0.0");
109
110 /**
111 * Class constructor.
112 *
Jonathan Hart31582d12014-10-22 13:52:41 -0700113 * @param appId the application ID
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700114 * @param intentService the intent service
115 * @param hostService the host service
Jonathan Hart31582d12014-10-22 13:52:41 -0700116 * @param configService the configuration service
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700117 * @param interfaceService the interface service
Jonathan Hart335ef462014-10-16 08:20:46 -0700118 */
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700119 public Router(ApplicationId appId, IntentService intentService,
Jonathan Hart31582d12014-10-22 13:52:41 -0700120 HostService hostService, SdnIpConfigService configService,
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700121 InterfaceService interfaceService) {
122 this.appId = appId;
Jonathan Hart335ef462014-10-16 08:20:46 -0700123 this.intentService = intentService;
124 this.hostService = hostService;
Jonathan Hart31582d12014-10-22 13:52:41 -0700125 this.configService = configService;
Jonathan Hart335ef462014-10-16 08:20:46 -0700126 this.interfaceService = interfaceService;
127
128 bgpRoutes = new ConcurrentInvertedRadixTree<>(
129 new DefaultByteArrayNodeFactory());
130 routeUpdates = new LinkedBlockingQueue<>();
131 routesWaitingOnArp = Multimaps.synchronizedSetMultimap(
132 HashMultimap.<IpAddress, RouteEntry>create());
133 pushedRouteIntents = new ConcurrentHashMap<>();
134
135 bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
136 new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
137 bgpIntentsSynchronizerExecutor = Executors.newSingleThreadExecutor(
138 new ThreadFactoryBuilder()
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700139 .setNameFormat("bgp-intents-synchronizer-%d").build());
Jonathan Hartab63aac2014-10-16 08:52:55 -0700140
141 this.hostService.addListener(new InternalHostListener());
Jonathan Hart335ef462014-10-16 08:20:46 -0700142 }
143
144 /**
145 * Starts the Router.
146 */
147 public void start() {
148
Jonathan Hart0e12fad2014-10-17 14:54:58 -0700149 // TODO hack to enable SDN-IP now for testing
150 isElectedLeader = true;
151 isActivatedLeader = true;
152
Jonathan Hart335ef462014-10-16 08:20:46 -0700153 bgpUpdatesExecutor.execute(new Runnable() {
154 @Override
155 public void run() {
156 doUpdatesThread();
157 }
158 });
159
160 bgpIntentsSynchronizerExecutor.execute(new Runnable() {
161 @Override
162 public void run() {
163 doIntentSynchronizationThread();
164 }
165 });
166 }
167
168 //@Override TODO hook this up to something
169 public void leaderChanged(boolean isLeader) {
170 log.debug("Leader changed: {}", isLeader);
171
172 if (!isLeader) {
173 this.isElectedLeader = false;
174 this.isActivatedLeader = false;
175 return; // Nothing to do
176 }
177 this.isActivatedLeader = false;
178 this.isElectedLeader = true;
179
180 //
181 // Tell the Intents Synchronizer thread to start the synchronization
182 //
183 intentsSynchronizerSemaphore.release();
184 }
185
186 @Override
187 public void update(RouteUpdate routeUpdate) {
Jonathan Hart31582d12014-10-22 13:52:41 -0700188 log.debug("Received new route update: {}", routeUpdate);
Jonathan Hart335ef462014-10-16 08:20:46 -0700189
190 try {
191 routeUpdates.put(routeUpdate);
192 } catch (InterruptedException e) {
193 log.debug("Interrupted while putting on routeUpdates queue", e);
194 Thread.currentThread().interrupt();
195 }
196 }
197
198 /**
199 * Thread for Intent Synchronization.
200 */
201 private void doIntentSynchronizationThread() {
202 boolean interrupted = false;
203 try {
204 while (!interrupted) {
205 try {
206 intentsSynchronizerSemaphore.acquire();
207 //
208 // Drain all permits, because a single synchronization is
209 // sufficient.
210 //
211 intentsSynchronizerSemaphore.drainPermits();
212 } catch (InterruptedException e) {
213 log.debug("Interrupted while waiting to become " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700214 "Intent Synchronization leader");
Jonathan Hart335ef462014-10-16 08:20:46 -0700215 interrupted = true;
216 break;
217 }
218 syncIntents();
219 }
220 } finally {
221 if (interrupted) {
222 Thread.currentThread().interrupt();
223 }
224 }
225 }
226
227 /**
228 * Thread for handling route updates.
229 */
230 private void doUpdatesThread() {
231 boolean interrupted = false;
232 try {
233 while (!interrupted) {
234 try {
235 RouteUpdate update = routeUpdates.take();
236 switch (update.type()) {
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700237 case UPDATE:
238 processRouteAdd(update.routeEntry());
239 break;
240 case DELETE:
241 processRouteDelete(update.routeEntry());
242 break;
243 default:
244 log.error("Unknown update Type: {}", update.type());
245 break;
Jonathan Hart335ef462014-10-16 08:20:46 -0700246 }
247 } catch (InterruptedException e) {
248 log.debug("Interrupted while taking from updates queue", e);
249 interrupted = true;
250 } catch (Exception e) {
251 log.debug("exception", e);
252 }
253 }
254 } finally {
255 if (interrupted) {
256 Thread.currentThread().interrupt();
257 }
258 }
259 }
260
261 /**
262 * Performs Intents Synchronization between the internally stored Route
263 * Intents and the installed Route Intents.
264 */
265 private void syncIntents() {
266 synchronized (this) {
267 if (!isElectedLeader) {
268 return; // Nothing to do: not the leader anymore
269 }
270 log.debug("Syncing SDN-IP Route Intents...");
271
272 Map<IpPrefix, MultiPointToSinglePointIntent> fetchedIntents =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700273 new HashMap<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700274
275 //
276 // Fetch all intents, and classify the Multi-Point-to-Point Intents
277 // based on the matching prefix.
278 //
279 for (Intent intent : intentService.getIntents()) {
280 //
281 // TODO: Ignore all intents that are not installed by
282 // the SDN-IP application.
283 //
284 if (!(intent instanceof MultiPointToSinglePointIntent)) {
285 continue;
286 }
287 MultiPointToSinglePointIntent mp2pIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700288 (MultiPointToSinglePointIntent) intent;
Jonathan Hart335ef462014-10-16 08:20:46 -0700289 /*Match match = mp2pIntent.getMatch();
290 if (!(match instanceof PacketMatch)) {
291 continue;
292 }
293 PacketMatch packetMatch = (PacketMatch) match;
294 Ip4Prefix prefix = packetMatch.getDstIpAddress();
295 if (prefix == null) {
296 continue;
297 }
298 fetchedIntents.put(prefix, mp2pIntent);*/
299 for (Criterion criterion : mp2pIntent.selector().criteria()) {
300 if (criterion.type() == Type.IPV4_DST) {
301 IPCriterion ipCriterion = (IPCriterion) criterion;
302 fetchedIntents.put(ipCriterion.ip(), mp2pIntent);
303 }
304 }
305
306 }
307
308 //
309 // Compare for each prefix the local IN-MEMORY Intents with the
310 // FETCHED Intents:
311 // - If the IN-MEMORY Intent is same as the FETCHED Intent, store
312 // the FETCHED Intent in the local memory (i.e., override the
313 // IN-MEMORY Intent) to preserve the original Intent ID
314 // - if the IN-MEMORY Intent is not same as the FETCHED Intent,
315 // delete the FETCHED Intent, and push/install the IN-MEMORY
316 // Intent.
317 // - If there is an IN-MEMORY Intent for a prefix, but no FETCHED
318 // Intent for same prefix, then push/install the IN-MEMORY
319 // Intent.
320 // - If there is a FETCHED Intent for a prefix, but no IN-MEMORY
321 // Intent for same prefix, then delete/withdraw the FETCHED
322 // Intent.
323 //
324 Collection<Pair<IpPrefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700325 storeInMemoryIntents = new LinkedList<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700326 Collection<Pair<IpPrefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700327 addIntents = new LinkedList<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700328 Collection<Pair<IpPrefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700329 deleteIntents = new LinkedList<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700330 for (Map.Entry<IpPrefix, MultiPointToSinglePointIntent> entry :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700331 pushedRouteIntents.entrySet()) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700332 IpPrefix prefix = entry.getKey();
333 MultiPointToSinglePointIntent inMemoryIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700334 entry.getValue();
Jonathan Hart335ef462014-10-16 08:20:46 -0700335 MultiPointToSinglePointIntent fetchedIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700336 fetchedIntents.get(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700337
338 if (fetchedIntent == null) {
339 //
340 // No FETCHED Intent for same prefix: push the IN-MEMORY
341 // Intent.
342 //
343 addIntents.add(Pair.of(prefix, inMemoryIntent));
344 continue;
345 }
346
347 //
348 // If IN-MEMORY Intent is same as the FETCHED Intent,
349 // store the FETCHED Intent in the local memory.
350 //
351 if (compareMultiPointToSinglePointIntents(inMemoryIntent,
352 fetchedIntent)) {
353 storeInMemoryIntents.add(Pair.of(prefix, fetchedIntent));
354 } else {
355 //
356 // The IN-MEMORY Intent is not same as the FETCHED Intent,
357 // hence delete the FETCHED Intent, and install the
358 // IN-MEMORY Intent.
359 //
360 deleteIntents.add(Pair.of(prefix, fetchedIntent));
361 addIntents.add(Pair.of(prefix, inMemoryIntent));
362 }
363 fetchedIntents.remove(prefix);
364 }
365
366 //
367 // Any remaining FETCHED Intents have to be deleted/withdrawn
368 //
369 for (Map.Entry<IpPrefix, MultiPointToSinglePointIntent> entry :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700370 fetchedIntents.entrySet()) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700371 IpPrefix prefix = entry.getKey();
372 MultiPointToSinglePointIntent fetchedIntent = entry.getValue();
373 deleteIntents.add(Pair.of(prefix, fetchedIntent));
374 }
375
376 //
377 // Perform the actions:
378 // 1. Store in memory fetched intents that are same. Can be done
379 // even if we are not the leader anymore
380 // 2. Delete intents: check if the leader before each operation
381 // 3. Add intents: check if the leader before each operation
382 //
383 for (Pair<IpPrefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700384 storeInMemoryIntents) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700385 IpPrefix prefix = pair.getLeft();
386 MultiPointToSinglePointIntent intent = pair.getRight();
387 log.debug("Intent synchronization: updating in-memory " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700388 "Intent for prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700389 pushedRouteIntents.put(prefix, intent);
390 }
391 //
392 isActivatedLeader = true; // Allow push of Intents
393 for (Pair<IpPrefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700394 deleteIntents) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700395 IpPrefix prefix = pair.getLeft();
396 MultiPointToSinglePointIntent intent = pair.getRight();
397 if (!isElectedLeader) {
398 isActivatedLeader = false;
399 return;
400 }
401 log.debug("Intent synchronization: deleting Intent for " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700402 "prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700403 intentService.withdraw(intent);
404 }
405 //
406 for (Pair<IpPrefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700407 addIntents) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700408 IpPrefix prefix = pair.getLeft();
409 MultiPointToSinglePointIntent intent = pair.getRight();
410 if (!isElectedLeader) {
411 isActivatedLeader = false;
412 return;
413 }
414 log.debug("Intent synchronization: adding Intent for " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700415 "prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700416 intentService.submit(intent);
417 }
418 if (!isElectedLeader) {
419 isActivatedLeader = false;
420 }
421 log.debug("Syncing SDN-IP routes completed.");
422 }
423 }
424
425 /**
426 * Compares two Multi-point to Single Point Intents whether they represent
427 * same logical intention.
428 *
429 * @param intent1 the first Intent to compare
430 * @param intent2 the second Intent to compare
431 * @return true if both Intents represent same logical intention, otherwise
432 * false
433 */
434 private boolean compareMultiPointToSinglePointIntents(
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700435 MultiPointToSinglePointIntent intent1,
436 MultiPointToSinglePointIntent intent2) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700437 /*Match match1 = intent1.getMatch();
438 Match match2 = intent2.getMatch();
439 Action action1 = intent1.getAction();
440 Action action2 = intent2.getAction();
441 Set<SwitchPort> ingressPorts1 = intent1.getIngressPorts();
442 Set<SwitchPort> ingressPorts2 = intent2.getIngressPorts();
443 SwitchPort egressPort1 = intent1.getEgressPort();
444 SwitchPort egressPort2 = intent2.getEgressPort();
445
446 return Objects.equal(match1, match2) &&
447 Objects.equal(action1, action2) &&
448 Objects.equal(egressPort1, egressPort2) &&
449 Objects.equal(ingressPorts1, ingressPorts2);*/
450 return Objects.equal(intent1.selector(), intent2.selector()) &&
451 Objects.equal(intent1.treatment(), intent2.treatment()) &&
452 Objects.equal(intent1.ingressPoints(), intent2.ingressPoints()) &&
453 Objects.equal(intent1.egressPoint(), intent2.egressPoint());
454 }
455
456 /**
457 * Processes adding a route entry.
458 * <p/>
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700459 * Put new route entry into the radix tree. If there was an existing
460 * next hop for this prefix, but the next hop was different, then execute
Jonathan Hart335ef462014-10-16 08:20:46 -0700461 * deleting old route entry. If the next hop is the SDN domain, we do not
462 * handle it at the moment. Otherwise, execute adding a route.
463 *
464 * @param routeEntry the route entry to add
465 */
466 protected void processRouteAdd(RouteEntry routeEntry) {
467 synchronized (this) {
468 log.debug("Processing route add: {}", routeEntry);
469
470 IpPrefix prefix = routeEntry.prefix();
471 IpAddress nextHop = null;
472 RouteEntry foundRouteEntry =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700473 bgpRoutes.put(RouteEntry.createBinaryString(prefix),
474 routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700475 if (foundRouteEntry != null) {
476 nextHop = foundRouteEntry.nextHop();
477 }
478
479 if (nextHop != null && !nextHop.equals(routeEntry.nextHop())) {
480 // There was an existing nexthop for this prefix. This update
481 // supersedes that, so we need to remove the old flows for this
482 // prefix from the switches
483 executeRouteDelete(routeEntry);
484 }
485 if (nextHop != null && nextHop.equals(routeEntry.nextHop())) {
486 return;
487 }
488
489 if (routeEntry.nextHop().equals(LOCAL_NEXT_HOP)) {
490 // Route originated by SDN domain
491 // We don't handle these at the moment
492 log.debug("Own route {} to {}",
493 routeEntry.prefix(), routeEntry.nextHop());
494 return;
495 }
496
497 executeRouteAdd(routeEntry);
498 }
499 }
500
501 /**
502 * Executes adding a route entry.
503 * <p/>
504 * Find out the egress Interface and MAC address of next hop router for
505 * this route entry. If the MAC address can not be found in ARP cache,
506 * then this prefix will be put in routesWaitingOnArp queue. Otherwise,
507 * new route intent will be created and installed.
508 *
509 * @param routeEntry the route entry to add
510 */
511 private void executeRouteAdd(RouteEntry routeEntry) {
512 log.debug("Executing route add: {}", routeEntry);
513
Jonathan Hart31582d12014-10-22 13:52:41 -0700514 // Monitor the IP address so we'll get notified of updates to the MAC
515 // address.
516 hostService.startMonitoringIp(routeEntry.nextHop());
517
Jonathan Hart335ef462014-10-16 08:20:46 -0700518 // See if we know the MAC address of the next hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700519 MacAddress nextHopMacAddress = null;
Pavlin Radoslavov33f228a2014-10-27 19:33:16 -0700520 Set<Host> hosts = hostService.getHostsByIp(routeEntry.nextHop());
Jonathan Hart335ef462014-10-16 08:20:46 -0700521 if (!hosts.isEmpty()) {
522 // TODO how to handle if multiple hosts are returned?
523 nextHopMacAddress = hosts.iterator().next().mac();
524 }
525
526 if (nextHopMacAddress == null) {
527 routesWaitingOnArp.put(routeEntry.nextHop(), routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700528 return;
529 }
530
531 addRouteIntentToNextHop(routeEntry.prefix(),
532 routeEntry.nextHop(),
533 nextHopMacAddress);
534 }
535
536 /**
537 * Adds a route intent given a prefix and a next hop IP address. This
538 * method will find the egress interface for the intent.
539 *
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700540 * @param prefix IP prefix of the route to add
541 * @param nextHopIpAddress IP address of the next hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700542 * @param nextHopMacAddress MAC address of the next hop
543 */
544 private void addRouteIntentToNextHop(IpPrefix prefix,
545 IpAddress nextHopIpAddress,
546 MacAddress nextHopMacAddress) {
547
548 // Find the attachment point (egress interface) of the next hop
549 Interface egressInterface;
Jonathan Hart31582d12014-10-22 13:52:41 -0700550 if (configService.getBgpPeers().containsKey(nextHopIpAddress)) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700551 // Route to a peer
552 log.debug("Route to peer {}", nextHopIpAddress);
553 BgpPeer peer =
Jonathan Hart31582d12014-10-22 13:52:41 -0700554 configService.getBgpPeers().get(nextHopIpAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700555 egressInterface =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700556 interfaceService.getInterface(peer.connectPoint());
Jonathan Hart335ef462014-10-16 08:20:46 -0700557 } else {
558 // Route to non-peer
559 log.debug("Route to non-peer {}", nextHopIpAddress);
560 egressInterface =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700561 interfaceService.getMatchingInterface(nextHopIpAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700562 if (egressInterface == null) {
563 log.warn("No outgoing interface found for {}",
564 nextHopIpAddress);
565 return;
566 }
567 }
568
569 doAddRouteIntent(prefix, egressInterface, nextHopMacAddress);
570 }
571
572 /**
573 * Installs a route intent for a prefix.
574 * <p/>
575 * Intent will match dst IP prefix and rewrite dst MAC address at all other
576 * border switches, then forward packets according to dst MAC address.
577 *
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700578 * @param prefix IP prefix from route
579 * @param egressInterface egress Interface connected to next hop router
Jonathan Hart335ef462014-10-16 08:20:46 -0700580 * @param nextHopMacAddress MAC address of next hop router
581 */
582 private void doAddRouteIntent(IpPrefix prefix, Interface egressInterface,
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700583 MacAddress nextHopMacAddress) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700584 log.debug("Adding intent for prefix {}, next hop mac {}",
585 prefix, nextHopMacAddress);
586
587 MultiPointToSinglePointIntent pushedIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700588 pushedRouteIntents.get(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700589
590 // Just for testing.
591 if (pushedIntent != null) {
592 log.error("There should not be a pushed intent: {}", pushedIntent);
593 }
594
595 ConnectPoint egressPort = egressInterface.connectPoint();
596
597 Set<ConnectPoint> ingressPorts = new HashSet<>();
598
599 for (Interface intf : interfaceService.getInterfaces()) {
600 if (!intf.equals(egressInterface)) {
601 ConnectPoint srcPort = intf.connectPoint();
602 ingressPorts.add(srcPort);
603 }
604 }
605
606 // Match the destination IP prefix at the first hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700607 TrafficSelector selector = DefaultTrafficSelector.builder()
608 .matchEthType(Ethernet.TYPE_IPV4)
609 .matchIPDst(prefix)
610 .build();
611
612 // Rewrite the destination MAC address
Jonathan Hart335ef462014-10-16 08:20:46 -0700613 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
614 .setEthDst(nextHopMacAddress)
615 .build();
616
617 MultiPointToSinglePointIntent intent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700618 new MultiPointToSinglePointIntent(appId, selector, treatment,
619 ingressPorts, egressPort);
Jonathan Hart335ef462014-10-16 08:20:46 -0700620
621 if (isElectedLeader && isActivatedLeader) {
622 log.debug("Intent installation: adding Intent for prefix: {}",
623 prefix);
624 intentService.submit(intent);
625 }
626
627 // Maintain the Intent
628 pushedRouteIntents.put(prefix, intent);
629 }
630
631 /**
632 * Executes deleting a route entry.
633 * <p/>
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700634 * Removes prefix from radix tree, and if successful, then try to delete
635 * the related intent.
Jonathan Hart335ef462014-10-16 08:20:46 -0700636 *
637 * @param routeEntry the route entry to delete
638 */
639 protected void processRouteDelete(RouteEntry routeEntry) {
640 synchronized (this) {
641 log.debug("Processing route delete: {}", routeEntry);
642 IpPrefix prefix = routeEntry.prefix();
643
Jonathan Hart335ef462014-10-16 08:20:46 -0700644 if (bgpRoutes.remove(RouteEntry.createBinaryString(prefix))) {
645 //
646 // Only delete flows if an entry was actually removed from the
647 // tree. If no entry was removed, the <prefix, nexthop> wasn't
648 // there so it's probably already been removed and we don't
649 // need to do anything.
650 //
651 executeRouteDelete(routeEntry);
652 }
653
654 routesWaitingOnArp.remove(routeEntry.nextHop(), routeEntry);
655 // TODO cancel the request in the ARP manager as well
656 }
657 }
658
659 /**
660 * Executed deleting a route entry.
661 *
662 * @param routeEntry the route entry to delete
663 */
664 private void executeRouteDelete(RouteEntry routeEntry) {
665 log.debug("Executing route delete: {}", routeEntry);
666
667 IpPrefix prefix = routeEntry.prefix();
668
669 MultiPointToSinglePointIntent intent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700670 pushedRouteIntents.remove(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700671
672 if (intent == null) {
673 log.debug("There is no intent in pushedRouteIntents to delete " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700674 "for prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700675 } else {
676 if (isElectedLeader && isActivatedLeader) {
677 log.debug("Intent installation: deleting Intent for prefix: {}",
678 prefix);
679 intentService.withdraw(intent);
680 }
681 }
682 }
683
684 /**
Jonathan Hart31582d12014-10-22 13:52:41 -0700685 * Signals the Router that the MAC to IP mapping has potentially been
686 * updated. This has the effect of updating the MAC address for any
687 * installed prefixes if it has changed, as well as installing any pending
688 * prefixes that were waiting for MAC resolution.
Jonathan Hart335ef462014-10-16 08:20:46 -0700689 *
Jonathan Hart31582d12014-10-22 13:52:41 -0700690 * @param ipAddress the IP address that an event was received for
691 * @param macAddress the most recently known MAC address for the IP address
Jonathan Hart335ef462014-10-16 08:20:46 -0700692 */
Jonathan Hart31582d12014-10-22 13:52:41 -0700693 private void updateMac(IpAddress ipAddress, MacAddress macAddress) {
694 log.debug("Received updated MAC info: {} => {}", ipAddress, macAddress);
695
696 // TODO here we should check whether the next hop for any of our
697 // installed prefixes has changed, not just prefixes pending installation.
Jonathan Hart335ef462014-10-16 08:20:46 -0700698
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700699 // We synchronize on this to prevent changes to the radix tree
700 // while we're pushing intents. If the tree changes, the
701 // tree and intents could get out of sync.
Jonathan Hart335ef462014-10-16 08:20:46 -0700702 synchronized (this) {
703
704 Set<RouteEntry> routesToPush =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700705 routesWaitingOnArp.removeAll(ipAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700706
707 for (RouteEntry routeEntry : routesToPush) {
708 // These will always be adds
709 IpPrefix prefix = routeEntry.prefix();
710 String binaryString = RouteEntry.createBinaryString(prefix);
711 RouteEntry foundRouteEntry =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700712 bgpRoutes.getValueForExactKey(binaryString);
Jonathan Hart335ef462014-10-16 08:20:46 -0700713 if (foundRouteEntry != null &&
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700714 foundRouteEntry.nextHop().equals(routeEntry.nextHop())) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700715 // We only push prefix flows if the prefix is still in the
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700716 // radix tree and the next hop is the same as our
Jonathan Hart335ef462014-10-16 08:20:46 -0700717 // update.
718 // The prefix could have been removed while we were waiting
719 // for the ARP, or the next hop could have changed.
720 addRouteIntentToNextHop(prefix, ipAddress, macAddress);
721 } else {
Jonathan Hart31582d12014-10-22 13:52:41 -0700722 log.debug("{} has been revoked before the MAC was resolved",
723 routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700724 }
725 }
726 }
727 }
728
729 /**
730 * Gets the SDN-IP routes.
731 *
732 * @return the SDN-IP routes
733 */
734 public Collection<RouteEntry> getRoutes() {
735 Iterator<KeyValuePair<RouteEntry>> it =
736 bgpRoutes.getKeyValuePairsForKeysStartingWith("").iterator();
737
738 List<RouteEntry> routes = new LinkedList<>();
739
740 while (it.hasNext()) {
741 KeyValuePair<RouteEntry> entry = it.next();
742 routes.add(entry.getValue());
743 }
744
745 return routes;
746 }
747
748 /**
Pingping3855f312014-10-22 12:50:37 -0700749 * Gets the pushed route intents.
750 *
751 * @return the pushed route intents
752 */
753 public Collection<MultiPointToSinglePointIntent> getPushedRouteIntents() {
754 List<MultiPointToSinglePointIntent> pushedIntents = new LinkedList<>();
755
756 for (Map.Entry<IpPrefix, MultiPointToSinglePointIntent> entry :
757 pushedRouteIntents.entrySet()) {
758 pushedIntents.add(entry.getValue());
759 }
760 return pushedIntents;
761 }
762
763 /**
Jonathan Hart335ef462014-10-16 08:20:46 -0700764 * Listener for host events.
765 */
766 class InternalHostListener implements HostListener {
767 @Override
768 public void event(HostEvent event) {
769 if (event.type() == HostEvent.Type.HOST_ADDED ||
770 event.type() == HostEvent.Type.HOST_UPDATED) {
771 Host host = event.subject();
Pavlin Radoslavov33f228a2014-10-27 19:33:16 -0700772 for (IpAddress ip : host.ipAddresses()) {
773 updateMac(ip, host.mac());
Jonathan Hart335ef462014-10-16 08:20:46 -0700774 }
775 }
776 }
777 }
778}