blob: 59df2b403e8831a21714b0530e098b790284bc7b [file] [log] [blame]
Kalhee Kimba366062017-11-07 16:32:09 +00001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
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.routing.fpm;
18
Andrea Campanella4310f6e2018-03-27 16:35:39 -070019import com.google.common.collect.ImmutableMap;
Charles Chan035ed1f2018-01-30 16:00:32 -080020import com.google.common.collect.Lists;
Kalhee Kimba366062017-11-07 16:32:09 +000021import org.jboss.netty.bootstrap.ServerBootstrap;
22import org.jboss.netty.channel.Channel;
23import org.jboss.netty.channel.ChannelException;
24import org.jboss.netty.channel.ChannelFactory;
25import org.jboss.netty.channel.ChannelPipeline;
26import org.jboss.netty.channel.ChannelPipelineFactory;
27import org.jboss.netty.channel.Channels;
28import org.jboss.netty.channel.group.ChannelGroup;
29import org.jboss.netty.channel.group.DefaultChannelGroup;
30import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
31import org.jboss.netty.handler.timeout.IdleStateHandler;
32import org.jboss.netty.util.HashedWheelTimer;
Kalhee Kimba366062017-11-07 16:32:09 +000033import org.onlab.packet.Ip4Address;
34import org.onlab.packet.Ip6Address;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070035import org.onlab.packet.IpAddress;
Kalhee Kimba366062017-11-07 16:32:09 +000036import org.onlab.packet.IpPrefix;
Kalhee Kimba366062017-11-07 16:32:09 +000037import org.onlab.util.KryoNamespace;
38import org.onlab.util.Tools;
39import org.onosproject.cfg.ComponentConfigService;
Charles Chan035ed1f2018-01-30 16:00:32 -080040import org.onosproject.cluster.ClusterEvent;
41import org.onosproject.cluster.ClusterEventListener;
Kalhee Kimba366062017-11-07 16:32:09 +000042import org.onosproject.cluster.ClusterService;
43import org.onosproject.cluster.NodeId;
Kalhee Kimba366062017-11-07 16:32:09 +000044import org.onosproject.core.ApplicationId;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070045import org.onosproject.core.CoreService;
46import org.onosproject.net.host.InterfaceIpAddress;
47import org.onosproject.net.intf.Interface;
48import org.onosproject.net.intf.InterfaceService;
Kalhee Kimba366062017-11-07 16:32:09 +000049import org.onosproject.routeservice.Route;
50import org.onosproject.routeservice.RouteAdminService;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070051import org.onosproject.routing.fpm.api.FpmPrefixStore;
52import org.onosproject.routing.fpm.api.FpmPrefixStoreEvent;
53import org.onosproject.routing.fpm.api.FpmRecord;
Kalhee Kimba366062017-11-07 16:32:09 +000054import org.onosproject.routing.fpm.protocol.FpmHeader;
55import org.onosproject.routing.fpm.protocol.Netlink;
56import org.onosproject.routing.fpm.protocol.NetlinkMessageType;
57import org.onosproject.routing.fpm.protocol.RouteAttribute;
58import org.onosproject.routing.fpm.protocol.RouteAttributeDst;
59import org.onosproject.routing.fpm.protocol.RouteAttributeGateway;
60import org.onosproject.routing.fpm.protocol.RtNetlink;
61import org.onosproject.routing.fpm.protocol.RtProtocol;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070062import org.onosproject.store.StoreDelegate;
Kalhee Kimba366062017-11-07 16:32:09 +000063import org.onosproject.store.serializers.KryoNamespaces;
Charles Chan035ed1f2018-01-30 16:00:32 -080064import org.onosproject.store.service.AsyncDistributedLock;
Kalhee Kimba366062017-11-07 16:32:09 +000065import org.onosproject.store.service.ConsistentMap;
66import org.onosproject.store.service.Serializer;
67import org.onosproject.store.service.StorageService;
Kalhee Kimba366062017-11-07 16:32:09 +000068import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070069import org.osgi.service.component.annotations.Activate;
70import org.osgi.service.component.annotations.Component;
71import org.osgi.service.component.annotations.Deactivate;
72import org.osgi.service.component.annotations.Modified;
73import org.osgi.service.component.annotations.Reference;
74import org.osgi.service.component.annotations.ReferenceCardinality;
75import org.osgi.service.component.annotations.ReferencePolicy;
Kalhee Kimba366062017-11-07 16:32:09 +000076import org.slf4j.Logger;
77import org.slf4j.LoggerFactory;
78
79import java.net.InetSocketAddress;
Charles Chan035ed1f2018-01-30 16:00:32 -080080import java.time.Duration;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070081import java.util.ArrayList;
82import java.util.Arrays;
Kalhee Kimba366062017-11-07 16:32:09 +000083import java.util.Collection;
84import java.util.Collections;
85import java.util.Dictionary;
86import java.util.HashSet;
87import java.util.LinkedList;
Kalhee Kimba366062017-11-07 16:32:09 +000088import java.util.List;
89import java.util.Map;
90import java.util.Set;
91import java.util.concurrent.ConcurrentHashMap;
Jordan Haltermanaa2faca2018-08-13 02:41:50 -070092import java.util.concurrent.ExecutorService;
93import java.util.concurrent.Executors;
Kalhee Kimba366062017-11-07 16:32:09 +000094import java.util.stream.Collectors;
95
96import static java.util.concurrent.Executors.newCachedThreadPool;
97import static org.onlab.util.Tools.groupedThreads;
Ray Milkey8e406512018-10-24 15:56:50 -070098import static org.onosproject.routing.fpm.OsgiPropertyConstants.CLEAR_ROUTES;
99import static org.onosproject.routing.fpm.OsgiPropertyConstants.CLEAR_ROUTES_DEFAULT;
100import static org.onosproject.routing.fpm.OsgiPropertyConstants.PD_PUSH_ENABLED;
101import static org.onosproject.routing.fpm.OsgiPropertyConstants.PD_PUSH_ENABLED_DEFAULT;
102import static org.onosproject.routing.fpm.OsgiPropertyConstants.PD_PUSH_NEXT_HOP_IPV4;
103import static org.onosproject.routing.fpm.OsgiPropertyConstants.PD_PUSH_NEXT_HOP_IPV4_DEFAULT;
104import static org.onosproject.routing.fpm.OsgiPropertyConstants.PD_PUSH_NEXT_HOP_IPV6;
105import static org.onosproject.routing.fpm.OsgiPropertyConstants.PD_PUSH_NEXT_HOP_IPV6_DEFAULT;
Kalhee Kimba366062017-11-07 16:32:09 +0000106
107/**
108 * Forwarding Plane Manager (FPM) route source.
109 */
Ray Milkey8e406512018-10-24 15:56:50 -0700110@Component(
111 immediate = true,
112 service = FpmInfoService.class,
113 property = {
114 CLEAR_ROUTES + ":Boolean=" + CLEAR_ROUTES_DEFAULT,
115 PD_PUSH_ENABLED + ":Boolean=" + PD_PUSH_ENABLED_DEFAULT,
116 PD_PUSH_NEXT_HOP_IPV4 + "=" + PD_PUSH_NEXT_HOP_IPV4_DEFAULT,
117 PD_PUSH_NEXT_HOP_IPV6 + "=" + PD_PUSH_NEXT_HOP_IPV6_DEFAULT,
118 }
119)
Kalhee Kimba366062017-11-07 16:32:09 +0000120public class FpmManager implements FpmInfoService {
121 private final Logger log = LoggerFactory.getLogger(getClass());
122
123 private static final int FPM_PORT = 2620;
124 private static final String APP_NAME = "org.onosproject.fpm";
125 private static final int IDLE_TIMEOUT_SECS = 5;
Charles Chan035ed1f2018-01-30 16:00:32 -0800126 private static final String LOCK_NAME = "fpm-manager-lock";
Kalhee Kimba366062017-11-07 16:32:09 +0000127
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700128 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimba366062017-11-07 16:32:09 +0000129 protected CoreService coreService;
130
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimba366062017-11-07 16:32:09 +0000132 protected ComponentConfigService componentConfigService;
133
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimba366062017-11-07 16:32:09 +0000135 protected RouteAdminService routeService;
136
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimba366062017-11-07 16:32:09 +0000138 protected ClusterService clusterService;
139
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimba366062017-11-07 16:32:09 +0000141 protected StorageService storageService;
142
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimba366062017-11-07 16:32:09 +0000144 protected InterfaceService interfaceService;
145
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700146 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
Kalhee Kimba366062017-11-07 16:32:09 +0000147 bind = "bindRipStore",
148 unbind = "unbindRipStore",
149 policy = ReferencePolicy.DYNAMIC,
150 target = "(fpm_type=RIP)")
151 protected volatile FpmPrefixStore ripStore;
152
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700153 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
Kalhee Kimba366062017-11-07 16:32:09 +0000154 bind = "bindDhcpStore",
155 unbind = "unbindDhcpStore",
156 policy = ReferencePolicy.DYNAMIC,
157 target = "(fpm_type=DHCP)")
158 protected volatile FpmPrefixStore dhcpStore;
159
160 private final StoreDelegate<FpmPrefixStoreEvent> fpmPrefixStoreDelegate
161 = new FpmPrefixStoreDelegate();
162
163 private ApplicationId appId;
164 private ServerBootstrap serverBootstrap;
165 private Channel serverChannel;
166 private ChannelGroup allChannels = new DefaultChannelGroup();
Charles Chan035ed1f2018-01-30 16:00:32 -0800167 private final InternalClusterListener clusterListener = new InternalClusterListener();
168 private AsyncDistributedLock asyncLock;
Kalhee Kimba366062017-11-07 16:32:09 +0000169
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700170 private ExecutorService clusterEventExecutor;
171
Kalhee Kimba366062017-11-07 16:32:09 +0000172 private ConsistentMap<FpmPeer, Set<FpmConnectionInfo>> peers;
173
174 private Map<FpmPeer, Map<IpPrefix, Route>> fpmRoutes = new ConcurrentHashMap<>();
175
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700176 //Local cache for peers to be used in case of cluster partition.
177 private Map<FpmPeer, Set<FpmConnectionInfo>> localPeers = new ConcurrentHashMap<>();
178
Ray Milkey8e406512018-10-24 15:56:50 -0700179 /** Whether to clear routes when the FPM connection goes down. */
180 private boolean clearRoutes = CLEAR_ROUTES_DEFAULT;
Kalhee Kimba366062017-11-07 16:32:09 +0000181
Ray Milkey8e406512018-10-24 15:56:50 -0700182 /** Whether to push prefixes to Quagga over fpm connection. */
183 private boolean pdPushEnabled = PD_PUSH_ENABLED_DEFAULT;
Kalhee Kimba366062017-11-07 16:32:09 +0000184
Ray Milkey8e406512018-10-24 15:56:50 -0700185 /** IPv4 next-hop address for PD Pushing. */
shalde064280feec2018-06-15 19:01:29 -0400186 private List<Ip4Address> pdPushNextHopIPv4 = null;
Kalhee Kimba366062017-11-07 16:32:09 +0000187
Ray Milkey8e406512018-10-24 15:56:50 -0700188 /** IPv6 next-hop address for PD Pushing. */
shalde064280feec2018-06-15 19:01:29 -0400189 private List<Ip6Address> pdPushNextHopIPv6 = null;
Kalhee Kimba366062017-11-07 16:32:09 +0000190
191 protected void bindRipStore(FpmPrefixStore store) {
192 if ((ripStore == null) && (store != null)) {
193 ripStore = store;
194 ripStore.setDelegate(fpmPrefixStoreDelegate);
195 for (Channel ch : allChannels) {
196 processRipStaticRoutes(ch);
197 }
198 }
199 }
200
201 protected void unbindRipStore(FpmPrefixStore store) {
202 if (ripStore == store) {
203 ripStore.unsetDelegate(fpmPrefixStoreDelegate);
204 ripStore = null;
205 }
206 }
207
208 protected void bindDhcpStore(FpmPrefixStore store) {
209 if ((dhcpStore == null) && (store != null)) {
210 dhcpStore = store;
211 dhcpStore.setDelegate(fpmPrefixStoreDelegate);
212 for (Channel ch : allChannels) {
213 processDhcpStaticRoutes(ch);
214 }
215 }
216 }
217
218 protected void unbindDhcpStore(FpmPrefixStore store) {
219 if (dhcpStore == store) {
220 dhcpStore.unsetDelegate(fpmPrefixStoreDelegate);
221 dhcpStore = null;
222 }
223 }
224
225 @Activate
226 protected void activate(ComponentContext context) {
227 componentConfigService.preSetProperty(
228 "org.onosproject.incubator.store.routing.impl.RouteStoreImpl",
229 "distributed", "true");
230
231 componentConfigService.registerProperties(getClass());
232
233 KryoNamespace serializer = KryoNamespace.newBuilder()
234 .register(KryoNamespaces.API)
235 .register(FpmPeer.class)
236 .register(FpmConnectionInfo.class)
237 .build();
238 peers = storageService.<FpmPeer, Set<FpmConnectionInfo>>consistentMapBuilder()
239 .withName("fpm-connections")
240 .withSerializer(Serializer.using(serializer))
241 .build();
242
243 modified(context);
244 startServer();
245
246 appId = coreService.registerApplication(APP_NAME, peers::destroy);
247
Charles Chan035ed1f2018-01-30 16:00:32 -0800248 asyncLock = storageService.lockBuilder().withName(LOCK_NAME).build();
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700249
250 clusterEventExecutor = Executors.newSingleThreadExecutor(groupedThreads("fpm-event-main", "%d", log));
Saurav Dase7f51012018-02-09 17:26:45 -0800251 clusterService.addListener(clusterListener);
Charles Chan035ed1f2018-01-30 16:00:32 -0800252
Kalhee Kimba366062017-11-07 16:32:09 +0000253 log.info("Started");
254 }
255
256 @Deactivate
257 protected void deactivate() {
258 componentConfigService.preSetProperty(
259 "org.onosproject.incubator.store.routing.impl.RouteStoreImpl",
260 "distributed", "false");
261
262 stopServer();
263 fpmRoutes.clear();
264 componentConfigService.unregisterProperties(getClass(), false);
Charles Chan035ed1f2018-01-30 16:00:32 -0800265
266 clusterService.removeListener(clusterListener);
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700267 clusterEventExecutor.shutdown();
Charles Chan035ed1f2018-01-30 16:00:32 -0800268 asyncLock.unlock();
269
Kalhee Kimba366062017-11-07 16:32:09 +0000270 log.info("Stopped");
271 }
272
273 @Modified
274 protected void modified(ComponentContext context) {
shalde064280feec2018-06-15 19:01:29 -0400275 Ip4Address rurIPv4Address;
276 Ip6Address rurIPv6Address;
Kalhee Kimba366062017-11-07 16:32:09 +0000277 Dictionary<?, ?> properties = context.getProperties();
278 if (properties == null) {
279 return;
280 }
Ray Milkey8e406512018-10-24 15:56:50 -0700281 String strClearRoutes = Tools.get(properties, CLEAR_ROUTES);
Kalhee Kimba366062017-11-07 16:32:09 +0000282 if (strClearRoutes != null) {
283 clearRoutes = Boolean.parseBoolean(strClearRoutes);
284 log.info("clearRoutes is {}", clearRoutes);
285 }
286
Ray Milkey8e406512018-10-24 15:56:50 -0700287 String strPdPushEnabled = Tools.get(properties, PD_PUSH_ENABLED);
Kalhee Kimba366062017-11-07 16:32:09 +0000288 if (strPdPushEnabled != null) {
289 boolean oldValue = pdPushEnabled;
290 pdPushEnabled = Boolean.parseBoolean(strPdPushEnabled);
291 if (pdPushEnabled) {
292
shalde064280feec2018-06-15 19:01:29 -0400293 pdPushNextHopIPv4 = new ArrayList<Ip4Address>();
294 pdPushNextHopIPv6 = new ArrayList<Ip6Address>();
Kalhee Kimba366062017-11-07 16:32:09 +0000295
Ray Milkey8e406512018-10-24 15:56:50 -0700296 String strPdPushNextHopIPv4 = Tools.get(properties, PD_PUSH_NEXT_HOP_IPV4);
Kalhee Kimba366062017-11-07 16:32:09 +0000297 if (strPdPushNextHopIPv4 != null) {
shalde064280feec2018-06-15 19:01:29 -0400298 List<String> strPdPushNextHopIPv4List = Arrays.asList(strPdPushNextHopIPv4.split(","));
299 for (String nextHop : strPdPushNextHopIPv4List) {
Mayank Tiwari2d3a3082018-11-23 16:18:50 -0500300 log.trace("IPv4 next hop added is:" + nextHop);
shalde064280feec2018-06-15 19:01:29 -0400301 pdPushNextHopIPv4.add(Ip4Address.valueOf(nextHop));
302 }
Kalhee Kimba366062017-11-07 16:32:09 +0000303 }
Ray Milkey8e406512018-10-24 15:56:50 -0700304 String strPdPushNextHopIPv6 = Tools.get(properties, PD_PUSH_NEXT_HOP_IPV6);
Kalhee Kimba366062017-11-07 16:32:09 +0000305 if (strPdPushNextHopIPv6 != null) {
shalde064280feec2018-06-15 19:01:29 -0400306 List<String> strPdPushNextHopIPv6List = Arrays.asList(strPdPushNextHopIPv6.split(","));
307 for (String nextHop : strPdPushNextHopIPv6List) {
Mayank Tiwari2d3a3082018-11-23 16:18:50 -0500308 log.trace("IPv6 next hop added is:" + nextHop);
shalde064280feec2018-06-15 19:01:29 -0400309 pdPushNextHopIPv6.add(Ip6Address.valueOf(nextHop));
310 }
Kalhee Kimba366062017-11-07 16:32:09 +0000311 }
312
Ray Milkey032b9642018-06-21 08:28:12 -0700313 if (pdPushNextHopIPv4.size() == 0) {
shalde064280feec2018-06-15 19:01:29 -0400314 rurIPv4Address = interfaceService.getInterfaces()
Kalhee Kimba366062017-11-07 16:32:09 +0000315 .stream()
316 .filter(iface -> iface.name().contains("RUR"))
317 .map(Interface::ipAddressesList)
318 .flatMap(Collection::stream)
319 .map(InterfaceIpAddress::ipAddress)
320 .filter(IpAddress::isIp4)
321 .map(IpAddress::getIp4Address)
322 .findFirst()
323 .orElse(null);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400324 log.debug("RUR IPv4 address extracted from netcfg is: {}", rurIPv4Address);
shalde064280feec2018-06-15 19:01:29 -0400325 if (rurIPv4Address != null) {
326 pdPushNextHopIPv4.add(rurIPv4Address);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400327 } else {
328 log.debug("Unable to extract RUR IPv4 address from netcfg");
shalde064280feec2018-06-15 19:01:29 -0400329 }
330
Kalhee Kimba366062017-11-07 16:32:09 +0000331 }
332
Mayank Tiwaric679a022018-06-23 11:19:08 -0400333 if (pdPushNextHopIPv6 == null || pdPushNextHopIPv6.size() == 0) {
shalde064280feec2018-06-15 19:01:29 -0400334 rurIPv6Address = interfaceService.getInterfaces()
Kalhee Kimba366062017-11-07 16:32:09 +0000335 .stream()
336 .filter(iface -> iface.name().contains("RUR"))
337 .map(Interface::ipAddressesList)
338 .flatMap(Collection::stream)
339 .map(InterfaceIpAddress::ipAddress)
340 .filter(IpAddress::isIp6)
341 .map(IpAddress::getIp6Address)
342 .findFirst()
343 .orElse(null);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400344 log.debug("RUR IPv6 address extracted from netcfg is: {}", rurIPv6Address);
shalde064280feec2018-06-15 19:01:29 -0400345 if (rurIPv6Address != null) {
346 pdPushNextHopIPv6.add(rurIPv6Address);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400347 } else {
348 log.debug("Unable to extract RUR IPv6 address from netcfg");
shalde064280feec2018-06-15 19:01:29 -0400349 }
Kalhee Kimba366062017-11-07 16:32:09 +0000350 }
351
352 log.info("PD pushing is enabled.");
Ray Milkey032b9642018-06-21 08:28:12 -0700353 if (pdPushNextHopIPv4.size() != 0) {
shalde064280feec2018-06-15 19:01:29 -0400354 log.info("ipv4 next-hop {} with {} items", pdPushNextHopIPv4.toString(), pdPushNextHopIPv4.size());
Kalhee Kimba366062017-11-07 16:32:09 +0000355 } else {
356 log.info("ipv4 next-hop is null");
357 }
Ray Milkey032b9642018-06-21 08:28:12 -0700358 if (pdPushNextHopIPv6.size() != 0) {
shalde064280feec2018-06-15 19:01:29 -0400359 log.info("ipv6 next-hop={} with {} items", pdPushNextHopIPv6.toString(), pdPushNextHopIPv6.size());
Kalhee Kimba366062017-11-07 16:32:09 +0000360 } else {
361 log.info("ipv6 next-hop is null");
362 }
shalde064280feec2018-06-15 19:01:29 -0400363 processStaticRoutes();
Kalhee Kimba366062017-11-07 16:32:09 +0000364 } else {
365 log.info("PD pushing is disabled.");
366 }
367 }
368 }
369
370 private void startServer() {
371 HashedWheelTimer timer = new HashedWheelTimer(
372 groupedThreads("onos/fpm", "fpm-timer-%d", log));
373
374 ChannelFactory channelFactory = new NioServerSocketChannelFactory(
375 newCachedThreadPool(groupedThreads("onos/fpm", "sm-boss-%d", log)),
376 newCachedThreadPool(groupedThreads("onos/fpm", "sm-worker-%d", log)));
377 ChannelPipelineFactory pipelineFactory = () -> {
378 // Allocate a new session per connection
379 IdleStateHandler idleHandler =
380 new IdleStateHandler(timer, IDLE_TIMEOUT_SECS, 0, 0);
381 FpmSessionHandler fpmSessionHandler =
382 new FpmSessionHandler(this, new InternalFpmListener());
383 FpmFrameDecoder fpmFrameDecoder = new FpmFrameDecoder();
384
385 // Setup the processing pipeline
386 ChannelPipeline pipeline = Channels.pipeline();
387 pipeline.addLast("FpmFrameDecoder", fpmFrameDecoder);
388 pipeline.addLast("idle", idleHandler);
389 pipeline.addLast("FpmSession", fpmSessionHandler);
390 return pipeline;
391 };
392
393 InetSocketAddress listenAddress = new InetSocketAddress(FPM_PORT);
394
395 serverBootstrap = new ServerBootstrap(channelFactory);
396 serverBootstrap.setOption("child.reuseAddr", true);
397 serverBootstrap.setOption("child.keepAlive", true);
398 serverBootstrap.setOption("child.tcpNoDelay", true);
399 serverBootstrap.setPipelineFactory(pipelineFactory);
400 try {
401 serverChannel = serverBootstrap.bind(listenAddress);
402 allChannels.add(serverChannel);
403 } catch (ChannelException e) {
404 log.debug("Exception binding to FPM port {}: ",
405 listenAddress.getPort(), e);
406 stopServer();
407 }
408 }
409
410 private void stopServer() {
411 allChannels.close().awaitUninterruptibly();
412 allChannels.clear();
413 if (serverBootstrap != null) {
414 serverBootstrap.releaseExternalResources();
415 }
416
417 if (clearRoutes) {
418 peers.keySet().forEach(this::clearRoutes);
419 }
420 }
421
Kalhee Kim40beb722018-01-16 20:32:04 +0000422 private boolean routeInDhcpStore(IpPrefix prefix) {
423
424 if (dhcpStore != null) {
425 Collection<FpmRecord> dhcpRecords = dhcpStore.getFpmRecords();
426 return dhcpRecords.stream().anyMatch(record -> record.ipPrefix().equals(prefix));
427 }
428 return false;
429 }
430
431 private boolean routeInRipStore(IpPrefix prefix) {
432
433 if (ripStore != null) {
434 Collection<FpmRecord> ripRecords = ripStore.getFpmRecords();
435 return ripRecords.stream().anyMatch(record -> record.ipPrefix().equals(prefix));
436 }
437 return false;
438 }
439
Kalhee Kimba366062017-11-07 16:32:09 +0000440 private void fpmMessage(FpmPeer peer, FpmHeader fpmMessage) {
441 if (fpmMessage.type() == FpmHeader.FPM_TYPE_KEEPALIVE) {
442 return;
443 }
444
445 Netlink netlink = fpmMessage.netlink();
446 RtNetlink rtNetlink = netlink.rtNetlink();
447
448 if (log.isTraceEnabled()) {
449 log.trace("Received FPM message: {}", fpmMessage);
450 }
451
452 if (!(rtNetlink.protocol() == RtProtocol.ZEBRA ||
453 rtNetlink.protocol() == RtProtocol.UNSPEC)) {
454 log.trace("Ignoring non-zebra route");
455 return;
456 }
457
458 IpAddress dstAddress = null;
459 IpAddress gateway = null;
460
461 for (RouteAttribute attribute : rtNetlink.attributes()) {
462 if (attribute.type() == RouteAttribute.RTA_DST) {
463 RouteAttributeDst raDst = (RouteAttributeDst) attribute;
464 dstAddress = raDst.dstAddress();
465 } else if (attribute.type() == RouteAttribute.RTA_GATEWAY) {
466 RouteAttributeGateway raGateway = (RouteAttributeGateway) attribute;
467 gateway = raGateway.gateway();
468 }
469 }
470
471 if (dstAddress == null) {
472 log.error("Dst address missing!");
473 return;
474 }
475
476 IpPrefix prefix = IpPrefix.valueOf(dstAddress, rtNetlink.dstLength());
477
Kalhee Kim40beb722018-01-16 20:32:04 +0000478 // Ignore routes that we sent.
Charles Chaneb42a732018-06-25 13:01:35 -0700479 if (gateway != null && (
480 (prefix.isIp4() && pdPushNextHopIPv4 != null &&
481 pdPushNextHopIPv4.contains(gateway.getIp4Address())) ||
482 (prefix.isIp6() && pdPushNextHopIPv6 != null &&
483 pdPushNextHopIPv6.contains(gateway.getIp6Address())))) {
Kalhee Kim40beb722018-01-16 20:32:04 +0000484 if (routeInDhcpStore(prefix) || routeInRipStore(prefix)) {
485 return;
486 }
487 }
488
Kalhee Kimba366062017-11-07 16:32:09 +0000489 List<Route> updates = new LinkedList<>();
490 List<Route> withdraws = new LinkedList<>();
491
492 Route route;
493 switch (netlink.type()) {
494 case RTM_NEWROUTE:
495 if (gateway == null) {
496 // We ignore interface routes with no gateway for now.
497 return;
498 }
499 route = new Route(Route.Source.FPM, prefix, gateway, clusterService.getLocalNode().id());
500
501
502 Route oldRoute = fpmRoutes.get(peer).put(prefix, route);
503
504 if (oldRoute != null) {
505 log.trace("Swapping {} with {}", oldRoute, route);
506 withdraws.add(oldRoute);
507 }
508 updates.add(route);
509 break;
510 case RTM_DELROUTE:
511 Route existing = fpmRoutes.get(peer).remove(prefix);
512 if (existing == null) {
513 log.warn("Got delete for non-existent prefix");
514 return;
515 }
516
517 route = new Route(Route.Source.FPM, prefix, existing.nextHop(), clusterService.getLocalNode().id());
518
519 withdraws.add(route);
520 break;
521 case RTM_GETROUTE:
522 default:
523 break;
524 }
525
Charles Chan035ed1f2018-01-30 16:00:32 -0800526 updateRouteStore(updates, withdraws);
527 }
528
529 private synchronized void updateRouteStore(Collection<Route> routesToAdd, Collection<Route> routesToRemove) {
530 routeService.withdraw(routesToRemove);
531 routeService.update(routesToAdd);
Kalhee Kimba366062017-11-07 16:32:09 +0000532 }
533
534 private void clearRoutes(FpmPeer peer) {
535 log.info("Clearing all routes for peer {}", peer);
536 Map<IpPrefix, Route> routes = fpmRoutes.remove(peer);
537 if (routes != null) {
Charles Chan035ed1f2018-01-30 16:00:32 -0800538 updateRouteStore(Lists.newArrayList(), routes.values());
Kalhee Kimba366062017-11-07 16:32:09 +0000539 }
540 }
541
542 public void processStaticRoutes() {
shalde064280feec2018-06-15 19:01:29 -0400543 log.debug("processStaticRoutes function is called");
Kalhee Kimba366062017-11-07 16:32:09 +0000544 for (Channel ch : allChannels) {
545 processStaticRoutes(ch);
546 }
547 }
548
549 public void processStaticRoutes(Channel ch) {
550 processRipStaticRoutes(ch);
551 processDhcpStaticRoutes(ch);
552 }
553
554 private void processRipStaticRoutes(Channel ch) {
555
556 /* Get RIP static routes. */
557 if (ripStore != null) {
558 Collection<FpmRecord> ripRecords = ripStore.getFpmRecords();
559 log.info("RIP store size is {}", ripRecords.size());
560
561 ripRecords.forEach(record -> sendRouteUpdateToChannel(true,
562 record.ipPrefix(), ch));
563 }
564 }
565
566 private void processDhcpStaticRoutes(Channel ch) {
567
568 /* Get Dhcp static routes. */
569 if (dhcpStore != null) {
570 Collection<FpmRecord> dhcpRecords = dhcpStore.getFpmRecords();
571 log.info("Dhcp store size is {}", dhcpRecords.size());
572
573 dhcpRecords.forEach(record -> sendRouteUpdateToChannel(true,
574 record.ipPrefix(), ch));
575 }
576 }
577
shalde064280feec2018-06-15 19:01:29 -0400578 private void updateRoute(IpAddress pdPushNextHop, boolean isAdd, IpPrefix prefix,
579 Channel ch, int raLength, short addrFamily) {
Kalhee Kimba366062017-11-07 16:32:09 +0000580 try {
shalde064280feec2018-06-15 19:01:29 -0400581 RouteAttributeDst raDst = RouteAttributeDst.builder()
582 .length(raLength)
583 .type(RouteAttribute.RTA_DST)
584 .dstAddress(prefix.address())
585 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000586
Kalhee Kim715dd732018-01-23 14:39:56 +0000587 RouteAttributeGateway raGateway = RouteAttributeGateway.builder()
shalde064280feec2018-06-15 19:01:29 -0400588 .length(raLength)
589 .type(RouteAttribute.RTA_GATEWAY)
590 .gateway(pdPushNextHop)
591 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000592
Kalhee Kim715dd732018-01-23 14:39:56 +0000593 // Build RtNetlink.
594 RtNetlink rtNetlink = RtNetlink.builder()
shalde064280feec2018-06-15 19:01:29 -0400595 .addressFamily(addrFamily)
596 .dstLength(prefix.prefixLength())
597 .routeAttribute(raDst)
598 .routeAttribute(raGateway)
599 .build();
Kalhee Kim715dd732018-01-23 14:39:56 +0000600
601 // Build Netlink.
Kalhee Kimba366062017-11-07 16:32:09 +0000602 int messageLength = raDst.length() + raGateway.length() +
shalde064280feec2018-06-15 19:01:29 -0400603 RtNetlink.RT_NETLINK_LENGTH + Netlink.NETLINK_HEADER_LENGTH;
Kalhee Kim715dd732018-01-23 14:39:56 +0000604 Netlink netLink = Netlink.builder()
shalde064280feec2018-06-15 19:01:29 -0400605 .length(messageLength)
606 .type(isAdd ? NetlinkMessageType.RTM_NEWROUTE : NetlinkMessageType.RTM_DELROUTE)
607 .flags(Netlink.NETLINK_REQUEST | Netlink.NETLINK_CREATE)
608 .rtNetlink(rtNetlink)
609 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000610
Kalhee Kim715dd732018-01-23 14:39:56 +0000611 // Build FpmHeader.
Kalhee Kimba366062017-11-07 16:32:09 +0000612 messageLength += FpmHeader.FPM_HEADER_LENGTH;
Kalhee Kim715dd732018-01-23 14:39:56 +0000613 FpmHeader fpmMessage = FpmHeader.builder()
shalde064280feec2018-06-15 19:01:29 -0400614 .version(FpmHeader.FPM_VERSION_1)
615 .type(FpmHeader.FPM_TYPE_NETLINK)
616 .length(messageLength)
617 .netlink(netLink)
618 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000619
620 // Encode message in a channel buffer and transmit.
621 ch.write(fpmMessage.encode());
622
623 } catch (RuntimeException e) {
624 log.info("Route not sent over fpm connection.");
625 }
626 }
627
shalde064280feec2018-06-15 19:01:29 -0400628 private void sendRouteUpdateToChannel(boolean isAdd, IpPrefix prefix, Channel ch) {
629
630 if (!pdPushEnabled) {
631 return;
632 }
633 int raLength;
634 short addrFamily;
635
636 // Build route attributes.
637 if (prefix.isIp4()) {
638 List<Ip4Address> pdPushNextHopList;
639 if (pdPushNextHopIPv4 == null || pdPushNextHopIPv4.size() == 0) {
640 log.info("Prefix not pushed because ipv4 next-hop is null.");
641 return;
642 }
643 pdPushNextHopList = pdPushNextHopIPv4;
644 raLength = Ip4Address.BYTE_LENGTH + RouteAttribute.ROUTE_ATTRIBUTE_HEADER_LENGTH;
645 addrFamily = RtNetlink.RT_ADDRESS_FAMILY_INET;
646 for (Ip4Address pdPushNextHop: pdPushNextHopList) {
647 log.debug("IPv4 next hop is:" + pdPushNextHop);
648 updateRoute(pdPushNextHop, isAdd, prefix, ch, raLength, addrFamily);
649 }
650 } else {
651 List<Ip6Address> pdPushNextHopList;
652 if (pdPushNextHopIPv6 == null || pdPushNextHopIPv6.size() == 0) {
653 log.info("Prefix not pushed because ipv6 next-hop is null.");
654 return;
655 }
656 pdPushNextHopList = pdPushNextHopIPv6;
657 raLength = Ip6Address.BYTE_LENGTH + RouteAttribute.ROUTE_ATTRIBUTE_HEADER_LENGTH;
658 addrFamily = RtNetlink.RT_ADDRESS_FAMILY_INET6;
659 for (Ip6Address pdPushNextHop: pdPushNextHopList) {
660 log.debug("IPv6 next hop is:" + pdPushNextHop);
661 updateRoute(pdPushNextHop, isAdd, prefix, ch, raLength, addrFamily);
662 }
663 }
664 }
665
Kalhee Kimba366062017-11-07 16:32:09 +0000666 private void sendRouteUpdate(boolean isAdd, IpPrefix prefix) {
667
668 for (Channel ch : allChannels) {
669 sendRouteUpdateToChannel(isAdd, prefix, ch);
670 }
671 }
672
673 public boolean isPdPushEnabled() {
674 return pdPushEnabled;
675 }
676
677 private FpmPeerInfo toFpmInfo(FpmPeer peer, Collection<FpmConnectionInfo> connections) {
678 return new FpmPeerInfo(connections,
679 fpmRoutes.getOrDefault(peer, Collections.emptyMap()).size());
680 }
681
682 @Override
683 public Map<FpmPeer, FpmPeerInfo> peers() {
684 return peers.asJavaMap().entrySet().stream()
685 .collect(Collectors.toMap(
686 e -> e.getKey(),
687 e -> toFpmInfo(e.getKey(), e.getValue())));
688 }
689
690 private class InternalFpmListener implements FpmListener {
691 @Override
692 public void fpmMessage(FpmPeer peer, FpmHeader fpmMessage) {
693 FpmManager.this.fpmMessage(peer, fpmMessage);
694 }
695
696 @Override
697 public boolean peerConnected(FpmPeer peer) {
698 if (peers.keySet().contains(peer)) {
699 return false;
700 }
701
702 NodeId localNode = clusterService.getLocalNode().id();
703 peers.compute(peer, (p, infos) -> {
704 if (infos == null) {
705 infos = new HashSet<>();
706 }
707
708 infos.add(new FpmConnectionInfo(localNode, peer, System.currentTimeMillis()));
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700709 localPeers.put(peer, infos);
Kalhee Kimba366062017-11-07 16:32:09 +0000710 return infos;
711 });
712
713 fpmRoutes.computeIfAbsent(peer, p -> new ConcurrentHashMap<>());
714 return true;
715 }
716
717 @Override
718 public void peerDisconnected(FpmPeer peer) {
719 log.info("FPM connection to {} went down", peer);
720
721 if (clearRoutes) {
722 clearRoutes(peer);
723 }
724
725 peers.compute(peer, (p, infos) -> {
726 if (infos == null) {
727 return null;
728 }
729
730 infos.stream()
731 .filter(i -> i.connectedTo().equals(clusterService.getLocalNode().id()))
732 .findAny()
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700733 .ifPresent(i -> {
734 infos.remove(i);
735 localPeers.get(peer).remove(i);
736 });
Kalhee Kimba366062017-11-07 16:32:09 +0000737
738 if (infos.isEmpty()) {
739 return null;
740 }
741
742 return infos;
743 });
744 }
745 }
746
747 /**
748 * Adds a channel to the channel group.
749 *
750 * @param channel the channel to add
751 */
752 public void addSessionChannel(Channel channel) {
753 allChannels.add(channel);
754 }
755
756 /**
757 * Removes a channel from the channel group.
758 *
759 * @param channel the channel to remove
760 */
761 public void removeSessionChannel(Channel channel) {
762 allChannels.remove(channel);
763 }
764
765 /**
766 * Store delegate for Fpm Prefix store.
767 * Handles Fpm prefix store event.
768 */
769 class FpmPrefixStoreDelegate implements StoreDelegate<FpmPrefixStoreEvent> {
770
771 @Override
772 public void notify(FpmPrefixStoreEvent e) {
773
774 log.trace("FpmPrefixStoreEvent notify");
775
776 FpmRecord record = e.subject();
777 switch (e.type()) {
778 case ADD:
779 sendRouteUpdate(true, record.ipPrefix());
780 break;
781 case REMOVE:
782 sendRouteUpdate(false, record.ipPrefix());
783 break;
784 default:
785 log.warn("unsupported store event type", e.type());
786 return;
787 }
788 }
789 }
Charles Chan035ed1f2018-01-30 16:00:32 -0800790
791 private class InternalClusterListener implements ClusterEventListener {
792 @Override
793 public void event(ClusterEvent event) {
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700794 clusterEventExecutor.execute(() -> {
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700795 log.info("Receives ClusterEvent {} for {}", event.type(), event.subject().id());
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700796 switch (event.type()) {
797 case INSTANCE_READY:
798 // When current node is healing from a network partition,
799 // seeing INSTANCE_READY means current node has the ability to read from the cluster,
800 // but it is possible that current node still can't write to the cluster at this moment.
801 // The AsyncDistributedLock is introduced to ensure we attempt to push FPM routes
802 // after current node can write.
803 // Adding 15 seconds retry for the current node to be able to write.
804 asyncLock.tryLock(Duration.ofSeconds(15)).whenComplete((result, error) -> {
805 if (result != null && result.isPresent()) {
806 log.debug("Lock obtained. Push local FPM routes to route store");
807 // All FPM routes on current node will be pushed again even when current node is not
808 // the one that becomes READY. A better way is to do this only on the minority nodes.
809 pushFpmRoutes();
810 localPeers.forEach((key, value) -> peers.put(key, value));
811 asyncLock.unlock();
812 } else {
813 log.debug("Fail to obtain lock. Abort.");
814 }
815 });
816 break;
817 case INSTANCE_DEACTIVATED:
818 case INSTANCE_REMOVED:
819 ImmutableMap.copyOf(peers.asJavaMap()).forEach((key, value) -> {
820 if (value != null) {
821 value.stream()
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700822 .filter(i -> i.connectedTo().equals(event.subject().id()))
823 .findAny()
824 .ifPresent(value::remove);
825
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700826 if (value.isEmpty()) {
827 peers.remove(key);
828 }
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700829 }
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700830 });
831 break;
832 case INSTANCE_ADDED:
833 case INSTANCE_ACTIVATED:
834 default:
835 break;
836 }
837 });
Charles Chan035ed1f2018-01-30 16:00:32 -0800838 }
839 }
840
Saurav Dase7f51012018-02-09 17:26:45 -0800841 @Override
Charles Chan035ed1f2018-01-30 16:00:32 -0800842 public void pushFpmRoutes() {
843 Set<Route> routes = fpmRoutes.values().stream()
844 .map(Map::entrySet).flatMap(Set::stream).map(Map.Entry::getValue)
845 .collect(Collectors.toSet());
846 updateRouteStore(routes, Lists.newArrayList());
847 log.info("{} FPM routes have been updated to route store", routes.size());
848 }
Kalhee Kimba366062017-11-07 16:32:09 +0000849}