926a7761d34876a2e860331f4af19248ba8913a4
[mdsal.git] / replicate / mdsal-replicate-netty / src / main / java / org / opendaylight / mdsal / replicate / netty / AbstractBootstrapSupport.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  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.mdsal.replicate.netty;
9
10 import static java.util.Objects.requireNonNull;
11
12 import io.netty.bootstrap.Bootstrap;
13 import io.netty.bootstrap.ServerBootstrap;
14 import io.netty.channel.Channel;
15 import io.netty.channel.EventLoopGroup;
16 import io.netty.channel.epoll.Epoll;
17 import io.netty.channel.socket.ServerSocketChannel;
18 import java.util.concurrent.TimeUnit;
19 import org.eclipse.jdt.annotation.NonNull;
20
21 public abstract class AbstractBootstrapSupport implements AutoCloseable, BootstrapSupport {
22     private final Class<? extends Channel> channelClass;
23     private final Class<? extends ServerSocketChannel> serverChannelClass;
24     private final EventLoopGroup bossGroup;
25     private final EventLoopGroup workerGroup;
26
27     AbstractBootstrapSupport(final Class<? extends Channel> channelClass,
28             final Class<? extends ServerSocketChannel> serverChannelClass, final EventLoopGroup bossGroup,
29             final EventLoopGroup workerGroup) {
30         this.channelClass = requireNonNull(channelClass);
31         this.serverChannelClass = requireNonNull(serverChannelClass);
32         this.bossGroup = requireNonNull(bossGroup);
33         this.workerGroup = requireNonNull(workerGroup);
34     }
35
36     public static @NonNull BootstrapSupport create() {
37         if (Epoll.isAvailable()) {
38             return new EpollBootstrapSupport();
39         }
40         return new NioBootstrapSupport();
41     }
42
43     @Override
44     public final Bootstrap newBootstrap() {
45         return new Bootstrap().group(workerGroup).channel(channelClass);
46     }
47
48     @Override
49     public  final ServerBootstrap newServerBootstrap() {
50         return new ServerBootstrap().group(bossGroup, workerGroup).channel(serverChannelClass);
51     }
52
53     @Override
54     public final void close() throws InterruptedException {
55         bossGroup.shutdownGracefully();
56         workerGroup.shutdownGracefully();
57
58         bossGroup.awaitTermination(10, TimeUnit.SECONDS);
59         workerGroup.awaitTermination(10, TimeUnit.SECONDS);
60     }
61 }