blob: acca731903d11fee3cbb99fe5e075e35b3940faf [file] [log] [blame]
Jonathan Hartbfc5c482016-04-05 18:57:00 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-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 Hartbfc5c482016-04-05 18:57:00 -070026import org.onosproject.event.ListenerService;
Charles Chan8fe9f4c2016-10-24 16:46:25 -070027import org.onosproject.incubator.net.routing.NextHopData;
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;
33import org.onosproject.incubator.net.routing.RouteListener;
34import org.onosproject.incubator.net.routing.RouteService;
35import org.onosproject.incubator.net.routing.RouteStore;
36import org.onosproject.incubator.net.routing.RouteStoreDelegate;
37import org.onosproject.incubator.net.routing.RouteTableId;
38import org.onosproject.net.Host;
39import org.onosproject.net.host.HostEvent;
40import org.onosproject.net.host.HostListener;
41import org.onosproject.net.host.HostService;
42import org.slf4j.Logger;
43import org.slf4j.LoggerFactory;
44
45import javax.annotation.concurrent.GuardedBy;
46import java.util.Collection;
47import java.util.Collections;
48import java.util.HashMap;
49import java.util.Map;
50import java.util.Optional;
51import java.util.Set;
52import java.util.concurrent.BlockingQueue;
53import java.util.concurrent.ExecutorService;
54import java.util.concurrent.LinkedBlockingQueue;
55import java.util.concurrent.ThreadFactory;
56import java.util.function.Function;
57import java.util.stream.Collectors;
58
59import static java.util.concurrent.Executors.newSingleThreadExecutor;
60import static org.onlab.util.Tools.groupedThreads;
61
62/**
63 * Implementation of the unicast route service.
64 */
65@Service
66@Component
67public class RouteManager implements ListenerService<RouteEvent, RouteListener>,
68 RouteService, RouteAdminService {
69
70 private final Logger log = LoggerFactory.getLogger(getClass());
71
72 private RouteStoreDelegate delegate = new InternalRouteStoreDelegate();
73 private InternalHostListener hostListener = new InternalHostListener();
74
75 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
76 protected RouteStore routeStore;
77
78 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
79 protected HostService hostService;
80
81 @GuardedBy(value = "this")
82 private Map<RouteListener, ListenerQueue> listeners = new HashMap<>();
83
84 private ThreadFactory threadFactory;
85
86 @Activate
87 protected void activate() {
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070088 threadFactory = groupedThreads("onos/route", "listener-%d", log);
Jonathan Hartbfc5c482016-04-05 18:57:00 -070089
90 routeStore.setDelegate(delegate);
91 hostService.addListener(hostListener);
92
93 }
94
95 @Deactivate
96 protected void deactivate() {
97 listeners.values().forEach(l -> l.stop());
98
99 routeStore.unsetDelegate(delegate);
100 hostService.removeListener(hostListener);
101 }
102
103 /**
104 * {@inheritDoc}
105 *
106 * In a departure from other services in ONOS, calling addListener will
107 * cause all current routes to be pushed to the listener before any new
108 * events are sent. This allows a listener to easily get the exact set of
109 * routes without worrying about missing any.
110 *
111 * @param listener listener to be added
112 */
113 @Override
114 public void addListener(RouteListener listener) {
115 synchronized (this) {
116 log.debug("Synchronizing current routes to new listener");
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700117 ListenerQueue l = createListenerQueue(listener);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700118 routeStore.getRouteTables().forEach(table -> {
119 Collection<Route> routes = routeStore.getRoutes(table);
120 if (routes != null) {
Charles Chan8fe9f4c2016-10-24 16:46:25 -0700121 routes.forEach(route -> {
122 NextHopData nextHopData = routeStore.getNextHop(route.nextHop());
Charles Chane4d13102016-11-08 15:38:44 -0800123 l.post(new RouteEvent(RouteEvent.Type.ROUTE_ADDED,
Charles Chan8fe9f4c2016-10-24 16:46:25 -0700124 new ResolvedRoute(route, nextHopData.mac(),
125 nextHopData.location())));
126 });
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700127 }
128 });
129
130 listeners.put(listener, l);
131
132 l.start();
133 log.debug("Route synchronization complete");
134 }
135 }
136
137 @Override
138 public void removeListener(RouteListener listener) {
139 synchronized (this) {
140 ListenerQueue l = listeners.remove(listener);
141 if (l != null) {
142 l.stop();
143 }
144 }
145 }
146
147 /**
148 * Posts an event to all listeners.
149 *
150 * @param event event
151 */
152 private void post(RouteEvent event) {
Jonathan Hartfd176612016-04-11 10:42:10 -0700153 log.debug("Sending event {}", event);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700154 synchronized (this) {
155 listeners.values().forEach(l -> l.post(event));
156 }
157 }
158
159 @Override
160 public Map<RouteTableId, Collection<Route>> getAllRoutes() {
161 return routeStore.getRouteTables().stream()
162 .collect(Collectors.toMap(Function.identity(),
163 table -> (table == null) ?
164 Collections.emptySet() : routeStore.getRoutes(table)));
165 }
166
167 @Override
168 public Route longestPrefixMatch(IpAddress ip) {
169 return routeStore.longestPrefixMatch(ip);
170 }
171
172 @Override
Jonathan Hartfd176612016-04-11 10:42:10 -0700173 public Collection<Route> getRoutesForNextHop(IpAddress nextHop) {
174 return routeStore.getRoutesForNextHop(nextHop);
175 }
176
177 @Override
178 public Set<NextHop> getNextHops() {
179 return routeStore.getNextHops().entrySet().stream()
Charles Chanc78a0982016-11-09 16:52:11 -0800180 .map(entry -> new NextHop(entry.getKey(), entry.getValue()))
Jonathan Hartfd176612016-04-11 10:42:10 -0700181 .collect(Collectors.toSet());
182 }
183
184 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700185 public void update(Collection<Route> routes) {
186 synchronized (this) {
187 routes.forEach(route -> {
Jonathan Hartfd176612016-04-11 10:42:10 -0700188 log.debug("Received update {}", route);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700189 routeStore.updateRoute(route);
190 resolve(route);
191 });
192 }
193 }
194
195 @Override
196 public void withdraw(Collection<Route> routes) {
197 synchronized (this) {
Jonathan Hartfd176612016-04-11 10:42:10 -0700198 routes.forEach(route -> {
199 log.debug("Received withdraw {}", routes);
200 routeStore.removeRoute(route);
201 });
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700202 }
203 }
204
205 private void resolve(Route route) {
206 // Monitor the IP address for updates of the MAC address
207 hostService.startMonitoringIp(route.nextHop());
208
Charles Chan8fe9f4c2016-10-24 16:46:25 -0700209 NextHopData nextHopData = routeStore.getNextHop(route.nextHop());
210 if (nextHopData == null) {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700211 Set<Host> hosts = hostService.getHostsByIp(route.nextHop());
212 Optional<Host> host = hosts.stream().findFirst();
213 if (host.isPresent()) {
Charles Chan8fe9f4c2016-10-24 16:46:25 -0700214 nextHopData = NextHopData.fromHost(host.get());
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700215 }
216 }
217
Charles Chan8fe9f4c2016-10-24 16:46:25 -0700218 if (nextHopData != null) {
219 routeStore.updateNextHop(route.nextHop(), nextHopData);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700220 }
221 }
222
223 private void hostUpdated(Host host) {
224 synchronized (this) {
225 for (IpAddress ip : host.ipAddresses()) {
Charles Chan8fe9f4c2016-10-24 16:46:25 -0700226 routeStore.updateNextHop(ip, NextHopData.fromHost(host));
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700227 }
228 }
229 }
230
231 private void hostRemoved(Host host) {
232 synchronized (this) {
233 for (IpAddress ip : host.ipAddresses()) {
Charles Chan8fe9f4c2016-10-24 16:46:25 -0700234 routeStore.removeNextHop(ip, NextHopData.fromHost(host));
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700235 }
236 }
237 }
238
239 /**
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700240 * Creates a new listener queue.
241 *
242 * @param listener route listener
243 * @return listener queue
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700244 */
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700245 ListenerQueue createListenerQueue(RouteListener listener) {
246 return new DefaultListenerQueue(listener);
247 }
248
249 /**
250 * Default route listener queue.
251 */
252 private class DefaultListenerQueue implements ListenerQueue {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700253
254 private final ExecutorService executorService;
255 private final BlockingQueue<RouteEvent> queue;
256 private final RouteListener listener;
257
258 /**
259 * Creates a new listener queue.
260 *
261 * @param listener route listener to queue updates for
262 */
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700263 public DefaultListenerQueue(RouteListener listener) {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700264 this.listener = listener;
265 queue = new LinkedBlockingQueue<>();
266 executorService = newSingleThreadExecutor(threadFactory);
267 }
268
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700269 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700270 public void post(RouteEvent event) {
271 queue.add(event);
272 }
273
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700274 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700275 public void start() {
276 executorService.execute(this::poll);
277 }
278
Jonathan Hart6c2e7962016-04-11 13:54:09 -0700279 @Override
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700280 public void stop() {
281 executorService.shutdown();
282 }
283
284 private void poll() {
Jonathan Hartf79ab482016-08-19 14:20:50 -0700285 while (true) {
286 try {
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700287 listener.event(queue.take());
Jonathan Hartf79ab482016-08-19 14:20:50 -0700288 } catch (InterruptedException e) {
289 log.info("Route listener event thread shutting down: {}", e.getMessage());
290 break;
291 } catch (Exception e) {
292 log.warn("Exception during route event handler", e);
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700293 }
Jonathan Hartbfc5c482016-04-05 18:57:00 -0700294 }
295 }
296
297 }
298
299 /**
300 * Delegate to receive events from the route store.
301 */
302 private class InternalRouteStoreDelegate implements RouteStoreDelegate {
303 @Override
304 public void notify(RouteEvent event) {
305 post(event);
306 }
307 }
308
309 /**
310 * Internal listener for host events.
311 */
312 private class InternalHostListener implements HostListener {
313 @Override
314 public void event(HostEvent event) {
315 switch (event.type()) {
316 case HOST_ADDED:
317 case HOST_UPDATED:
318 hostUpdated(event.subject());
319 break;
320 case HOST_REMOVED:
321 hostRemoved(event.subject());
322 break;
323 case HOST_MOVED:
324 break;
325 default:
326 break;
327 }
328 }
329 }
330
331}