Refactor BmpDispatcherUtil
[bgpcep.git] / bmp / bmp-impl / src / main / java / org / opendaylight / protocol / bmp / impl / BmpNettyGroups.java
1 /*
2  * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bmp.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.util.concurrent.ThreadFactoryBuilder;
13 import io.netty.bootstrap.AbstractBootstrap;
14 import io.netty.bootstrap.Bootstrap;
15 import io.netty.bootstrap.ServerBootstrap;
16 import io.netty.buffer.PooledByteBufAllocator;
17 import io.netty.channel.AbstractChannel;
18 import io.netty.channel.ChannelInitializer;
19 import io.netty.channel.ChannelOption;
20 import io.netty.channel.EventLoopGroup;
21 import io.netty.channel.epoll.Epoll;
22 import io.netty.channel.epoll.EpollChannelOption;
23 import io.netty.channel.epoll.EpollEventLoopGroup;
24 import io.netty.channel.epoll.EpollServerSocketChannel;
25 import io.netty.channel.epoll.EpollSocketChannel;
26 import io.netty.channel.nio.NioEventLoopGroup;
27 import io.netty.channel.socket.nio.NioServerSocketChannel;
28 import io.netty.channel.socket.nio.NioSocketChannel;
29 import java.net.InetSocketAddress;
30 import java.net.SocketAddress;
31 import java.util.concurrent.ThreadFactory;
32 import java.util.concurrent.TimeUnit;
33 import javax.annotation.PreDestroy;
34 import javax.inject.Inject;
35 import javax.inject.Singleton;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.opendaylight.protocol.bmp.api.BmpSessionFactory;
39 import org.opendaylight.protocol.bmp.api.BmpSessionListenerFactory;
40 import org.opendaylight.protocol.concepts.KeyMapping;
41 import org.osgi.service.component.annotations.Activate;
42 import org.osgi.service.component.annotations.Component;
43 import org.osgi.service.component.annotations.Deactivate;
44
45 @Singleton
46 @Component(service = BmpNettyGroups.class)
47 public final class BmpNettyGroups implements AutoCloseable {
48     @FunctionalInterface
49     public interface CreateChannel {
50         ChannelInitializer<AbstractChannel> create(@NonNull BmpSessionFactory sessionFactory,
51                 @NonNull BmpHandlerFactory hf, @NonNull BmpSessionListenerFactory slf);
52     }
53
54     private abstract static class AbstractImpl {
55         private final EventLoopGroup bossGroup;
56         private final EventLoopGroup workerGroup;
57
58         AbstractImpl(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
59             this.bossGroup = requireNonNull(bossGroup);
60             this.workerGroup = requireNonNull(workerGroup);
61         }
62
63         abstract void setupBootstrap(Bootstrap bootstrap);
64
65         abstract void setupBootstrap(ServerBootstrap serverBootstrap);
66
67         abstract void setupKeys(AbstractBootstrap<?, ?> bootstrap, KeyMapping keys);
68     }
69
70     private static final class EpollImpl extends AbstractImpl {
71         EpollImpl() {
72             super(new EpollEventLoopGroup(BOSS_TF), new EpollEventLoopGroup(WORKER_TF));
73         }
74
75         @Override
76         void setupBootstrap(final Bootstrap bootstrap) {
77             bootstrap.channel(EpollSocketChannel.class);
78         }
79
80         @Override
81         void setupBootstrap(final ServerBootstrap serverBootstrap) {
82             serverBootstrap.channel(EpollServerSocketChannel.class);
83         }
84
85         @Override
86         void setupKeys(final AbstractBootstrap<?, ?> bootstrap, final KeyMapping keys) {
87             bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
88         }
89     }
90
91     private static final class NioImpl extends AbstractImpl {
92         NioImpl() {
93             super(new NioEventLoopGroup(BOSS_TF), new NioEventLoopGroup(WORKER_TF));
94         }
95
96         @Override
97         void setupBootstrap(final Bootstrap bootstrap) {
98             bootstrap.channel(NioSocketChannel.class);
99         }
100
101         @Override
102         void setupBootstrap(final ServerBootstrap serverBootstrap) {
103             serverBootstrap.channel(NioServerSocketChannel.class);
104         }
105
106         @Override
107         void setupKeys(final AbstractBootstrap<?, ?> bootstrap, final KeyMapping keys) {
108             throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
109         }
110     }
111
112     private static final ThreadFactory BOSS_TF = new ThreadFactoryBuilder()
113         .setNameFormat("bmp-boss-%d")
114         .setDaemon(true)
115         .build();
116     private static final ThreadFactory WORKER_TF = new ThreadFactoryBuilder()
117         .setNameFormat("bmp-worker-%d")
118         .setDaemon(true)
119         .build();
120     private static final int MAX_CONNECTIONS_COUNT = 128;
121     private static final long TIMEOUT = 10;
122
123     private AbstractImpl impl;
124
125     @Inject
126     @Activate
127     public BmpNettyGroups() {
128         impl = Epoll.isAvailable() ? new EpollImpl() : new NioImpl();
129     }
130
131     @PreDestroy
132     @Deactivate
133     @Override
134     public void close() {
135         if (impl != null) {
136             impl.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
137             impl.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
138             impl = null;
139         }
140     }
141
142     public static ChannelInitializer<AbstractChannel> createChannelWithDecoder(
143             final @NonNull BmpSessionFactory sessionFactory, final @NonNull BmpHandlerFactory hf,
144             final @NonNull BmpSessionListenerFactory slf) {
145         return new ChannelInitializer<>() {
146             @Override
147             protected void initChannel(final AbstractChannel ch) throws Exception {
148                 ch.pipeline().addLast(hf.getDecoders()).addLast(sessionFactory.getSession(ch, slf));
149             }
150         };
151     }
152
153     public static ChannelInitializer<AbstractChannel> createChannelWithEncoder(
154             final @NonNull BmpSessionFactory sessionFactory, final @NonNull BmpHandlerFactory hf,
155             final @NonNull BmpSessionListenerFactory slf) {
156         return new ChannelInitializer<>() {
157             @Override
158             protected void initChannel(final AbstractChannel ch) throws Exception {
159                 ch.pipeline().addLast(hf.getEncoders()).addLast(sessionFactory.getSession(ch, slf));
160             }
161         };
162     }
163
164     /**
165      * To be used by BMP Dispatcher mainly.
166      */
167     public ServerBootstrap createServerBootstrap(final @NonNull BmpSessionFactory sessionFactory,
168             final @NonNull BmpHandlerFactory hf, final @NonNull BmpSessionListenerFactory slf,
169             final @NonNull CreateChannel createChannel, final @NonNull KeyMapping keys) {
170         final var serverBootstrap = new ServerBootstrap();
171         impl.setupBootstrap(serverBootstrap);
172         if (!keys.isEmpty()) {
173             impl.setupKeys(serverBootstrap, keys);
174         }
175
176         return serverBootstrap.childHandler(createChannel.create(sessionFactory, hf, slf))
177             .option(ChannelOption.SO_BACKLOG, MAX_CONNECTIONS_COUNT)
178             .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
179             .group(impl.bossGroup, impl.workerGroup);
180     }
181
182     /**
183      * To be used by BMP Dispatcher mainly.
184      */
185     public Bootstrap createClientBootstrap(final @NonNull BmpSessionFactory sessionFactory,
186             final @NonNull BmpHandlerFactory hf, final @NonNull CreateChannel createChannel,
187             final @NonNull BmpSessionListenerFactory slf, final @NonNull InetSocketAddress remoteAddress,
188             final int connectTimeout, final @NonNull KeyMapping keys) {
189         return createClientBootstrap(sessionFactory, hf, createChannel, slf, remoteAddress, null, connectTimeout, keys,
190             false);
191     }
192
193     public Bootstrap createClientBootstrap(final @NonNull BmpSessionFactory sessionFactory,
194             final @NonNull BmpHandlerFactory hf, final @NonNull CreateChannel createChannel,
195             final @NonNull BmpSessionListenerFactory slf, final @NonNull InetSocketAddress remoteAddress,
196             final @Nullable SocketAddress localAddress, final int connectTimeout, final @NonNull KeyMapping keys,
197             final boolean reuseAddress) {
198         final var bootstrap = new Bootstrap();
199         impl.setupBootstrap(bootstrap);
200         if (!keys.isEmpty()) {
201             impl.setupKeys(bootstrap, keys);
202         }
203         if (localAddress != null) {
204             bootstrap.localAddress(localAddress);
205         }
206         return bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress)
207             .option(ChannelOption.SO_KEEPALIVE, true)
208             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
209             .group(impl.workerGroup)
210             .handler(createChannel.create(sessionFactory, hf, slf))
211             .remoteAddress(remoteAddress);
212     }
213 }