blob: 6ab1f03a223b7103613dfcb7380b725256f5668e [file] [log] [blame]
Jonathan Hartbfc5c482016-04-05 18:57:00 -07001/*
Jonathan Hart96c146b2017-02-24 16:32:00 -08002 * Copyright 2017-present Open Networking Laboratory
Jonathan Hartbfc5c482016-04-05 18:57:00 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.incubator.net.routing.impl;
18
19import org.apache.felix.scr.annotations.Activate;
20import org.apache.felix.scr.annotations.Component;
21import org.apache.felix.scr.annotations.Deactivate;
22import org.apache.felix.scr.annotations.Reference;
23import org.apache.felix.scr.annotations.ReferenceCardinality;
24import org.apache.felix.scr.annotations.Service;
25import org.onlab.packet.IpAddress;
Jonathan Hartf7021682017-03-22 18:17:21 -070026import org.onlab.packet.IpPrefix;
Jonathan Hart96c146b2017-02-24 16:32:00 -080027import org.onosproject.incubator.net.routing.InternalRouteEvent;
Jonathan Hartfd176612016-04-11 10:42:10 -070028import org.onosproject.incubator.net.routing.NextHop;
Jonathan Hartbfc5c482016-04-05 18:57:00 -070029import org.onosproject.incubator.net.routing.ResolvedRoute;
30import org.onosproject.incubator.net.routing.Route;
31import org.onosproject.incubator.net.routing.RouteAdminService;
32import org.onosproject.incubator.net.routing.RouteEvent;
Jonathan Hart96c146b2017-02-24 16:32:00 -080033import org.onosproject.incubator.net.routing.RouteInfo;
Jonathan Hartbfc5c482016-04-05 18:57:00 -070034import org.onosproject.incubator.net.routing.RouteListener;
35import org.onosproject.incubator.net.routing.RouteService;
Jonathan Hart96c146b2017-02-24 16:32:00 -080036import org.onosproject.incubator.net.routing.RouteSet;
Jonathan Hartbfc5c482016-04-05 18:57:00 -070037import org.onosproject.incubator.net.routing.RouteStore;
38import org.onosproject.incubator.net.routing.RouteStoreDelegate;
39import org.onosproject.incubator.net.routing.RouteTableId;
40import org.onosproject.net.Host;
41import org.onosproject.net.host.HostEvent;
42import org.onosproject.net.host.HostListener;
43import org.onosproject.net.host.HostService;
44import org.slf4j.Logger;
45import org.slf4j.LoggerFactory;
46
47import javax.annotation.concurrent.GuardedBy;
48import java.util.Collection;
49import java.util.Collections;
Jonathan Hart96c146b2017-02-24 16:32:00 -080050import java.util.Comparator;
Jonathan Hartbfc5c482016-04-05 18:57:00 -070051import java.util.HashMap;
52import java.util.Map;
Jonathan Hart96c146b2017-02-24 16:32:00 -080053import java.util.Objects;
Jonathan Hartbfc5c482016-04-05 18:57:00 -070054import java.util.Optional;
55import java.util.Set;
56import java.util.concurrent.BlockingQueue;
57import java.util.concurrent.ExecutorService;
58import java.util.concurrent.LinkedBlockingQueue;
59import java.util.concurrent.ThreadFactory;
60import java.util.function.Function;
61import java.util.stream.Collectors;
62
63import static java.util.concurrent.Executors.newSingleThreadExecutor;
64import static org.onlab.util.Tools.groupedThreads;
65
66/**
67 * Implementation of the unicast route service.
68 */
69@Service
70@Component
Jonathan Hartf7021682017-03-22 18:17:21 -070071public class RouteManager implements RouteService, RouteAdminService {
Jonathan Hartbfc5c482016-04-05 18:57:00 -070072
73 private final Logger log = LoggerFactory.getLogger(getClass());
74
75 private RouteStoreDelegate delegate = new InternalRouteStoreDelegate();
76 private InternalHostListener hostListener = new InternalHostListener();
77
78 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
79 protected RouteStore routeStore;
80
81 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
82 protected HostService hostService;
83
Jonathan Hart96c146b2017-02-24 16:32:00 -080084 private ResolvedRouteStore resolvedRouteStore;
85
Jonathan Hartbfc5c482016-04-05 18:57:00 -070086 @GuardedBy(value = "this")
87 private Map<RouteListener, ListenerQueue> listeners = new HashMap<>();
88
89 private ThreadFactory threadFactory;
90
91 @Activate
92 protected void activate() {
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070093 threadFactory = groupedThreads("onos/route", "listener-%d", log);
Jonathan Hartbfc5c482016-04-05 18:57:00 -070094
Jonathan Hart96c146b2017-02-24 16:32:00 -080095 resolvedRouteStore = new DefaultResolvedRouteStore();
96
Jonathan Hartbfc5c482016-04-05 18:57:00 -070097 routeStore.setDelegate(delegate);
98 hostService.addListener(hostListener);
Jonathan Hart96c146b2017-02-24 16:32:00 -080099
100 routeStore.getRouteTables().stream()
101 .flatMap(id -> routeStore.getRoutes(id).stream())
102 .forEach(this::resolve);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700103 }
104
105 @Deactivate
106 protected void deactivate() {
Jonathan Hart96c146b2017-02-24 16:32:00 -0800107 listeners.values().forEach(ListenerQueue::stop);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700108
109 routeStore.unsetDelegate(delegate);
110 hostService.removeListener(hostListener);
111 }
112
113 /**
114 * {@inheritDoc}
115 *
116 * In a departure from other services in ONOS, calling addListener will
117 * cause all current routes to be pushed to the listener before any new
118 * events are sent. This allows a listener to easily get the exact set of
119 * routes without worrying about missing any.
120 *
121 * @param listener listener to be added
122 */
123 @Override
124 public void addListener(RouteListener listener) {
125 synchronized (this) {
126 log.debug("Synchronizing current routes to new listener");
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700127 ListenerQueue l = createListenerQueue(listener);
Jonathan Hart96c146b2017-02-24 16:32:00 -0800128 resolvedRouteStore.getRouteTables().stream()
129 .map(resolvedRouteStore::getRoutes)
130 .flatMap(Collection::stream)
Jonathan Hartf7021682017-03-22 18:17:21 -0700131 .map(route -> new RouteEvent(RouteEvent.Type.ROUTE_ADDED, route,
132 resolvedRouteStore.getAllRoutes(route.prefix())))
Jonathan Hart96c146b2017-02-24 16:32:00 -0800133 .forEach(l::post);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700134
135 listeners.put(listener, l);
136
137 l.start();
138 log.debug("Route synchronization complete");
139 }
140 }
141
142 @Override
143 public void removeListener(RouteListener listener) {
144 synchronized (this) {
145 ListenerQueue l = listeners.remove(listener);
146 if (l != null) {
147 l.stop();
148 }
149 }
150 }
151
152 /**
153 * Posts an event to all listeners.
154 *
155 * @param event event
156 */
157 private void post(RouteEvent event) {
Jonathan Hart96c146b2017-02-24 16:32:00 -0800158 if (event != null) {
159 log.debug("Sending event {}", event);
160 synchronized (this) {
161 listeners.values().forEach(l -> l.post(event));
162 }
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700163 }
164 }
165
166 @Override
167 public Map<RouteTableId, Collection<Route>> getAllRoutes() {
168 return routeStore.getRouteTables().stream()
169 .collect(Collectors.toMap(Function.identity(),
170 table -> (table == null) ?
Jonathan Hart96c146b2017-02-24 16:32:00 -0800171 Collections.emptySet() : reformatRoutes(routeStore.getRoutes(table))));
172 }
173
174 private Collection<Route> reformatRoutes(Collection<RouteSet> routeSets) {
175 return routeSets.stream().flatMap(r -> r.routes().stream()).collect(Collectors.toList());
176 }
177
178 public Collection<RouteTableId> getRouteTables() {
179 return routeStore.getRouteTables();
180 }
181
182 @Override
183 public Collection<RouteInfo> getRoutes(RouteTableId id) {
184 return routeStore.getRoutes(id).stream()
185 .map(routeSet -> new RouteInfo(routeSet.prefix(),
186 resolvedRouteStore.getRoute(routeSet.prefix()).orElse(null), resolveRouteSet(routeSet)))
187 .collect(Collectors.toList());
188 }
189
190 private Set<ResolvedRoute> resolveRouteSet(RouteSet routeSet) {
191 return routeSet.routes().stream()
192 .map(this::tryResolve)
193 .collect(Collectors.toSet());
194 }
195
196 private ResolvedRoute tryResolve(Route route) {
197 ResolvedRoute resolvedRoute = resolve(route);
198 if (resolvedRoute == null) {
199 resolvedRoute = new ResolvedRoute(route, null, null);
200 }
201 return resolvedRoute;
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700202 }
203
204 @Override
205 public Route longestPrefixMatch(IpAddress ip) {
Jonathan Hart96c146b2017-02-24 16:32:00 -0800206 return longestPrefixLookup(ip)
Jonathan Hart10dbafd2017-05-18 15:53:03 -0700207 .map(ResolvedRoute::route)
Jonathan Hart96c146b2017-02-24 16:32:00 -0800208 .orElse(null);
209 }
210
211 @Override
212 public Optional<ResolvedRoute> longestPrefixLookup(IpAddress ip) {
213 return resolvedRouteStore.longestPrefixMatch(ip);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700214 }
215
216 @Override
Jonathan Hartfd176612016-04-11 10:42:10 -0700217 public Collection<Route> getRoutesForNextHop(IpAddress nextHop) {
218 return routeStore.getRoutesForNextHop(nextHop);
219 }
220
221 @Override
222 public Set<NextHop> getNextHops() {
223 return routeStore.getNextHops().entrySet().stream()
Charles Chanc78a0982016-11-09 16:52:11 -0800224 .map(entry -> new NextHop(entry.getKey(), entry.getValue()))
Jonathan Hartfd176612016-04-11 10:42:10 -0700225 .collect(Collectors.toSet());
226 }
227
228 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700229 public void update(Collection<Route> routes) {
230 synchronized (this) {
231 routes.forEach(route -> {
Jonathan Hartfd176612016-04-11 10:42:10 -0700232 log.debug("Received update {}", route);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700233 routeStore.updateRoute(route);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700234 });
235 }
236 }
237
238 @Override
239 public void withdraw(Collection<Route> routes) {
240 synchronized (this) {
Jonathan Hartfd176612016-04-11 10:42:10 -0700241 routes.forEach(route -> {
Charles Chanb21d69a2016-11-11 17:46:14 -0800242 log.debug("Received withdraw {}", route);
Jonathan Hartfd176612016-04-11 10:42:10 -0700243 routeStore.removeRoute(route);
244 });
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700245 }
246 }
247
Jonathan Hart96c146b2017-02-24 16:32:00 -0800248 private ResolvedRoute resolve(Route route) {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700249 hostService.startMonitoringIp(route.nextHop());
Jonathan Hart96c146b2017-02-24 16:32:00 -0800250 Set<Host> hosts = hostService.getHostsByIp(route.nextHop());
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700251
Jonathan Hart96c146b2017-02-24 16:32:00 -0800252 Optional<Host> host = hosts.stream().findFirst();
253 if (host.isPresent()) {
Charles Chan92ca94d2017-03-17 18:05:22 -0700254 return new ResolvedRoute(route, host.get().mac(), host.get().vlan(),
255 host.get().location());
Jonathan Hart96c146b2017-02-24 16:32:00 -0800256 } else {
257 return null;
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700258 }
Jonathan Hart96c146b2017-02-24 16:32:00 -0800259 }
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700260
Jonathan Hart96c146b2017-02-24 16:32:00 -0800261 private ResolvedRoute decide(ResolvedRoute route1, ResolvedRoute route2) {
Jonathan Hartf7021682017-03-22 18:17:21 -0700262 return Comparator.comparing(ResolvedRoute::nextHop)
Jonathan Hart96c146b2017-02-24 16:32:00 -0800263 .compare(route1, route2) <= 0 ? route1 : route2;
264 }
265
Jonathan Hartf7021682017-03-22 18:17:21 -0700266 private void store(ResolvedRoute route, Set<ResolvedRoute> alternatives) {
267 post(resolvedRouteStore.updateRoute(route, alternatives));
268 }
269
270 private void remove(IpPrefix prefix) {
271 post(resolvedRouteStore.removeRoute(prefix));
Jonathan Hart96c146b2017-02-24 16:32:00 -0800272 }
273
274 private void resolve(RouteSet routes) {
Jonathan Hartf7021682017-03-22 18:17:21 -0700275 Set<ResolvedRoute> resolvedRoutes = routes.routes().stream()
276 .map(this::resolve)
277 .filter(Objects::nonNull)
278 .collect(Collectors.toSet());
279
280 Optional<ResolvedRoute> bestRoute = resolvedRoutes.stream()
Jonathan Hart96c146b2017-02-24 16:32:00 -0800281 .reduce(this::decide);
282
Jonathan Hartf7021682017-03-22 18:17:21 -0700283 if (bestRoute.isPresent()) {
284 store(bestRoute.get(), resolvedRoutes);
Jonathan Hart96c146b2017-02-24 16:32:00 -0800285 } else {
Jonathan Hartf7021682017-03-22 18:17:21 -0700286 remove(routes.prefix());
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700287 }
288 }
289
290 private void hostUpdated(Host host) {
Jonathan Hart96c146b2017-02-24 16:32:00 -0800291 hostChanged(host);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700292 }
293
294 private void hostRemoved(Host host) {
Jonathan Hart96c146b2017-02-24 16:32:00 -0800295 hostChanged(host);
296 }
297
298 private void hostChanged(Host host) {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700299 synchronized (this) {
Jonathan Hart96c146b2017-02-24 16:32:00 -0800300 host.ipAddresses().stream()
301 .flatMap(ip -> routeStore.getRoutesForNextHop(ip).stream())
302 .map(route -> routeStore.getRoutes(route.prefix()))
303 .forEach(this::resolve);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700304 }
305 }
306
307 /**
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700308 * Creates a new listener queue.
309 *
310 * @param listener route listener
311 * @return listener queue
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700312 */
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700313 ListenerQueue createListenerQueue(RouteListener listener) {
314 return new DefaultListenerQueue(listener);
315 }
316
317 /**
318 * Default route listener queue.
319 */
320 private class DefaultListenerQueue implements ListenerQueue {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700321
322 private final ExecutorService executorService;
323 private final BlockingQueue<RouteEvent> queue;
324 private final RouteListener listener;
325
326 /**
327 * Creates a new listener queue.
328 *
329 * @param listener route listener to queue updates for
330 */
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700331 public DefaultListenerQueue(RouteListener listener) {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700332 this.listener = listener;
333 queue = new LinkedBlockingQueue<>();
334 executorService = newSingleThreadExecutor(threadFactory);
335 }
336
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700337 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700338 public void post(RouteEvent event) {
339 queue.add(event);
340 }
341
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700342 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700343 public void start() {
344 executorService.execute(this::poll);
345 }
346
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700347 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700348 public void stop() {
349 executorService.shutdown();
350 }
351
352 private void poll() {
Jonathan Hartf79ab482016-08-19 14:20:50 -0700353 while (true) {
354 try {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700355 listener.event(queue.take());
Jonathan Hartf79ab482016-08-19 14:20:50 -0700356 } catch (InterruptedException e) {
357 log.info("Route listener event thread shutting down: {}", e.getMessage());
358 break;
359 } catch (Exception e) {
360 log.warn("Exception during route event handler", e);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700361 }
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700362 }
363 }
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700364 }
365
366 /**
367 * Delegate to receive events from the route store.
368 */
369 private class InternalRouteStoreDelegate implements RouteStoreDelegate {
370 @Override
Jonathan Hart96c146b2017-02-24 16:32:00 -0800371 public void notify(InternalRouteEvent event) {
372 switch (event.type()) {
373 case ROUTE_ADDED:
374 resolve(event.subject());
375 break;
376 case ROUTE_REMOVED:
377 resolve(event.subject());
378 break;
379 default:
380 break;
381 }
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700382 }
383 }
384
385 /**
386 * Internal listener for host events.
387 */
388 private class InternalHostListener implements HostListener {
389 @Override
390 public void event(HostEvent event) {
391 switch (event.type()) {
392 case HOST_ADDED:
393 case HOST_UPDATED:
394 hostUpdated(event.subject());
395 break;
396 case HOST_REMOVED:
397 hostRemoved(event.subject());
398 break;
399 case HOST_MOVED:
400 break;
401 default:
402 break;
403 }
404 }
405 }
406
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700407}