blob: 3ae5b82e3388025e8f9489b9f3297e6037127a40 [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;
Pavlin Radoslavov6b570732014-11-06 13:16:45 -080056import org.onlab.packet.Ip4Address;
57import org.onlab.packet.Ip4Prefix;
Thomas Vachuskab97cf282014-10-20 23:31:12 -070058import org.onlab.packet.MacAddress;
59import org.slf4j.Logger;
60import org.slf4j.LoggerFactory;
61
Pingping3855f312014-10-22 12:50:37 -070062import com.google.common.base.Objects;
63import com.google.common.collect.HashMultimap;
64import com.google.common.collect.Multimaps;
65import com.google.common.collect.SetMultimap;
66import com.google.common.util.concurrent.ThreadFactoryBuilder;
67import com.googlecode.concurrenttrees.common.KeyValuePair;
68import com.googlecode.concurrenttrees.radix.node.concrete.DefaultByteArrayNodeFactory;
69import com.googlecode.concurrenttrees.radixinverted.ConcurrentInvertedRadixTree;
70import com.googlecode.concurrenttrees.radixinverted.InvertedRadixTree;
Jonathan Hart335ef462014-10-16 08:20:46 -070071
Jonathan Hart335ef462014-10-16 08:20:46 -070072/**
73 * This class processes BGP route update, translates each update into a intent
74 * and submits the intent.
Jonathan Hart335ef462014-10-16 08:20:46 -070075 */
76public class Router implements RouteListener {
77
78 private static final Logger log = LoggerFactory.getLogger(Router.class);
79
Jonathan Hart0b04bed2014-10-16 16:39:19 -070080 // Store all route updates in a radix tree.
81 // The key in this tree is the binary string of prefix of the route.
Jonathan Hart335ef462014-10-16 08:20:46 -070082 private InvertedRadixTree<RouteEntry> bgpRoutes;
83
84 // Stores all incoming route updates in a queue.
85 private BlockingQueue<RouteUpdate> routeUpdates;
86
Pavlin Radoslavov6b570732014-11-06 13:16:45 -080087 // The Ip4Address is the next hop address of each route update.
88 private SetMultimap<Ip4Address, RouteEntry> routesWaitingOnArp;
89 private ConcurrentHashMap<Ip4Prefix, MultiPointToSinglePointIntent> pushedRouteIntents;
Jonathan Hart335ef462014-10-16 08:20:46 -070090
91 private IntentService intentService;
Jonathan Hart335ef462014-10-16 08:20:46 -070092 private HostService hostService;
Jonathan Hart31582d12014-10-22 13:52:41 -070093 private SdnIpConfigService configService;
Jonathan Hart335ef462014-10-16 08:20:46 -070094 private InterfaceService interfaceService;
95
96 private ExecutorService bgpUpdatesExecutor;
97 private ExecutorService bgpIntentsSynchronizerExecutor;
98
Thomas Vachuskab97cf282014-10-20 23:31:12 -070099 private final ApplicationId appId;
Jonathan Hart335ef462014-10-16 08:20:46 -0700100
101 //
102 // State to deal with SDN-IP Leader election and pushing Intents
103 //
104 private Semaphore intentsSynchronizerSemaphore = new Semaphore(0);
105 private volatile boolean isElectedLeader = false;
106 private volatile boolean isActivatedLeader = false;
107
Jonathan Hartbcae7bd2014-10-16 10:24:41 -0700108 // For routes announced by local BGP daemon in SDN network,
Jonathan Hart335ef462014-10-16 08:20:46 -0700109 // the next hop will be 0.0.0.0.
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800110 public static final Ip4Address LOCAL_NEXT_HOP =
111 Ip4Address.valueOf("0.0.0.0");
Jonathan Hart335ef462014-10-16 08:20:46 -0700112
113 /**
114 * Class constructor.
115 *
Jonathan Hart31582d12014-10-22 13:52:41 -0700116 * @param appId the application ID
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700117 * @param intentService the intent service
118 * @param hostService the host service
Jonathan Hart31582d12014-10-22 13:52:41 -0700119 * @param configService the configuration service
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700120 * @param interfaceService the interface service
Jonathan Hart335ef462014-10-16 08:20:46 -0700121 */
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700122 public Router(ApplicationId appId, IntentService intentService,
Jonathan Hart31582d12014-10-22 13:52:41 -0700123 HostService hostService, SdnIpConfigService configService,
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700124 InterfaceService interfaceService) {
125 this.appId = appId;
Jonathan Hart335ef462014-10-16 08:20:46 -0700126 this.intentService = intentService;
127 this.hostService = hostService;
Jonathan Hart31582d12014-10-22 13:52:41 -0700128 this.configService = configService;
Jonathan Hart335ef462014-10-16 08:20:46 -0700129 this.interfaceService = interfaceService;
130
131 bgpRoutes = new ConcurrentInvertedRadixTree<>(
132 new DefaultByteArrayNodeFactory());
133 routeUpdates = new LinkedBlockingQueue<>();
134 routesWaitingOnArp = Multimaps.synchronizedSetMultimap(
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800135 HashMultimap.<Ip4Address, RouteEntry>create());
Jonathan Hart335ef462014-10-16 08:20:46 -0700136 pushedRouteIntents = new ConcurrentHashMap<>();
137
138 bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
139 new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
140 bgpIntentsSynchronizerExecutor = Executors.newSingleThreadExecutor(
141 new ThreadFactoryBuilder()
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700142 .setNameFormat("bgp-intents-synchronizer-%d").build());
Jonathan Hartab63aac2014-10-16 08:52:55 -0700143
144 this.hostService.addListener(new InternalHostListener());
Jonathan Hart335ef462014-10-16 08:20:46 -0700145 }
146
147 /**
Jonathan Hart739c8352014-10-29 17:49:26 -0700148 * Starts the router.
Jonathan Hart335ef462014-10-16 08:20:46 -0700149 */
150 public void start() {
Jonathan Hart335ef462014-10-16 08:20:46 -0700151 bgpUpdatesExecutor.execute(new Runnable() {
152 @Override
153 public void run() {
154 doUpdatesThread();
155 }
156 });
157
158 bgpIntentsSynchronizerExecutor.execute(new Runnable() {
159 @Override
160 public void run() {
161 doIntentSynchronizationThread();
162 }
163 });
164 }
165
Jonathan Hart739c8352014-10-29 17:49:26 -0700166 /**
167 * Shuts the router down.
168 */
169 public void shutdown() {
170 bgpUpdatesExecutor.shutdownNow();
171 bgpIntentsSynchronizerExecutor.shutdownNow();
172 }
173
Jonathan Hart335ef462014-10-16 08:20:46 -0700174 //@Override TODO hook this up to something
175 public void leaderChanged(boolean isLeader) {
176 log.debug("Leader changed: {}", isLeader);
177
178 if (!isLeader) {
179 this.isElectedLeader = false;
180 this.isActivatedLeader = false;
181 return; // Nothing to do
182 }
183 this.isActivatedLeader = false;
184 this.isElectedLeader = true;
185
186 //
187 // Tell the Intents Synchronizer thread to start the synchronization
188 //
189 intentsSynchronizerSemaphore.release();
190 }
191
192 @Override
193 public void update(RouteUpdate routeUpdate) {
Jonathan Hart31582d12014-10-22 13:52:41 -0700194 log.debug("Received new route update: {}", routeUpdate);
Jonathan Hart335ef462014-10-16 08:20:46 -0700195
196 try {
197 routeUpdates.put(routeUpdate);
198 } catch (InterruptedException e) {
199 log.debug("Interrupted while putting on routeUpdates queue", e);
200 Thread.currentThread().interrupt();
201 }
202 }
203
204 /**
205 * Thread for Intent Synchronization.
206 */
207 private void doIntentSynchronizationThread() {
208 boolean interrupted = false;
209 try {
210 while (!interrupted) {
211 try {
212 intentsSynchronizerSemaphore.acquire();
213 //
214 // Drain all permits, because a single synchronization is
215 // sufficient.
216 //
217 intentsSynchronizerSemaphore.drainPermits();
218 } catch (InterruptedException e) {
219 log.debug("Interrupted while waiting to become " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700220 "Intent Synchronization leader");
Jonathan Hart335ef462014-10-16 08:20:46 -0700221 interrupted = true;
222 break;
223 }
224 syncIntents();
225 }
226 } finally {
227 if (interrupted) {
228 Thread.currentThread().interrupt();
229 }
230 }
231 }
232
233 /**
234 * Thread for handling route updates.
235 */
236 private void doUpdatesThread() {
237 boolean interrupted = false;
238 try {
239 while (!interrupted) {
240 try {
241 RouteUpdate update = routeUpdates.take();
242 switch (update.type()) {
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700243 case UPDATE:
244 processRouteAdd(update.routeEntry());
245 break;
246 case DELETE:
247 processRouteDelete(update.routeEntry());
248 break;
249 default:
250 log.error("Unknown update Type: {}", update.type());
251 break;
Jonathan Hart335ef462014-10-16 08:20:46 -0700252 }
253 } catch (InterruptedException e) {
254 log.debug("Interrupted while taking from updates queue", e);
255 interrupted = true;
256 } catch (Exception e) {
257 log.debug("exception", e);
258 }
259 }
260 } finally {
261 if (interrupted) {
262 Thread.currentThread().interrupt();
263 }
264 }
265 }
266
267 /**
268 * Performs Intents Synchronization between the internally stored Route
269 * Intents and the installed Route Intents.
270 */
271 private void syncIntents() {
272 synchronized (this) {
273 if (!isElectedLeader) {
274 return; // Nothing to do: not the leader anymore
275 }
276 log.debug("Syncing SDN-IP Route Intents...");
277
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800278 Map<Ip4Prefix, MultiPointToSinglePointIntent> fetchedIntents =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700279 new HashMap<>();
Jonathan Hart335ef462014-10-16 08:20:46 -0700280
281 //
282 // Fetch all intents, and classify the Multi-Point-to-Point Intents
283 // based on the matching prefix.
284 //
285 for (Intent intent : intentService.getIntents()) {
Jonathan Hartec2df012014-10-23 16:40:24 -0700286
287 if (!(intent instanceof MultiPointToSinglePointIntent)
288 || !intent.appId().equals(appId)) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700289 continue;
290 }
291 MultiPointToSinglePointIntent mp2pIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700292 (MultiPointToSinglePointIntent) intent;
Jonathan Hartec2df012014-10-23 16:40:24 -0700293
294 Criterion c = mp2pIntent.selector().getCriterion(Type.IPV4_DST);
295 if (c != null && c instanceof IPCriterion) {
296 IPCriterion ipCriterion = (IPCriterion) c;
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800297 Ip4Prefix ip4Prefix = ipCriterion.ip().getIp4Prefix();
298 if (ip4Prefix == null) {
299 // TODO: For now we support only IPv4
300 continue;
301 }
302 fetchedIntents.put(ip4Prefix, mp2pIntent);
Jonathan Hartec2df012014-10-23 16:40:24 -0700303 } else {
304 log.warn("No IPV4_DST criterion found for intent {}",
305 mp2pIntent.id());
Jonathan Hart335ef462014-10-16 08:20:46 -0700306 }
307
308 }
309
310 //
311 // Compare for each prefix the local IN-MEMORY Intents with the
312 // FETCHED Intents:
313 // - If the IN-MEMORY Intent is same as the FETCHED Intent, store
314 // the FETCHED Intent in the local memory (i.e., override the
315 // IN-MEMORY Intent) to preserve the original Intent ID
316 // - if the IN-MEMORY Intent is not same as the FETCHED Intent,
317 // delete the FETCHED Intent, and push/install the IN-MEMORY
318 // Intent.
319 // - If there is an IN-MEMORY Intent for a prefix, but no FETCHED
320 // Intent for same prefix, then push/install the IN-MEMORY
321 // Intent.
322 // - If there is a FETCHED Intent for a prefix, but no IN-MEMORY
323 // Intent for same prefix, then delete/withdraw the FETCHED
324 // Intent.
325 //
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800326 Collection<Pair<Ip4Prefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700327 storeInMemoryIntents = new LinkedList<>();
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800328 Collection<Pair<Ip4Prefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700329 addIntents = new LinkedList<>();
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800330 Collection<Pair<Ip4Prefix, MultiPointToSinglePointIntent>>
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700331 deleteIntents = new LinkedList<>();
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800332 for (Map.Entry<Ip4Prefix, MultiPointToSinglePointIntent> entry :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700333 pushedRouteIntents.entrySet()) {
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800334 Ip4Prefix prefix = entry.getKey();
Jonathan Hart335ef462014-10-16 08:20:46 -0700335 MultiPointToSinglePointIntent inMemoryIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700336 entry.getValue();
Jonathan Hart335ef462014-10-16 08:20:46 -0700337 MultiPointToSinglePointIntent fetchedIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700338 fetchedIntents.get(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700339
340 if (fetchedIntent == null) {
341 //
342 // No FETCHED Intent for same prefix: push the IN-MEMORY
343 // Intent.
344 //
345 addIntents.add(Pair.of(prefix, inMemoryIntent));
346 continue;
347 }
348
Jonathan Hartec2df012014-10-23 16:40:24 -0700349 IntentState state = intentService.getIntentState(fetchedIntent.id());
350 if (state == IntentState.WITHDRAWING ||
351 state == IntentState.WITHDRAWN) {
352 // The intent has been withdrawn but according to our route
353 // table it should be installed. We'll reinstall it.
354 addIntents.add(Pair.of(prefix, inMemoryIntent));
355 }
356
Jonathan Hart335ef462014-10-16 08:20:46 -0700357 //
358 // If IN-MEMORY Intent is same as the FETCHED Intent,
359 // store the FETCHED Intent in the local memory.
360 //
361 if (compareMultiPointToSinglePointIntents(inMemoryIntent,
362 fetchedIntent)) {
363 storeInMemoryIntents.add(Pair.of(prefix, fetchedIntent));
364 } else {
365 //
366 // The IN-MEMORY Intent is not same as the FETCHED Intent,
367 // hence delete the FETCHED Intent, and install the
368 // IN-MEMORY Intent.
369 //
370 deleteIntents.add(Pair.of(prefix, fetchedIntent));
371 addIntents.add(Pair.of(prefix, inMemoryIntent));
372 }
373 fetchedIntents.remove(prefix);
374 }
375
376 //
377 // Any remaining FETCHED Intents have to be deleted/withdrawn
378 //
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800379 for (Map.Entry<Ip4Prefix, MultiPointToSinglePointIntent> entry :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700380 fetchedIntents.entrySet()) {
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800381 Ip4Prefix prefix = entry.getKey();
Jonathan Hart335ef462014-10-16 08:20:46 -0700382 MultiPointToSinglePointIntent fetchedIntent = entry.getValue();
383 deleteIntents.add(Pair.of(prefix, fetchedIntent));
384 }
385
386 //
387 // Perform the actions:
388 // 1. Store in memory fetched intents that are same. Can be done
389 // even if we are not the leader anymore
390 // 2. Delete intents: check if the leader before each operation
391 // 3. Add intents: check if the leader before each operation
392 //
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800393 for (Pair<Ip4Prefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700394 storeInMemoryIntents) {
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800395 Ip4Prefix prefix = pair.getLeft();
Jonathan Hart335ef462014-10-16 08:20:46 -0700396 MultiPointToSinglePointIntent intent = pair.getRight();
397 log.debug("Intent synchronization: updating in-memory " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700398 "Intent for prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700399 pushedRouteIntents.put(prefix, intent);
400 }
401 //
402 isActivatedLeader = true; // Allow push of Intents
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800403 for (Pair<Ip4Prefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700404 deleteIntents) {
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800405 Ip4Prefix prefix = pair.getLeft();
Jonathan Hart335ef462014-10-16 08:20:46 -0700406 MultiPointToSinglePointIntent intent = pair.getRight();
407 if (!isElectedLeader) {
408 isActivatedLeader = false;
409 return;
410 }
411 log.debug("Intent synchronization: deleting Intent for " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700412 "prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700413 intentService.withdraw(intent);
414 }
415 //
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800416 for (Pair<Ip4Prefix, MultiPointToSinglePointIntent> pair :
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700417 addIntents) {
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800418 Ip4Prefix prefix = pair.getLeft();
Jonathan Hart335ef462014-10-16 08:20:46 -0700419 MultiPointToSinglePointIntent intent = pair.getRight();
420 if (!isElectedLeader) {
421 isActivatedLeader = false;
422 return;
423 }
424 log.debug("Intent synchronization: adding Intent for " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700425 "prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700426 intentService.submit(intent);
427 }
428 if (!isElectedLeader) {
429 isActivatedLeader = false;
430 }
431 log.debug("Syncing SDN-IP routes completed.");
432 }
433 }
434
435 /**
436 * Compares two Multi-point to Single Point Intents whether they represent
437 * same logical intention.
438 *
439 * @param intent1 the first Intent to compare
440 * @param intent2 the second Intent to compare
441 * @return true if both Intents represent same logical intention, otherwise
442 * false
443 */
444 private boolean compareMultiPointToSinglePointIntents(
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700445 MultiPointToSinglePointIntent intent1,
446 MultiPointToSinglePointIntent intent2) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700447
Pingpingf5d90932014-10-27 10:50:04 -0700448 return Objects.equal(intent1.appId(), intent2.appId()) &&
449 Objects.equal(intent1.selector(), intent2.selector()) &&
Jonathan Hart335ef462014-10-16 08:20:46 -0700450 Objects.equal(intent1.treatment(), intent2.treatment()) &&
451 Objects.equal(intent1.ingressPoints(), intent2.ingressPoints()) &&
452 Objects.equal(intent1.egressPoint(), intent2.egressPoint());
453 }
454
455 /**
456 * Processes adding a route entry.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700457 * <p>
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700458 * Put new route entry into the radix tree. If there was an existing
459 * next hop for this prefix, but the next hop was different, then execute
Jonathan Hart335ef462014-10-16 08:20:46 -0700460 * deleting old route entry. If the next hop is the SDN domain, we do not
461 * handle it at the moment. Otherwise, execute adding a route.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700462 * </p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700463 *
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
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800470 Ip4Prefix prefix = routeEntry.prefix();
471 Ip4Address nextHop = null;
Jonathan Hart335ef462014-10-16 08:20:46 -0700472 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.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700503 * <p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700504 * 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.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700508 * </p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700509 *
510 * @param routeEntry the route entry to add
511 */
512 private void executeRouteAdd(RouteEntry routeEntry) {
513 log.debug("Executing route add: {}", routeEntry);
514
Jonathan Hart31582d12014-10-22 13:52:41 -0700515 // Monitor the IP address so we'll get notified of updates to the MAC
516 // address.
517 hostService.startMonitoringIp(routeEntry.nextHop());
518
Jonathan Hart335ef462014-10-16 08:20:46 -0700519 // See if we know the MAC address of the next hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700520 MacAddress nextHopMacAddress = null;
Pavlin Radoslavov33f228a2014-10-27 19:33:16 -0700521 Set<Host> hosts = hostService.getHostsByIp(routeEntry.nextHop());
Jonathan Hart335ef462014-10-16 08:20:46 -0700522 if (!hosts.isEmpty()) {
523 // TODO how to handle if multiple hosts are returned?
524 nextHopMacAddress = hosts.iterator().next().mac();
525 }
526
527 if (nextHopMacAddress == null) {
528 routesWaitingOnArp.put(routeEntry.nextHop(), routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700529 return;
530 }
531
532 addRouteIntentToNextHop(routeEntry.prefix(),
533 routeEntry.nextHop(),
534 nextHopMacAddress);
535 }
536
537 /**
538 * Adds a route intent given a prefix and a next hop IP address. This
539 * method will find the egress interface for the intent.
540 *
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700541 * @param prefix IP prefix of the route to add
542 * @param nextHopIpAddress IP address of the next hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700543 * @param nextHopMacAddress MAC address of the next hop
544 */
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800545 private void addRouteIntentToNextHop(Ip4Prefix prefix,
546 Ip4Address nextHopIpAddress,
Jonathan Hart335ef462014-10-16 08:20:46 -0700547 MacAddress nextHopMacAddress) {
548
549 // Find the attachment point (egress interface) of the next hop
550 Interface egressInterface;
Jonathan Hart31582d12014-10-22 13:52:41 -0700551 if (configService.getBgpPeers().containsKey(nextHopIpAddress)) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700552 // Route to a peer
553 log.debug("Route to peer {}", nextHopIpAddress);
554 BgpPeer peer =
Jonathan Hart31582d12014-10-22 13:52:41 -0700555 configService.getBgpPeers().get(nextHopIpAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700556 egressInterface =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700557 interfaceService.getInterface(peer.connectPoint());
Jonathan Hart335ef462014-10-16 08:20:46 -0700558 } else {
559 // Route to non-peer
560 log.debug("Route to non-peer {}", nextHopIpAddress);
561 egressInterface =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700562 interfaceService.getMatchingInterface(nextHopIpAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700563 if (egressInterface == null) {
564 log.warn("No outgoing interface found for {}",
565 nextHopIpAddress);
566 return;
567 }
568 }
569
570 doAddRouteIntent(prefix, egressInterface, nextHopMacAddress);
571 }
572
573 /**
574 * Installs a route intent for a prefix.
575 * <p/>
576 * Intent will match dst IP prefix and rewrite dst MAC address at all other
577 * border switches, then forward packets according to dst MAC address.
578 *
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700579 * @param prefix IP prefix from route
580 * @param egressInterface egress Interface connected to next hop router
Jonathan Hart335ef462014-10-16 08:20:46 -0700581 * @param nextHopMacAddress MAC address of next hop router
582 */
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800583 private void doAddRouteIntent(Ip4Prefix prefix, Interface egressInterface,
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700584 MacAddress nextHopMacAddress) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700585 log.debug("Adding intent for prefix {}, next hop mac {}",
586 prefix, nextHopMacAddress);
587
588 MultiPointToSinglePointIntent pushedIntent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700589 pushedRouteIntents.get(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700590
591 // Just for testing.
592 if (pushedIntent != null) {
593 log.error("There should not be a pushed intent: {}", pushedIntent);
594 }
595
596 ConnectPoint egressPort = egressInterface.connectPoint();
597
598 Set<ConnectPoint> ingressPorts = new HashSet<>();
599
600 for (Interface intf : interfaceService.getInterfaces()) {
Jonathan Hart2e3eef32014-11-12 11:05:40 -0800601 if (!intf.connectPoint().equals(egressInterface.connectPoint())) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700602 ConnectPoint srcPort = intf.connectPoint();
603 ingressPorts.add(srcPort);
604 }
605 }
606
607 // Match the destination IP prefix at the first hop
Jonathan Hart335ef462014-10-16 08:20:46 -0700608 TrafficSelector selector = DefaultTrafficSelector.builder()
609 .matchEthType(Ethernet.TYPE_IPV4)
610 .matchIPDst(prefix)
611 .build();
612
613 // Rewrite the destination MAC address
Jonathan Hart335ef462014-10-16 08:20:46 -0700614 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
615 .setEthDst(nextHopMacAddress)
616 .build();
617
618 MultiPointToSinglePointIntent intent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700619 new MultiPointToSinglePointIntent(appId, selector, treatment,
620 ingressPorts, egressPort);
Jonathan Hart335ef462014-10-16 08:20:46 -0700621
622 if (isElectedLeader && isActivatedLeader) {
623 log.debug("Intent installation: adding Intent for prefix: {}",
624 prefix);
625 intentService.submit(intent);
626 }
627
628 // Maintain the Intent
629 pushedRouteIntents.put(prefix, intent);
630 }
631
632 /**
633 * Executes deleting a route entry.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700634 * <p>
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700635 * Removes prefix from radix tree, and if successful, then try to delete
636 * the related intent.
Thomas Vachuska4b420772014-10-30 16:46:17 -0700637 * </p>
Jonathan Hart335ef462014-10-16 08:20:46 -0700638 *
639 * @param routeEntry the route entry to delete
640 */
641 protected void processRouteDelete(RouteEntry routeEntry) {
642 synchronized (this) {
643 log.debug("Processing route delete: {}", routeEntry);
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800644 Ip4Prefix prefix = routeEntry.prefix();
Jonathan Hart335ef462014-10-16 08:20:46 -0700645
Jonathan Hart335ef462014-10-16 08:20:46 -0700646 if (bgpRoutes.remove(RouteEntry.createBinaryString(prefix))) {
647 //
648 // Only delete flows if an entry was actually removed from the
649 // tree. If no entry was removed, the <prefix, nexthop> wasn't
650 // there so it's probably already been removed and we don't
651 // need to do anything.
652 //
653 executeRouteDelete(routeEntry);
654 }
655
656 routesWaitingOnArp.remove(routeEntry.nextHop(), routeEntry);
657 // TODO cancel the request in the ARP manager as well
658 }
659 }
660
661 /**
662 * Executed deleting a route entry.
663 *
664 * @param routeEntry the route entry to delete
665 */
666 private void executeRouteDelete(RouteEntry routeEntry) {
667 log.debug("Executing route delete: {}", routeEntry);
668
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800669 Ip4Prefix prefix = routeEntry.prefix();
Jonathan Hart335ef462014-10-16 08:20:46 -0700670
671 MultiPointToSinglePointIntent intent =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700672 pushedRouteIntents.remove(prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700673
674 if (intent == null) {
675 log.debug("There is no intent in pushedRouteIntents to delete " +
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700676 "for prefix: {}", prefix);
Jonathan Hart335ef462014-10-16 08:20:46 -0700677 } else {
678 if (isElectedLeader && isActivatedLeader) {
679 log.debug("Intent installation: deleting Intent for prefix: {}",
680 prefix);
681 intentService.withdraw(intent);
682 }
683 }
684 }
685
686 /**
Jonathan Hart31582d12014-10-22 13:52:41 -0700687 * Signals the Router that the MAC to IP mapping has potentially been
688 * updated. This has the effect of updating the MAC address for any
689 * installed prefixes if it has changed, as well as installing any pending
690 * prefixes that were waiting for MAC resolution.
Jonathan Hart335ef462014-10-16 08:20:46 -0700691 *
Jonathan Hart31582d12014-10-22 13:52:41 -0700692 * @param ipAddress the IP address that an event was received for
693 * @param macAddress the most recently known MAC address for the IP address
Jonathan Hart335ef462014-10-16 08:20:46 -0700694 */
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800695 private void updateMac(Ip4Address ipAddress, MacAddress macAddress) {
Jonathan Hart31582d12014-10-22 13:52:41 -0700696 log.debug("Received updated MAC info: {} => {}", ipAddress, macAddress);
697
698 // TODO here we should check whether the next hop for any of our
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800699 // installed prefixes has changed, not just prefixes pending
700 // installation.
Jonathan Hart335ef462014-10-16 08:20:46 -0700701
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700702 // We synchronize on this to prevent changes to the radix tree
703 // while we're pushing intents. If the tree changes, the
704 // tree and intents could get out of sync.
Jonathan Hart335ef462014-10-16 08:20:46 -0700705 synchronized (this) {
706
707 Set<RouteEntry> routesToPush =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700708 routesWaitingOnArp.removeAll(ipAddress);
Jonathan Hart335ef462014-10-16 08:20:46 -0700709
710 for (RouteEntry routeEntry : routesToPush) {
711 // These will always be adds
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800712 Ip4Prefix prefix = routeEntry.prefix();
Jonathan Hart335ef462014-10-16 08:20:46 -0700713 String binaryString = RouteEntry.createBinaryString(prefix);
714 RouteEntry foundRouteEntry =
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700715 bgpRoutes.getValueForExactKey(binaryString);
Jonathan Hart335ef462014-10-16 08:20:46 -0700716 if (foundRouteEntry != null &&
Thomas Vachuskab97cf282014-10-20 23:31:12 -0700717 foundRouteEntry.nextHop().equals(routeEntry.nextHop())) {
Jonathan Hart335ef462014-10-16 08:20:46 -0700718 // We only push prefix flows if the prefix is still in the
Jonathan Hart0b04bed2014-10-16 16:39:19 -0700719 // radix tree and the next hop is the same as our
Jonathan Hart335ef462014-10-16 08:20:46 -0700720 // update.
721 // The prefix could have been removed while we were waiting
722 // for the ARP, or the next hop could have changed.
723 addRouteIntentToNextHop(prefix, ipAddress, macAddress);
724 } else {
Jonathan Hart31582d12014-10-22 13:52:41 -0700725 log.debug("{} has been revoked before the MAC was resolved",
726 routeEntry);
Jonathan Hart335ef462014-10-16 08:20:46 -0700727 }
728 }
729 }
730 }
731
732 /**
733 * Gets the SDN-IP routes.
734 *
735 * @return the SDN-IP routes
736 */
737 public Collection<RouteEntry> getRoutes() {
738 Iterator<KeyValuePair<RouteEntry>> it =
739 bgpRoutes.getKeyValuePairsForKeysStartingWith("").iterator();
740
741 List<RouteEntry> routes = new LinkedList<>();
742
743 while (it.hasNext()) {
744 KeyValuePair<RouteEntry> entry = it.next();
745 routes.add(entry.getValue());
746 }
747
748 return routes;
749 }
750
751 /**
Pingping3855f312014-10-22 12:50:37 -0700752 * Gets the pushed route intents.
753 *
754 * @return the pushed route intents
755 */
756 public Collection<MultiPointToSinglePointIntent> getPushedRouteIntents() {
757 List<MultiPointToSinglePointIntent> pushedIntents = new LinkedList<>();
758
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800759 for (Map.Entry<Ip4Prefix, MultiPointToSinglePointIntent> entry :
Pingping3855f312014-10-22 12:50:37 -0700760 pushedRouteIntents.entrySet()) {
761 pushedIntents.add(entry.getValue());
762 }
763 return pushedIntents;
764 }
765
766 /**
Jonathan Hart335ef462014-10-16 08:20:46 -0700767 * Listener for host events.
768 */
769 class InternalHostListener implements HostListener {
770 @Override
771 public void event(HostEvent event) {
772 if (event.type() == HostEvent.Type.HOST_ADDED ||
773 event.type() == HostEvent.Type.HOST_UPDATED) {
774 Host host = event.subject();
Pavlin Radoslavov33f228a2014-10-27 19:33:16 -0700775 for (IpAddress ip : host.ipAddresses()) {
Pavlin Radoslavov6b570732014-11-06 13:16:45 -0800776 Ip4Address ip4Address = ip.getIp4Address();
777 if (ip4Address == null) {
778 // TODO: For now we support only IPv4
779 continue;
780 }
781 updateMac(ip4Address, host.mac());
Jonathan Hart335ef462014-10-16 08:20:46 -0700782 }
783 }
784 }
785 }
786}