001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.ipc;
019
020import org.apache.hbase.thirdparty.io.netty.bootstrap.ServerBootstrap;
021import org.apache.hbase.thirdparty.io.netty.channel.Channel;
022import org.apache.hbase.thirdparty.io.netty.channel.ChannelInitializer;
023import org.apache.hbase.thirdparty.io.netty.channel.ChannelOption;
024import org.apache.hbase.thirdparty.io.netty.channel.ChannelPipeline;
025import org.apache.hbase.thirdparty.io.netty.channel.EventLoopGroup;
026import org.apache.hbase.thirdparty.io.netty.channel.ServerChannel;
027import org.apache.hbase.thirdparty.io.netty.channel.group.ChannelGroup;
028import org.apache.hbase.thirdparty.io.netty.channel.group.DefaultChannelGroup;
029import org.apache.hbase.thirdparty.io.netty.channel.nio.NioEventLoopGroup;
030import org.apache.hbase.thirdparty.io.netty.channel.socket.nio.NioServerSocketChannel;
031import org.apache.hbase.thirdparty.io.netty.handler.codec.FixedLengthFrameDecoder;
032import org.apache.hbase.thirdparty.io.netty.util.concurrent.DefaultThreadFactory;
033import org.apache.hbase.thirdparty.io.netty.util.concurrent.GlobalEventExecutor;
034
035import java.io.IOException;
036import java.io.InterruptedIOException;
037import java.net.InetSocketAddress;
038import java.util.List;
039import java.util.concurrent.CountDownLatch;
040
041import org.apache.hadoop.conf.Configuration;
042import org.apache.hadoop.hbase.CellScanner;
043import org.apache.hadoop.hbase.HBaseInterfaceAudience;
044import org.apache.hadoop.hbase.Server;
045import org.apache.yetus.audience.InterfaceAudience;
046import org.slf4j.Logger;
047import org.slf4j.LoggerFactory;
048import org.apache.hadoop.hbase.monitoring.MonitoredRPCHandler;
049import org.apache.hadoop.hbase.regionserver.HRegionServer;
050import org.apache.hadoop.hbase.security.HBasePolicyProvider;
051import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
052import org.apache.hbase.thirdparty.com.google.protobuf.BlockingService;
053import org.apache.hbase.thirdparty.com.google.protobuf.Descriptors.MethodDescriptor;
054import org.apache.hbase.thirdparty.com.google.protobuf.Message;
055import org.apache.hadoop.hbase.util.NettyEventLoopGroupConfig;
056import org.apache.hadoop.hbase.util.Pair;
057import org.apache.hadoop.security.authorize.ServiceAuthorizationManager;
058
059/**
060 * An RPC server with Netty4 implementation.
061 * @since 2.0.0
062 */
063@InterfaceAudience.LimitedPrivate({HBaseInterfaceAudience.CONFIG})
064public class NettyRpcServer extends RpcServer {
065
066  public static final Logger LOG = LoggerFactory.getLogger(NettyRpcServer.class);
067
068  private final InetSocketAddress bindAddress;
069
070  private final CountDownLatch closed = new CountDownLatch(1);
071  private final Channel serverChannel;
072  private final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
073
074  public NettyRpcServer(Server server, String name, List<BlockingServiceAndInterface> services,
075      InetSocketAddress bindAddress, Configuration conf, RpcScheduler scheduler,
076      boolean reservoirEnabled) throws IOException {
077    super(server, name, services, bindAddress, conf, scheduler, reservoirEnabled);
078    this.bindAddress = bindAddress;
079    EventLoopGroup eventLoopGroup;
080    Class<? extends ServerChannel> channelClass;
081    if (server instanceof HRegionServer) {
082      NettyEventLoopGroupConfig config = ((HRegionServer) server).getEventLoopGroupConfig();
083      eventLoopGroup = config.group();
084      channelClass = config.serverChannelClass();
085    } else {
086      eventLoopGroup = new NioEventLoopGroup(0,
087          new DefaultThreadFactory("NettyRpcServer", true, Thread.MAX_PRIORITY));
088      channelClass = NioServerSocketChannel.class;
089    }
090    ServerBootstrap bootstrap = new ServerBootstrap().group(eventLoopGroup).channel(channelClass)
091        .childOption(ChannelOption.TCP_NODELAY, tcpNoDelay)
092        .childOption(ChannelOption.SO_KEEPALIVE, tcpKeepAlive)
093        .childHandler(new ChannelInitializer<Channel>() {
094
095          @Override
096          protected void initChannel(Channel ch) throws Exception {
097            ChannelPipeline pipeline = ch.pipeline();
098            FixedLengthFrameDecoder preambleDecoder = new FixedLengthFrameDecoder(6);
099            preambleDecoder.setSingleDecode(true);
100            pipeline.addLast("preambleDecoder", preambleDecoder);
101            pipeline.addLast("preambleHandler", createNettyRpcServerPreambleHandler());
102            pipeline.addLast("frameDecoder", new NettyRpcFrameDecoder(maxRequestSize));
103            pipeline.addLast("decoder", new NettyRpcServerRequestDecoder(allChannels, metrics));
104            pipeline.addLast("encoder", new NettyRpcServerResponseEncoder(metrics));
105          }
106        });
107    try {
108      serverChannel = bootstrap.bind(this.bindAddress).sync().channel();
109      LOG.info("Bind to {}", serverChannel.localAddress());
110    } catch (InterruptedException e) {
111      throw new InterruptedIOException(e.getMessage());
112    }
113    initReconfigurable(conf);
114    this.scheduler.init(new RpcSchedulerContext(this));
115  }
116
117  @VisibleForTesting
118  protected NettyRpcServerPreambleHandler createNettyRpcServerPreambleHandler() {
119    return new NettyRpcServerPreambleHandler(NettyRpcServer.this);
120  }
121
122  @Override
123  public synchronized void start() {
124    if (started) {
125      return;
126    }
127    authTokenSecretMgr = createSecretManager();
128    if (authTokenSecretMgr != null) {
129      setSecretManager(authTokenSecretMgr);
130      authTokenSecretMgr.start();
131    }
132    this.authManager = new ServiceAuthorizationManager();
133    HBasePolicyProvider.init(conf, authManager);
134    scheduler.start();
135    started = true;
136  }
137
138  @Override
139  public synchronized void stop() {
140    if (!running) {
141      return;
142    }
143    LOG.info("Stopping server on " + this.serverChannel.localAddress());
144    if (authTokenSecretMgr != null) {
145      authTokenSecretMgr.stop();
146      authTokenSecretMgr = null;
147    }
148    allChannels.close().awaitUninterruptibly();
149    serverChannel.close();
150    scheduler.stop();
151    closed.countDown();
152    running = false;
153  }
154
155  @Override
156  public synchronized void join() throws InterruptedException {
157    closed.await();
158  }
159
160  @Override
161  public synchronized InetSocketAddress getListenerAddress() {
162    return ((InetSocketAddress) serverChannel.localAddress());
163  }
164
165  @Override
166  public void setSocketSendBufSize(int size) {
167  }
168
169  @Override
170  public int getNumOpenConnections() {
171    // allChannels also contains the server channel, so exclude that from the count.
172    return allChannels.size() - 1;
173  }
174
175  @Override
176  public Pair<Message, CellScanner> call(BlockingService service,
177      MethodDescriptor md, Message param, CellScanner cellScanner,
178      long receiveTime, MonitoredRPCHandler status) throws IOException {
179    return call(service, md, param, cellScanner, receiveTime, status,
180        System.currentTimeMillis(), 0);
181  }
182
183  @Override
184  public Pair<Message, CellScanner> call(BlockingService service, MethodDescriptor md,
185      Message param, CellScanner cellScanner, long receiveTime, MonitoredRPCHandler status,
186      long startTime, int timeout) throws IOException {
187    NettyServerCall fakeCall = new NettyServerCall(-1, service, md, null, param, cellScanner, null,
188        -1, null, receiveTime, timeout, reservoir, cellBlockBuilder, null);
189    return call(fakeCall, status);
190  }
191}