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.util;
019
020import org.apache.yetus.audience.InterfaceAudience;
021
022import org.apache.hbase.thirdparty.io.netty.channel.Channel;
023import org.apache.hbase.thirdparty.io.netty.channel.ChannelOption;
024import org.apache.hbase.thirdparty.io.netty.channel.ChannelOutboundBuffer;
025
026/**
027 * Wraps some usages of netty's unsafe API, for ease of maintainability.
028 */
029@InterfaceAudience.Private
030public final class NettyUnsafeUtils {
031
032  private NettyUnsafeUtils() {
033  }
034
035  /**
036   * Directly closes the channel, setting SO_LINGER to 0 and skipping any handlers in the pipeline.
037   * This is useful for cases where it's important to immediately close without any delay.
038   * Otherwise, pipeline handlers and even general TCP flows can cause a normal close to take
039   * upwards of a few second or more. This will likely cause the client side to see either a
040   * "Connection reset by peer" or unexpected ConnectionClosedException.
041   * <p>
042   * <b>It's necessary to call this from within the channel's eventLoop!</b>
043   */
044  public static void closeImmediately(Channel channel) {
045    assert channel.eventLoop().inEventLoop();
046    channel.config().setOption(ChannelOption.SO_LINGER, 0);
047    channel.unsafe().close(channel.voidPromise());
048  }
049
050  /**
051   * Get total bytes pending write to socket
052   */
053  public static long getTotalPendingOutboundBytes(Channel channel) {
054    ChannelOutboundBuffer outboundBuffer = channel.unsafe().outboundBuffer();
055    // can be null when the channel is closing
056    if (outboundBuffer == null) {
057      return 0;
058    }
059    return outboundBuffer.totalPendingWriteBytes();
060  }
061}