View Javadoc

1   package org.apache.hadoop.hbase.ipc;
2   /**
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  import java.nio.channels.ClosedChannelException;
20  
21  import org.apache.hadoop.hbase.classification.InterfaceAudience;
22  import org.apache.hadoop.hbase.CellScanner;
23  import org.apache.hadoop.hbase.ipc.RpcServer.Call;
24  import org.apache.hadoop.hbase.monitoring.MonitoredRPCHandler;
25  import org.apache.hadoop.hbase.monitoring.TaskMonitor;
26  import org.apache.hadoop.hbase.security.UserProvider;
27  import org.apache.hadoop.hbase.util.Pair;
28  import org.apache.hadoop.security.UserGroupInformation;
29  import org.apache.hadoop.util.StringUtils;
30  import org.cloudera.htrace.Trace;
31  import org.cloudera.htrace.TraceScope;
32  
33  import com.google.protobuf.Message;
34  
35  /**
36   * The request processing logic, which is usually executed in thread pools provided by an
37   * {@link RpcScheduler}.  Call {@link #run()} to actually execute the contained
38   * {@link RpcServer.Call}
39   */
40  @InterfaceAudience.Private
41  public class CallRunner {
42    private Call call;
43    private RpcServerInterface rpcServer;
44    private MonitoredRPCHandler status;
45    private UserProvider userProvider;
46  
47    /**
48     * On construction, adds the size of this call to the running count of outstanding call sizes.
49     * Presumption is that we are put on a queue while we wait on an executor to run us.  During this
50     * time we occupy heap.
51     */
52    // The constructor is shutdown so only RpcServer in this class can make one of these.
53    CallRunner(final RpcServerInterface rpcServer, final Call call, UserProvider userProvider) {
54      this.call = call;
55      this.rpcServer = rpcServer;
56      // Add size of the call to queue size.
57      this.rpcServer.addCallSize(call.getSize());
58      this.status = getStatus();
59      this.userProvider = userProvider;
60    }
61  
62    public Call getCall() {
63      return call;
64    }
65  
66    /**
67     * Cleanup after ourselves... let go of references.
68     */
69    private void cleanup() {
70      this.call = null;
71      this.rpcServer = null;
72      this.status = null;
73      this.userProvider = null;
74    }
75  
76    public void run() {
77      try {
78        if (!call.connection.channel.isOpen()) {
79          if (RpcServer.LOG.isDebugEnabled()) {
80            RpcServer.LOG.debug(Thread.currentThread().getName() + ": skipped " + call);
81          }
82          return;
83        }
84        this.status.setStatus("Setting up call");
85        this.status.setConnection(call.connection.getHostAddress(), call.connection.getRemotePort());
86        if (RpcServer.LOG.isDebugEnabled()) {
87          UserGroupInformation remoteUser = call.connection.user;
88          RpcServer.LOG.debug(call.toShortString() + " executing as " +
89              ((remoteUser == null) ? "NULL principal" : remoteUser.getUserName()));
90        }
91        Throwable errorThrowable = null;
92        String error = null;
93        Pair<Message, CellScanner> resultPair = null;
94        RpcServer.CurCall.set(call);
95        TraceScope traceScope = null;
96        try {
97          if (!this.rpcServer.isStarted()) {
98            throw new ServerNotRunningYetException("Server " + rpcServer.getListenerAddress()
99                + " is not running yet");
100         }
101         if (call.tinfo != null) {
102           traceScope = Trace.startSpan(call.toTraceString(), call.tinfo);
103         }
104         RequestContext.set(userProvider.create(call.connection.user), RpcServer.getRemoteIp(),
105           call.connection.service);
106         // make the call
107         resultPair = this.rpcServer.call(call.service, call.md, call.param, call.cellScanner,
108           call.timestamp, this.status);
109       } catch (Throwable e) {
110         RpcServer.LOG.debug(Thread.currentThread().getName() + ": " + call.toShortString(), e);
111         errorThrowable = e;
112         error = StringUtils.stringifyException(e);
113         if (e instanceof Error) {
114           throw (Error)e;
115         } 
116       } finally {
117         if (traceScope != null) {
118           traceScope.close();
119         }
120         // Must always clear the request context to avoid leaking
121         // credentials between requests.
122         RequestContext.clear();
123       }
124       RpcServer.CurCall.set(null);
125       // Set the response for undelayed calls and delayed calls with
126       // undelayed responses.
127       if (!call.isDelayed() || !call.isReturnValueDelayed()) {
128         Message param = resultPair != null ? resultPair.getFirst() : null;
129         CellScanner cells = resultPair != null ? resultPair.getSecond() : null;
130         call.setResponse(param, cells, errorThrowable, error);
131       }
132       call.sendResponseIfReady();
133       this.status.markComplete("Sent response");
134       this.status.pause("Waiting for a call");
135     } catch (OutOfMemoryError e) {
136       if (this.rpcServer.getErrorHandler() != null) {
137         if (this.rpcServer.getErrorHandler().checkOOME(e)) {
138           RpcServer.LOG.info(Thread.currentThread().getName() + ": exiting on OutOfMemoryError");
139           return;
140         }
141       } else {
142         // rethrow if no handler
143         throw e;
144       }
145     } catch (ClosedChannelException cce) {
146       RpcServer.LOG.warn(Thread.currentThread().getName() + ": caught a ClosedChannelException, " +
147           "this means that the server " + rpcServer.getListenerAddress() + " was processing a " +
148           "request but the client went away. The error message was: " +
149           cce.getMessage());
150     } catch (Exception e) {
151       RpcServer.LOG.warn(Thread.currentThread().getName()
152           + ": caught: " + StringUtils.stringifyException(e));
153     } finally {
154       // regardless if succesful or not we need to reset the callQueueSize
155       this.rpcServer.addCallSize(call.getSize() * -1);
156       cleanup();
157     }
158   }
159 
160   MonitoredRPCHandler getStatus() {
161     // It is ugly the way we park status up in RpcServer.  Let it be for now.  TODO.
162     MonitoredRPCHandler status = RpcServer.MONITORED_RPC.get();
163     if (status != null) {
164       return status;
165     }
166     status = TaskMonitor.get().createRPCStatus(Thread.currentThread().getName());
167     status.pause("Waiting for a call");
168     RpcServer.MONITORED_RPC.set(status);
169     return status;
170   }
171 }