blob: 4deaebb3b40a62ff51fe1af3ee3c2e12b14139a3 [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.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Deactivate;
24import org.apache.felix.scr.annotations.Modified;
25import org.apache.felix.scr.annotations.Property;
26import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.ReferencePolicy;
29import org.apache.felix.scr.annotations.Service;
30import org.jboss.netty.bootstrap.ServerBootstrap;
31import org.jboss.netty.channel.Channel;
32import org.jboss.netty.channel.ChannelException;
33import org.jboss.netty.channel.ChannelFactory;
34import org.jboss.netty.channel.ChannelPipeline;
35import org.jboss.netty.channel.ChannelPipelineFactory;
36import org.jboss.netty.channel.Channels;
37import org.jboss.netty.channel.group.ChannelGroup;
38import org.jboss.netty.channel.group.DefaultChannelGroup;
39import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
40import org.jboss.netty.handler.timeout.IdleStateHandler;
41import org.jboss.netty.util.HashedWheelTimer;
Kalhee Kimba366062017-11-07 16:32:09 +000042import org.onlab.packet.Ip4Address;
43import org.onlab.packet.Ip6Address;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070044import org.onlab.packet.IpAddress;
Kalhee Kimba366062017-11-07 16:32:09 +000045import org.onlab.packet.IpPrefix;
Kalhee Kimba366062017-11-07 16:32:09 +000046import org.onlab.util.KryoNamespace;
47import org.onlab.util.Tools;
48import org.onosproject.cfg.ComponentConfigService;
Charles Chan035ed1f2018-01-30 16:00:32 -080049import org.onosproject.cluster.ClusterEvent;
50import org.onosproject.cluster.ClusterEventListener;
Kalhee Kimba366062017-11-07 16:32:09 +000051import org.onosproject.cluster.ClusterService;
52import org.onosproject.cluster.NodeId;
Kalhee Kimba366062017-11-07 16:32:09 +000053import org.onosproject.core.ApplicationId;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070054import org.onosproject.core.CoreService;
55import org.onosproject.net.host.InterfaceIpAddress;
56import org.onosproject.net.intf.Interface;
57import org.onosproject.net.intf.InterfaceService;
Kalhee Kimba366062017-11-07 16:32:09 +000058import org.onosproject.routeservice.Route;
59import org.onosproject.routeservice.RouteAdminService;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070060import org.onosproject.routing.fpm.api.FpmPrefixStore;
61import org.onosproject.routing.fpm.api.FpmPrefixStoreEvent;
62import org.onosproject.routing.fpm.api.FpmRecord;
Kalhee Kimba366062017-11-07 16:32:09 +000063import org.onosproject.routing.fpm.protocol.FpmHeader;
64import org.onosproject.routing.fpm.protocol.Netlink;
65import org.onosproject.routing.fpm.protocol.NetlinkMessageType;
66import org.onosproject.routing.fpm.protocol.RouteAttribute;
67import org.onosproject.routing.fpm.protocol.RouteAttributeDst;
68import org.onosproject.routing.fpm.protocol.RouteAttributeGateway;
69import org.onosproject.routing.fpm.protocol.RtNetlink;
70import org.onosproject.routing.fpm.protocol.RtProtocol;
Andrea Campanella4310f6e2018-03-27 16:35:39 -070071import org.onosproject.store.StoreDelegate;
Kalhee Kimba366062017-11-07 16:32:09 +000072import org.onosproject.store.serializers.KryoNamespaces;
Charles Chan035ed1f2018-01-30 16:00:32 -080073import org.onosproject.store.service.AsyncDistributedLock;
Kalhee Kimba366062017-11-07 16:32:09 +000074import org.onosproject.store.service.ConsistentMap;
75import org.onosproject.store.service.Serializer;
76import org.onosproject.store.service.StorageService;
Kalhee Kimba366062017-11-07 16:32:09 +000077import org.osgi.service.component.ComponentContext;
78import org.slf4j.Logger;
79import org.slf4j.LoggerFactory;
80
81import java.net.InetSocketAddress;
Charles Chan035ed1f2018-01-30 16:00:32 -080082import java.time.Duration;
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;
shalde064280feec2018-06-15 19:01:29 -040089import java.util.ArrayList;
90import java.util.Arrays;
Kalhee Kimba366062017-11-07 16:32:09 +000091import java.util.Map;
92import java.util.Set;
93import java.util.concurrent.ConcurrentHashMap;
Jordan Haltermanaa2faca2018-08-13 02:41:50 -070094import java.util.concurrent.ExecutorService;
95import java.util.concurrent.Executors;
Kalhee Kimba366062017-11-07 16:32:09 +000096import java.util.stream.Collectors;
97
98import static java.util.concurrent.Executors.newCachedThreadPool;
99import static org.onlab.util.Tools.groupedThreads;
Kalhee Kimba366062017-11-07 16:32:09 +0000100
101/**
102 * Forwarding Plane Manager (FPM) route source.
103 */
104@Service
105@Component(immediate = true)
106public class FpmManager implements FpmInfoService {
107 private final Logger log = LoggerFactory.getLogger(getClass());
108
109 private static final int FPM_PORT = 2620;
110 private static final String APP_NAME = "org.onosproject.fpm";
111 private static final int IDLE_TIMEOUT_SECS = 5;
Charles Chan035ed1f2018-01-30 16:00:32 -0800112 private static final String LOCK_NAME = "fpm-manager-lock";
Kalhee Kimba366062017-11-07 16:32:09 +0000113
114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
115 protected CoreService coreService;
116
117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
118 protected ComponentConfigService componentConfigService;
119
120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
121 protected RouteAdminService routeService;
122
123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
124 protected ClusterService clusterService;
125
126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
127 protected StorageService storageService;
128
129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
130 protected InterfaceService interfaceService;
131
132 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
133 bind = "bindRipStore",
134 unbind = "unbindRipStore",
135 policy = ReferencePolicy.DYNAMIC,
136 target = "(fpm_type=RIP)")
137 protected volatile FpmPrefixStore ripStore;
138
139 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
140 bind = "bindDhcpStore",
141 unbind = "unbindDhcpStore",
142 policy = ReferencePolicy.DYNAMIC,
143 target = "(fpm_type=DHCP)")
144 protected volatile FpmPrefixStore dhcpStore;
145
146 private final StoreDelegate<FpmPrefixStoreEvent> fpmPrefixStoreDelegate
147 = new FpmPrefixStoreDelegate();
148
149 private ApplicationId appId;
150 private ServerBootstrap serverBootstrap;
151 private Channel serverChannel;
152 private ChannelGroup allChannels = new DefaultChannelGroup();
Charles Chan035ed1f2018-01-30 16:00:32 -0800153 private final InternalClusterListener clusterListener = new InternalClusterListener();
154 private AsyncDistributedLock asyncLock;
Kalhee Kimba366062017-11-07 16:32:09 +0000155
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700156 private ExecutorService clusterEventExecutor;
157
Kalhee Kimba366062017-11-07 16:32:09 +0000158 private ConsistentMap<FpmPeer, Set<FpmConnectionInfo>> peers;
159
160 private Map<FpmPeer, Map<IpPrefix, Route>> fpmRoutes = new ConcurrentHashMap<>();
161
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700162 //Local cache for peers to be used in case of cluster partition.
163 private Map<FpmPeer, Set<FpmConnectionInfo>> localPeers = new ConcurrentHashMap<>();
164
Kalhee Kimba366062017-11-07 16:32:09 +0000165 @Property(name = "clearRoutes", boolValue = true,
166 label = "Whether to clear routes when the FPM connection goes down")
167 private boolean clearRoutes = true;
168
169 @Property(name = "pdPushEnabled", boolValue = false,
170 label = "Whether to push prefixes to Quagga over fpm connection")
171 private boolean pdPushEnabled = false;
172
173 @Property(name = "pdPushNextHopIPv4", value = "",
174 label = "IPv4 next-hop address for PD Pushing.")
shalde064280feec2018-06-15 19:01:29 -0400175 private List<Ip4Address> pdPushNextHopIPv4 = null;
Kalhee Kimba366062017-11-07 16:32:09 +0000176
177 @Property(name = "pdPushNextHopIPv6", value = "",
178 label = "IPv6 next-hop address for PD Pushing.")
shalde064280feec2018-06-15 19:01:29 -0400179 private List<Ip6Address> pdPushNextHopIPv6 = null;
Kalhee Kimba366062017-11-07 16:32:09 +0000180
181 protected void bindRipStore(FpmPrefixStore store) {
182 if ((ripStore == null) && (store != null)) {
183 ripStore = store;
184 ripStore.setDelegate(fpmPrefixStoreDelegate);
185 for (Channel ch : allChannels) {
186 processRipStaticRoutes(ch);
187 }
188 }
189 }
190
191 protected void unbindRipStore(FpmPrefixStore store) {
192 if (ripStore == store) {
193 ripStore.unsetDelegate(fpmPrefixStoreDelegate);
194 ripStore = null;
195 }
196 }
197
198 protected void bindDhcpStore(FpmPrefixStore store) {
199 if ((dhcpStore == null) && (store != null)) {
200 dhcpStore = store;
201 dhcpStore.setDelegate(fpmPrefixStoreDelegate);
202 for (Channel ch : allChannels) {
203 processDhcpStaticRoutes(ch);
204 }
205 }
206 }
207
208 protected void unbindDhcpStore(FpmPrefixStore store) {
209 if (dhcpStore == store) {
210 dhcpStore.unsetDelegate(fpmPrefixStoreDelegate);
211 dhcpStore = null;
212 }
213 }
214
215 @Activate
216 protected void activate(ComponentContext context) {
217 componentConfigService.preSetProperty(
218 "org.onosproject.incubator.store.routing.impl.RouteStoreImpl",
219 "distributed", "true");
220
221 componentConfigService.registerProperties(getClass());
222
223 KryoNamespace serializer = KryoNamespace.newBuilder()
224 .register(KryoNamespaces.API)
225 .register(FpmPeer.class)
226 .register(FpmConnectionInfo.class)
227 .build();
228 peers = storageService.<FpmPeer, Set<FpmConnectionInfo>>consistentMapBuilder()
229 .withName("fpm-connections")
230 .withSerializer(Serializer.using(serializer))
231 .build();
232
233 modified(context);
234 startServer();
235
236 appId = coreService.registerApplication(APP_NAME, peers::destroy);
237
Charles Chan035ed1f2018-01-30 16:00:32 -0800238 asyncLock = storageService.lockBuilder().withName(LOCK_NAME).build();
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700239
240 clusterEventExecutor = Executors.newSingleThreadExecutor(groupedThreads("fpm-event-main", "%d", log));
Saurav Dase7f51012018-02-09 17:26:45 -0800241 clusterService.addListener(clusterListener);
Charles Chan035ed1f2018-01-30 16:00:32 -0800242
Kalhee Kimba366062017-11-07 16:32:09 +0000243 log.info("Started");
244 }
245
246 @Deactivate
247 protected void deactivate() {
248 componentConfigService.preSetProperty(
249 "org.onosproject.incubator.store.routing.impl.RouteStoreImpl",
250 "distributed", "false");
251
252 stopServer();
253 fpmRoutes.clear();
254 componentConfigService.unregisterProperties(getClass(), false);
Charles Chan035ed1f2018-01-30 16:00:32 -0800255
256 clusterService.removeListener(clusterListener);
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700257 clusterEventExecutor.shutdown();
Charles Chan035ed1f2018-01-30 16:00:32 -0800258 asyncLock.unlock();
259
Kalhee Kimba366062017-11-07 16:32:09 +0000260 log.info("Stopped");
261 }
262
263 @Modified
264 protected void modified(ComponentContext context) {
shalde064280feec2018-06-15 19:01:29 -0400265 Ip4Address rurIPv4Address;
266 Ip6Address rurIPv6Address;
Kalhee Kimba366062017-11-07 16:32:09 +0000267 Dictionary<?, ?> properties = context.getProperties();
268 if (properties == null) {
269 return;
270 }
271 String strClearRoutes = Tools.get(properties, "clearRoutes");
272 if (strClearRoutes != null) {
273 clearRoutes = Boolean.parseBoolean(strClearRoutes);
274 log.info("clearRoutes is {}", clearRoutes);
275 }
276
277 String strPdPushEnabled = Tools.get(properties, "pdPushEnabled");
278 if (strPdPushEnabled != null) {
279 boolean oldValue = pdPushEnabled;
280 pdPushEnabled = Boolean.parseBoolean(strPdPushEnabled);
281 if (pdPushEnabled) {
282
shalde064280feec2018-06-15 19:01:29 -0400283 pdPushNextHopIPv4 = new ArrayList<Ip4Address>();
284 pdPushNextHopIPv6 = new ArrayList<Ip6Address>();
Kalhee Kimba366062017-11-07 16:32:09 +0000285
286 String strPdPushNextHopIPv4 = Tools.get(properties, "pdPushNextHopIPv4");
287 if (strPdPushNextHopIPv4 != null) {
shalde064280feec2018-06-15 19:01:29 -0400288 List<String> strPdPushNextHopIPv4List = Arrays.asList(strPdPushNextHopIPv4.split(","));
289 for (String nextHop : strPdPushNextHopIPv4List) {
290 log.debug("IPv4 next hop added is:" + nextHop);
291 pdPushNextHopIPv4.add(Ip4Address.valueOf(nextHop));
292 }
Kalhee Kimba366062017-11-07 16:32:09 +0000293 }
294 String strPdPushNextHopIPv6 = Tools.get(properties, "pdPushNextHopIPv6");
295 if (strPdPushNextHopIPv6 != null) {
shalde064280feec2018-06-15 19:01:29 -0400296 List<String> strPdPushNextHopIPv6List = Arrays.asList(strPdPushNextHopIPv6.split(","));
297 for (String nextHop : strPdPushNextHopIPv6List) {
298 log.debug("IPv6 next hop added is:" + nextHop);
299 pdPushNextHopIPv6.add(Ip6Address.valueOf(nextHop));
300 }
Kalhee Kimba366062017-11-07 16:32:09 +0000301 }
302
Ray Milkey032b9642018-06-21 08:28:12 -0700303 if (pdPushNextHopIPv4.size() == 0) {
shalde064280feec2018-06-15 19:01:29 -0400304 rurIPv4Address = interfaceService.getInterfaces()
Kalhee Kimba366062017-11-07 16:32:09 +0000305 .stream()
306 .filter(iface -> iface.name().contains("RUR"))
307 .map(Interface::ipAddressesList)
308 .flatMap(Collection::stream)
309 .map(InterfaceIpAddress::ipAddress)
310 .filter(IpAddress::isIp4)
311 .map(IpAddress::getIp4Address)
312 .findFirst()
313 .orElse(null);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400314 log.debug("RUR IPv4 address extracted from netcfg is: {}", rurIPv4Address);
shalde064280feec2018-06-15 19:01:29 -0400315 if (rurIPv4Address != null) {
316 pdPushNextHopIPv4.add(rurIPv4Address);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400317 } else {
318 log.debug("Unable to extract RUR IPv4 address from netcfg");
shalde064280feec2018-06-15 19:01:29 -0400319 }
320
Kalhee Kimba366062017-11-07 16:32:09 +0000321 }
322
Mayank Tiwaric679a022018-06-23 11:19:08 -0400323 if (pdPushNextHopIPv6 == null || pdPushNextHopIPv6.size() == 0) {
shalde064280feec2018-06-15 19:01:29 -0400324 rurIPv6Address = interfaceService.getInterfaces()
Kalhee Kimba366062017-11-07 16:32:09 +0000325 .stream()
326 .filter(iface -> iface.name().contains("RUR"))
327 .map(Interface::ipAddressesList)
328 .flatMap(Collection::stream)
329 .map(InterfaceIpAddress::ipAddress)
330 .filter(IpAddress::isIp6)
331 .map(IpAddress::getIp6Address)
332 .findFirst()
333 .orElse(null);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400334 log.debug("RUR IPv6 address extracted from netcfg is: {}", rurIPv6Address);
shalde064280feec2018-06-15 19:01:29 -0400335 if (rurIPv6Address != null) {
336 pdPushNextHopIPv6.add(rurIPv6Address);
Mayank Tiwaric679a022018-06-23 11:19:08 -0400337 } else {
338 log.debug("Unable to extract RUR IPv6 address from netcfg");
shalde064280feec2018-06-15 19:01:29 -0400339 }
Kalhee Kimba366062017-11-07 16:32:09 +0000340 }
341
342 log.info("PD pushing is enabled.");
Ray Milkey032b9642018-06-21 08:28:12 -0700343 if (pdPushNextHopIPv4.size() != 0) {
shalde064280feec2018-06-15 19:01:29 -0400344 log.info("ipv4 next-hop {} with {} items", pdPushNextHopIPv4.toString(), pdPushNextHopIPv4.size());
Kalhee Kimba366062017-11-07 16:32:09 +0000345 } else {
346 log.info("ipv4 next-hop is null");
347 }
Ray Milkey032b9642018-06-21 08:28:12 -0700348 if (pdPushNextHopIPv6.size() != 0) {
shalde064280feec2018-06-15 19:01:29 -0400349 log.info("ipv6 next-hop={} with {} items", pdPushNextHopIPv6.toString(), pdPushNextHopIPv6.size());
Kalhee Kimba366062017-11-07 16:32:09 +0000350 } else {
351 log.info("ipv6 next-hop is null");
352 }
shalde064280feec2018-06-15 19:01:29 -0400353 processStaticRoutes();
Kalhee Kimba366062017-11-07 16:32:09 +0000354 } else {
355 log.info("PD pushing is disabled.");
356 }
357 }
358 }
359
360 private void startServer() {
361 HashedWheelTimer timer = new HashedWheelTimer(
362 groupedThreads("onos/fpm", "fpm-timer-%d", log));
363
364 ChannelFactory channelFactory = new NioServerSocketChannelFactory(
365 newCachedThreadPool(groupedThreads("onos/fpm", "sm-boss-%d", log)),
366 newCachedThreadPool(groupedThreads("onos/fpm", "sm-worker-%d", log)));
367 ChannelPipelineFactory pipelineFactory = () -> {
368 // Allocate a new session per connection
369 IdleStateHandler idleHandler =
370 new IdleStateHandler(timer, IDLE_TIMEOUT_SECS, 0, 0);
371 FpmSessionHandler fpmSessionHandler =
372 new FpmSessionHandler(this, new InternalFpmListener());
373 FpmFrameDecoder fpmFrameDecoder = new FpmFrameDecoder();
374
375 // Setup the processing pipeline
376 ChannelPipeline pipeline = Channels.pipeline();
377 pipeline.addLast("FpmFrameDecoder", fpmFrameDecoder);
378 pipeline.addLast("idle", idleHandler);
379 pipeline.addLast("FpmSession", fpmSessionHandler);
380 return pipeline;
381 };
382
383 InetSocketAddress listenAddress = new InetSocketAddress(FPM_PORT);
384
385 serverBootstrap = new ServerBootstrap(channelFactory);
386 serverBootstrap.setOption("child.reuseAddr", true);
387 serverBootstrap.setOption("child.keepAlive", true);
388 serverBootstrap.setOption("child.tcpNoDelay", true);
389 serverBootstrap.setPipelineFactory(pipelineFactory);
390 try {
391 serverChannel = serverBootstrap.bind(listenAddress);
392 allChannels.add(serverChannel);
393 } catch (ChannelException e) {
394 log.debug("Exception binding to FPM port {}: ",
395 listenAddress.getPort(), e);
396 stopServer();
397 }
398 }
399
400 private void stopServer() {
401 allChannels.close().awaitUninterruptibly();
402 allChannels.clear();
403 if (serverBootstrap != null) {
404 serverBootstrap.releaseExternalResources();
405 }
406
407 if (clearRoutes) {
408 peers.keySet().forEach(this::clearRoutes);
409 }
410 }
411
Kalhee Kim40beb722018-01-16 20:32:04 +0000412 private boolean routeInDhcpStore(IpPrefix prefix) {
413
414 if (dhcpStore != null) {
415 Collection<FpmRecord> dhcpRecords = dhcpStore.getFpmRecords();
416 return dhcpRecords.stream().anyMatch(record -> record.ipPrefix().equals(prefix));
417 }
418 return false;
419 }
420
421 private boolean routeInRipStore(IpPrefix prefix) {
422
423 if (ripStore != null) {
424 Collection<FpmRecord> ripRecords = ripStore.getFpmRecords();
425 return ripRecords.stream().anyMatch(record -> record.ipPrefix().equals(prefix));
426 }
427 return false;
428 }
429
Kalhee Kimba366062017-11-07 16:32:09 +0000430 private void fpmMessage(FpmPeer peer, FpmHeader fpmMessage) {
431 if (fpmMessage.type() == FpmHeader.FPM_TYPE_KEEPALIVE) {
432 return;
433 }
434
435 Netlink netlink = fpmMessage.netlink();
436 RtNetlink rtNetlink = netlink.rtNetlink();
437
438 if (log.isTraceEnabled()) {
439 log.trace("Received FPM message: {}", fpmMessage);
440 }
441
442 if (!(rtNetlink.protocol() == RtProtocol.ZEBRA ||
443 rtNetlink.protocol() == RtProtocol.UNSPEC)) {
444 log.trace("Ignoring non-zebra route");
445 return;
446 }
447
448 IpAddress dstAddress = null;
449 IpAddress gateway = null;
450
451 for (RouteAttribute attribute : rtNetlink.attributes()) {
452 if (attribute.type() == RouteAttribute.RTA_DST) {
453 RouteAttributeDst raDst = (RouteAttributeDst) attribute;
454 dstAddress = raDst.dstAddress();
455 } else if (attribute.type() == RouteAttribute.RTA_GATEWAY) {
456 RouteAttributeGateway raGateway = (RouteAttributeGateway) attribute;
457 gateway = raGateway.gateway();
458 }
459 }
460
461 if (dstAddress == null) {
462 log.error("Dst address missing!");
463 return;
464 }
465
466 IpPrefix prefix = IpPrefix.valueOf(dstAddress, rtNetlink.dstLength());
467
Kalhee Kim40beb722018-01-16 20:32:04 +0000468 // Ignore routes that we sent.
Charles Chaneb42a732018-06-25 13:01:35 -0700469 if (gateway != null && (
470 (prefix.isIp4() && pdPushNextHopIPv4 != null &&
471 pdPushNextHopIPv4.contains(gateway.getIp4Address())) ||
472 (prefix.isIp6() && pdPushNextHopIPv6 != null &&
473 pdPushNextHopIPv6.contains(gateway.getIp6Address())))) {
Kalhee Kim40beb722018-01-16 20:32:04 +0000474 if (routeInDhcpStore(prefix) || routeInRipStore(prefix)) {
475 return;
476 }
477 }
478
Kalhee Kimba366062017-11-07 16:32:09 +0000479 List<Route> updates = new LinkedList<>();
480 List<Route> withdraws = new LinkedList<>();
481
482 Route route;
483 switch (netlink.type()) {
484 case RTM_NEWROUTE:
485 if (gateway == null) {
486 // We ignore interface routes with no gateway for now.
487 return;
488 }
489 route = new Route(Route.Source.FPM, prefix, gateway, clusterService.getLocalNode().id());
490
491
492 Route oldRoute = fpmRoutes.get(peer).put(prefix, route);
493
494 if (oldRoute != null) {
495 log.trace("Swapping {} with {}", oldRoute, route);
496 withdraws.add(oldRoute);
497 }
498 updates.add(route);
499 break;
500 case RTM_DELROUTE:
501 Route existing = fpmRoutes.get(peer).remove(prefix);
502 if (existing == null) {
503 log.warn("Got delete for non-existent prefix");
504 return;
505 }
506
507 route = new Route(Route.Source.FPM, prefix, existing.nextHop(), clusterService.getLocalNode().id());
508
509 withdraws.add(route);
510 break;
511 case RTM_GETROUTE:
512 default:
513 break;
514 }
515
Charles Chan035ed1f2018-01-30 16:00:32 -0800516 updateRouteStore(updates, withdraws);
517 }
518
519 private synchronized void updateRouteStore(Collection<Route> routesToAdd, Collection<Route> routesToRemove) {
520 routeService.withdraw(routesToRemove);
521 routeService.update(routesToAdd);
Kalhee Kimba366062017-11-07 16:32:09 +0000522 }
523
524 private void clearRoutes(FpmPeer peer) {
525 log.info("Clearing all routes for peer {}", peer);
526 Map<IpPrefix, Route> routes = fpmRoutes.remove(peer);
527 if (routes != null) {
Charles Chan035ed1f2018-01-30 16:00:32 -0800528 updateRouteStore(Lists.newArrayList(), routes.values());
Kalhee Kimba366062017-11-07 16:32:09 +0000529 }
530 }
531
532 public void processStaticRoutes() {
shalde064280feec2018-06-15 19:01:29 -0400533 log.debug("processStaticRoutes function is called");
Kalhee Kimba366062017-11-07 16:32:09 +0000534 for (Channel ch : allChannels) {
535 processStaticRoutes(ch);
536 }
537 }
538
539 public void processStaticRoutes(Channel ch) {
540 processRipStaticRoutes(ch);
541 processDhcpStaticRoutes(ch);
542 }
543
544 private void processRipStaticRoutes(Channel ch) {
545
546 /* Get RIP static routes. */
547 if (ripStore != null) {
548 Collection<FpmRecord> ripRecords = ripStore.getFpmRecords();
549 log.info("RIP store size is {}", ripRecords.size());
550
551 ripRecords.forEach(record -> sendRouteUpdateToChannel(true,
552 record.ipPrefix(), ch));
553 }
554 }
555
556 private void processDhcpStaticRoutes(Channel ch) {
557
558 /* Get Dhcp static routes. */
559 if (dhcpStore != null) {
560 Collection<FpmRecord> dhcpRecords = dhcpStore.getFpmRecords();
561 log.info("Dhcp store size is {}", dhcpRecords.size());
562
563 dhcpRecords.forEach(record -> sendRouteUpdateToChannel(true,
564 record.ipPrefix(), ch));
565 }
566 }
567
shalde064280feec2018-06-15 19:01:29 -0400568 private void updateRoute(IpAddress pdPushNextHop, boolean isAdd, IpPrefix prefix,
569 Channel ch, int raLength, short addrFamily) {
Kalhee Kimba366062017-11-07 16:32:09 +0000570 try {
shalde064280feec2018-06-15 19:01:29 -0400571 RouteAttributeDst raDst = RouteAttributeDst.builder()
572 .length(raLength)
573 .type(RouteAttribute.RTA_DST)
574 .dstAddress(prefix.address())
575 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000576
Kalhee Kim715dd732018-01-23 14:39:56 +0000577 RouteAttributeGateway raGateway = RouteAttributeGateway.builder()
shalde064280feec2018-06-15 19:01:29 -0400578 .length(raLength)
579 .type(RouteAttribute.RTA_GATEWAY)
580 .gateway(pdPushNextHop)
581 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000582
Kalhee Kim715dd732018-01-23 14:39:56 +0000583 // Build RtNetlink.
584 RtNetlink rtNetlink = RtNetlink.builder()
shalde064280feec2018-06-15 19:01:29 -0400585 .addressFamily(addrFamily)
586 .dstLength(prefix.prefixLength())
587 .routeAttribute(raDst)
588 .routeAttribute(raGateway)
589 .build();
Kalhee Kim715dd732018-01-23 14:39:56 +0000590
591 // Build Netlink.
Kalhee Kimba366062017-11-07 16:32:09 +0000592 int messageLength = raDst.length() + raGateway.length() +
shalde064280feec2018-06-15 19:01:29 -0400593 RtNetlink.RT_NETLINK_LENGTH + Netlink.NETLINK_HEADER_LENGTH;
Kalhee Kim715dd732018-01-23 14:39:56 +0000594 Netlink netLink = Netlink.builder()
shalde064280feec2018-06-15 19:01:29 -0400595 .length(messageLength)
596 .type(isAdd ? NetlinkMessageType.RTM_NEWROUTE : NetlinkMessageType.RTM_DELROUTE)
597 .flags(Netlink.NETLINK_REQUEST | Netlink.NETLINK_CREATE)
598 .rtNetlink(rtNetlink)
599 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000600
Kalhee Kim715dd732018-01-23 14:39:56 +0000601 // Build FpmHeader.
Kalhee Kimba366062017-11-07 16:32:09 +0000602 messageLength += FpmHeader.FPM_HEADER_LENGTH;
Kalhee Kim715dd732018-01-23 14:39:56 +0000603 FpmHeader fpmMessage = FpmHeader.builder()
shalde064280feec2018-06-15 19:01:29 -0400604 .version(FpmHeader.FPM_VERSION_1)
605 .type(FpmHeader.FPM_TYPE_NETLINK)
606 .length(messageLength)
607 .netlink(netLink)
608 .build();
Kalhee Kimba366062017-11-07 16:32:09 +0000609
610 // Encode message in a channel buffer and transmit.
611 ch.write(fpmMessage.encode());
612
613 } catch (RuntimeException e) {
614 log.info("Route not sent over fpm connection.");
615 }
616 }
617
shalde064280feec2018-06-15 19:01:29 -0400618 private void sendRouteUpdateToChannel(boolean isAdd, IpPrefix prefix, Channel ch) {
619
620 if (!pdPushEnabled) {
621 return;
622 }
623 int raLength;
624 short addrFamily;
625
626 // Build route attributes.
627 if (prefix.isIp4()) {
628 List<Ip4Address> pdPushNextHopList;
629 if (pdPushNextHopIPv4 == null || pdPushNextHopIPv4.size() == 0) {
630 log.info("Prefix not pushed because ipv4 next-hop is null.");
631 return;
632 }
633 pdPushNextHopList = pdPushNextHopIPv4;
634 raLength = Ip4Address.BYTE_LENGTH + RouteAttribute.ROUTE_ATTRIBUTE_HEADER_LENGTH;
635 addrFamily = RtNetlink.RT_ADDRESS_FAMILY_INET;
636 for (Ip4Address pdPushNextHop: pdPushNextHopList) {
637 log.debug("IPv4 next hop is:" + pdPushNextHop);
638 updateRoute(pdPushNextHop, isAdd, prefix, ch, raLength, addrFamily);
639 }
640 } else {
641 List<Ip6Address> pdPushNextHopList;
642 if (pdPushNextHopIPv6 == null || pdPushNextHopIPv6.size() == 0) {
643 log.info("Prefix not pushed because ipv6 next-hop is null.");
644 return;
645 }
646 pdPushNextHopList = pdPushNextHopIPv6;
647 raLength = Ip6Address.BYTE_LENGTH + RouteAttribute.ROUTE_ATTRIBUTE_HEADER_LENGTH;
648 addrFamily = RtNetlink.RT_ADDRESS_FAMILY_INET6;
649 for (Ip6Address pdPushNextHop: pdPushNextHopList) {
650 log.debug("IPv6 next hop is:" + pdPushNextHop);
651 updateRoute(pdPushNextHop, isAdd, prefix, ch, raLength, addrFamily);
652 }
653 }
654 }
655
Kalhee Kimba366062017-11-07 16:32:09 +0000656 private void sendRouteUpdate(boolean isAdd, IpPrefix prefix) {
657
658 for (Channel ch : allChannels) {
659 sendRouteUpdateToChannel(isAdd, prefix, ch);
660 }
661 }
662
663 public boolean isPdPushEnabled() {
664 return pdPushEnabled;
665 }
666
667 private FpmPeerInfo toFpmInfo(FpmPeer peer, Collection<FpmConnectionInfo> connections) {
668 return new FpmPeerInfo(connections,
669 fpmRoutes.getOrDefault(peer, Collections.emptyMap()).size());
670 }
671
672 @Override
673 public Map<FpmPeer, FpmPeerInfo> peers() {
674 return peers.asJavaMap().entrySet().stream()
675 .collect(Collectors.toMap(
676 e -> e.getKey(),
677 e -> toFpmInfo(e.getKey(), e.getValue())));
678 }
679
680 private class InternalFpmListener implements FpmListener {
681 @Override
682 public void fpmMessage(FpmPeer peer, FpmHeader fpmMessage) {
683 FpmManager.this.fpmMessage(peer, fpmMessage);
684 }
685
686 @Override
687 public boolean peerConnected(FpmPeer peer) {
688 if (peers.keySet().contains(peer)) {
689 return false;
690 }
691
692 NodeId localNode = clusterService.getLocalNode().id();
693 peers.compute(peer, (p, infos) -> {
694 if (infos == null) {
695 infos = new HashSet<>();
696 }
697
698 infos.add(new FpmConnectionInfo(localNode, peer, System.currentTimeMillis()));
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700699 localPeers.put(peer, infos);
Kalhee Kimba366062017-11-07 16:32:09 +0000700 return infos;
701 });
702
703 fpmRoutes.computeIfAbsent(peer, p -> new ConcurrentHashMap<>());
704 return true;
705 }
706
707 @Override
708 public void peerDisconnected(FpmPeer peer) {
709 log.info("FPM connection to {} went down", peer);
710
711 if (clearRoutes) {
712 clearRoutes(peer);
713 }
714
715 peers.compute(peer, (p, infos) -> {
716 if (infos == null) {
717 return null;
718 }
719
720 infos.stream()
721 .filter(i -> i.connectedTo().equals(clusterService.getLocalNode().id()))
722 .findAny()
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700723 .ifPresent(i -> {
724 infos.remove(i);
725 localPeers.get(peer).remove(i);
726 });
Kalhee Kimba366062017-11-07 16:32:09 +0000727
728 if (infos.isEmpty()) {
729 return null;
730 }
731
732 return infos;
733 });
734 }
735 }
736
737 /**
738 * Adds a channel to the channel group.
739 *
740 * @param channel the channel to add
741 */
742 public void addSessionChannel(Channel channel) {
743 allChannels.add(channel);
744 }
745
746 /**
747 * Removes a channel from the channel group.
748 *
749 * @param channel the channel to remove
750 */
751 public void removeSessionChannel(Channel channel) {
752 allChannels.remove(channel);
753 }
754
755 /**
756 * Store delegate for Fpm Prefix store.
757 * Handles Fpm prefix store event.
758 */
759 class FpmPrefixStoreDelegate implements StoreDelegate<FpmPrefixStoreEvent> {
760
761 @Override
762 public void notify(FpmPrefixStoreEvent e) {
763
764 log.trace("FpmPrefixStoreEvent notify");
765
766 FpmRecord record = e.subject();
767 switch (e.type()) {
768 case ADD:
769 sendRouteUpdate(true, record.ipPrefix());
770 break;
771 case REMOVE:
772 sendRouteUpdate(false, record.ipPrefix());
773 break;
774 default:
775 log.warn("unsupported store event type", e.type());
776 return;
777 }
778 }
779 }
Charles Chan035ed1f2018-01-30 16:00:32 -0800780
781 private class InternalClusterListener implements ClusterEventListener {
782 @Override
783 public void event(ClusterEvent event) {
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700784 clusterEventExecutor.execute(() -> {
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700785 log.info("Receives ClusterEvent {} for {}", event.type(), event.subject().id());
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700786 switch (event.type()) {
787 case INSTANCE_READY:
788 // When current node is healing from a network partition,
789 // seeing INSTANCE_READY means current node has the ability to read from the cluster,
790 // but it is possible that current node still can't write to the cluster at this moment.
791 // The AsyncDistributedLock is introduced to ensure we attempt to push FPM routes
792 // after current node can write.
793 // Adding 15 seconds retry for the current node to be able to write.
794 asyncLock.tryLock(Duration.ofSeconds(15)).whenComplete((result, error) -> {
795 if (result != null && result.isPresent()) {
796 log.debug("Lock obtained. Push local FPM routes to route store");
797 // All FPM routes on current node will be pushed again even when current node is not
798 // the one that becomes READY. A better way is to do this only on the minority nodes.
799 pushFpmRoutes();
800 localPeers.forEach((key, value) -> peers.put(key, value));
801 asyncLock.unlock();
802 } else {
803 log.debug("Fail to obtain lock. Abort.");
804 }
805 });
806 break;
807 case INSTANCE_DEACTIVATED:
808 case INSTANCE_REMOVED:
809 ImmutableMap.copyOf(peers.asJavaMap()).forEach((key, value) -> {
810 if (value != null) {
811 value.stream()
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700812 .filter(i -> i.connectedTo().equals(event.subject().id()))
813 .findAny()
814 .ifPresent(value::remove);
815
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700816 if (value.isEmpty()) {
817 peers.remove(key);
818 }
Andrea Campanella4310f6e2018-03-27 16:35:39 -0700819 }
Jordan Haltermanaa2faca2018-08-13 02:41:50 -0700820 });
821 break;
822 case INSTANCE_ADDED:
823 case INSTANCE_ACTIVATED:
824 default:
825 break;
826 }
827 });
Charles Chan035ed1f2018-01-30 16:00:32 -0800828 }
829 }
830
Saurav Dase7f51012018-02-09 17:26:45 -0800831 @Override
Charles Chan035ed1f2018-01-30 16:00:32 -0800832 public void pushFpmRoutes() {
833 Set<Route> routes = fpmRoutes.values().stream()
834 .map(Map::entrySet).flatMap(Set::stream).map(Map.Entry::getValue)
835 .collect(Collectors.toSet());
836 updateRouteStore(routes, Lists.newArrayList());
837 log.info("{} FPM routes have been updated to route store", routes.size());
838 }
Kalhee Kimba366062017-11-07 16:32:09 +0000839}