View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.ipc;
19  
20  import io.netty.buffer.ByteBuf;
21  import io.netty.buffer.ByteBufInputStream;
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.channel.ChannelInboundHandlerAdapter;
24  
25  import java.io.IOException;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.CellScanner;
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.hbase.protobuf.generated.RPCProtos;
32  import org.apache.hadoop.ipc.RemoteException;
33  
34  import com.google.protobuf.Message;
35  
36  /**
37   * Handles Hbase responses
38   */
39  @InterfaceAudience.Private
40  public class AsyncServerResponseHandler extends ChannelInboundHandlerAdapter {
41    public static final Log LOG = LogFactory.getLog(AsyncServerResponseHandler.class.getName());
42  
43    private final AsyncRpcChannel channel;
44  
45    /**
46     * Constructor
47     *
48     * @param channel on which this response handler operates
49     */
50    public AsyncServerResponseHandler(AsyncRpcChannel channel) {
51      this.channel = channel;
52    }
53  
54    @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
55      ByteBuf inBuffer = (ByteBuf) msg;
56      ByteBufInputStream in = new ByteBufInputStream(inBuffer);
57      int totalSize = inBuffer.readableBytes();
58      try {
59        // Read the header
60        RPCProtos.ResponseHeader responseHeader = RPCProtos.ResponseHeader.parseDelimitedFrom(in);
61        int id = responseHeader.getCallId();
62        AsyncCall call = channel.removePendingCall(id);
63        if (call == null) {
64          // So we got a response for which we have no corresponding 'call' here on the client-side.
65          // We probably timed out waiting, cleaned up all references, and now the server decides
66          // to return a response.  There is nothing we can do w/ the response at this stage. Clean
67          // out the wire of the response so its out of the way and we can get other responses on
68          // this connection.
69          int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader);
70          int whatIsLeftToRead = totalSize - readSoFar;
71  
72          // This is done through a Netty ByteBuf which has different behavior than InputStream.
73          // It does not return number of bytes read but will update pointer internally and throws an
74          // exception when too many bytes are to be skipped.
75          inBuffer.skipBytes(whatIsLeftToRead);
76          return;
77        }
78  
79        if (responseHeader.hasException()) {
80          RPCProtos.ExceptionResponse exceptionResponse = responseHeader.getException();
81          RemoteException re = createRemoteException(exceptionResponse);
82          if (exceptionResponse.getExceptionClassName().
83              equals(FatalConnectionException.class.getName())) {
84            channel.close(re);
85          } else {
86            call.setFailed(re);
87          }
88        } else {
89          Message value = null;
90          // Call may be null because it may have timedout and been cleaned up on this side already
91          if (call.responseDefaultType != null) {
92            Message.Builder builder = call.responseDefaultType.newBuilderForType();
93            builder.mergeDelimitedFrom(in);
94            value = builder.build();
95          }
96          CellScanner cellBlockScanner = null;
97          if (responseHeader.hasCellBlockMeta()) {
98            int size = responseHeader.getCellBlockMeta().getLength();
99            byte[] cellBlock = new byte[size];
100           inBuffer.readBytes(cellBlock, 0, cellBlock.length);
101           cellBlockScanner = channel.client.createCellScanner(cellBlock);
102         }
103         call.setSuccess(value, cellBlockScanner);
104       }
105     } catch (IOException e) {
106       // Treat this as a fatal condition and close this connection
107       channel.close(e);
108     } finally {
109       inBuffer.release();
110     }
111   }
112 
113   /**
114    * @param e Proto exception
115    * @return RemoteException made from passed <code>e</code>
116    */
117   private RemoteException createRemoteException(final RPCProtos.ExceptionResponse e) {
118     String innerExceptionClassName = e.getExceptionClassName();
119     boolean doNotRetry = e.getDoNotRetry();
120     return e.hasHostname() ?
121         // If a hostname then add it to the RemoteWithExtrasException
122         new RemoteWithExtrasException(innerExceptionClassName, e.getStackTrace(), e.getHostname(),
123             e.getPort(), doNotRetry) :
124         new RemoteWithExtrasException(innerExceptionClassName, e.getStackTrace(), doNotRetry);
125   }
126 }