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.regionserver;
19  
20  import java.lang.reflect.Method;
21  import java.util.HashMap;
22  import java.util.Map;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.conf.Configuration;
27  import org.apache.hadoop.hbase.HConstants;
28  import org.apache.hadoop.hbase.TableName;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.ipc.PriorityFunction;
31  import org.apache.hadoop.hbase.ipc.QosPriority;
32  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
33  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
34  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.ReportRegionStateTransitionRequest;
35  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition;
36  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
37  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest;
38  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest;
39  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
40  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest;
41  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest;
42  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
43  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiRequest;
44  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateRequest;
45  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
46  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier;
47  import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader;
48  
49  import com.google.common.annotations.VisibleForTesting;
50  import com.google.protobuf.Message;
51  import com.google.protobuf.TextFormat;
52  
53  
54  /**
55   * Reads special method annotations and table names to figure a priority for use by QoS facility in
56   * ipc; e.g: rpcs to hbase:meta get priority.
57   */
58  // TODO: Remove.  This is doing way too much work just to figure a priority.  Do as Elliott
59  // suggests and just have the client specify a priority.
60  
61  //The logic for figuring out high priority RPCs is as follows:
62  //1. if the method is annotated with a QosPriority of QOS_HIGH,
63  //   that is honored
64  //2. parse out the protobuf message and see if the request is for meta
65  //   region, and if so, treat it as a high priority RPC
66  //Some optimizations for (2) are done here -
67  //Clients send the argument classname as part of making the RPC. The server
68  //decides whether to deserialize the proto argument message based on the
69  //pre-established set of argument classes (knownArgumentClasses below).
70  //This prevents the server from having to deserialize all proto argument
71  //messages prematurely.
72  //All the argument classes declare a 'getRegion' method that returns a
73  //RegionSpecifier object. Methods can be invoked on the returned object
74  //to figure out whether it is a meta region or not.
75  @InterfaceAudience.Private
76  class AnnotationReadingPriorityFunction implements PriorityFunction {
77    public static final Log LOG =
78      LogFactory.getLog(AnnotationReadingPriorityFunction.class.getName());
79  
80    /** Used to control the scan delay, currently sqrt(numNextCall * weight) */
81    public static final String SCAN_VTIME_WEIGHT_CONF_KEY = "hbase.ipc.server.scan.vtime.weight";
82  
83    private final Map<String, Integer> annotatedQos;
84    //We need to mock the regionserver instance for some unit tests (set via
85    //setRegionServer method.
86    private RSRpcServices rpcServices;
87    @SuppressWarnings("unchecked")
88    private final Class<? extends Message>[] knownArgumentClasses = new Class[]{
89        GetRegionInfoRequest.class,
90        GetStoreFileRequest.class,
91        CloseRegionRequest.class,
92        FlushRegionRequest.class,
93        SplitRegionRequest.class,
94        CompactRegionRequest.class,
95        GetRequest.class,
96        MutateRequest.class,
97        ScanRequest.class
98    };
99  
100   // Some caches for helping performance
101   private final Map<String, Class<? extends Message>> argumentToClassMap =
102     new HashMap<String, Class<? extends Message>>();
103   private final Map<String, Map<Class<? extends Message>, Method>> methodMap =
104     new HashMap<String, Map<Class<? extends Message>, Method>>();
105 
106   private final float scanVirtualTimeWeight;
107 
108   /**
109    * Calls {@link #AnnotationReadingPriorityFunction(RSRpcServices, Class)} using the result of
110    * {@code rpcServices#getClass()}
111    *
112    * @param rpcServices
113    *          The RPC server implementation
114    */
115   AnnotationReadingPriorityFunction(final RSRpcServices rpcServices) {
116     this(rpcServices, rpcServices.getClass());
117   }
118 
119   /**
120    * Constructs the priority function given the RPC server implementation and the annotations on the
121    * methods in the provided {@code clz}.
122    *
123    * @param rpcServices
124    *          The RPC server implementation
125    * @param clz
126    *          The concrete RPC server implementation's class
127    */
128   AnnotationReadingPriorityFunction(final RSRpcServices rpcServices,
129       Class<? extends RSRpcServices> clz) {
130     Map<String,Integer> qosMap = new HashMap<String,Integer>();
131     for (Method m : clz.getMethods()) {
132       QosPriority p = m.getAnnotation(QosPriority.class);
133       if (p != null) {
134         // Since we protobuf'd, and then subsequently, when we went with pb style, method names
135         // are capitalized.  This meant that this brittle compare of method names gotten by
136         // reflection no longer matched the method names coming in over pb.  TODO: Get rid of this
137         // check.  For now, workaround is to capitalize the names we got from reflection so they
138         // have chance of matching the pb ones.
139         String capitalizedMethodName = capitalize(m.getName());
140         qosMap.put(capitalizedMethodName, p.priority());
141       }
142     }
143     this.rpcServices = rpcServices;
144     this.annotatedQos = qosMap;
145     if (methodMap.get("getRegion") == null) {
146       methodMap.put("hasRegion", new HashMap<Class<? extends Message>, Method>());
147       methodMap.put("getRegion", new HashMap<Class<? extends Message>, Method>());
148     }
149     for (Class<? extends Message> cls : knownArgumentClasses) {
150       argumentToClassMap.put(cls.getName(), cls);
151       try {
152         methodMap.get("hasRegion").put(cls, cls.getDeclaredMethod("hasRegion"));
153         methodMap.get("getRegion").put(cls, cls.getDeclaredMethod("getRegion"));
154       } catch (Exception e) {
155         throw new RuntimeException(e);
156       }
157     }
158 
159     Configuration conf = rpcServices.getConfiguration();
160     scanVirtualTimeWeight = conf.getFloat(SCAN_VTIME_WEIGHT_CONF_KEY, 1.0f);
161   }
162 
163   private String capitalize(final String s) {
164     StringBuilder strBuilder = new StringBuilder(s);
165     strBuilder.setCharAt(0, Character.toUpperCase(strBuilder.charAt(0)));
166     return strBuilder.toString();
167   }
168 
169   /**
170    * Returns a 'priority' based on the request type.
171    *
172    * Currently the returned priority is used for queue selection.
173    * See the SimpleRpcScheduler as example. It maintains a queue per 'priory type'
174    * HIGH_QOS (meta requests), REPLICATION_QOS (replication requests),
175    * NORMAL_QOS (user requests).
176    */
177   @Override
178   public int getPriority(RequestHeader header, Message param) {
179     String methodName = header.getMethodName();
180     Integer priorityByAnnotation = annotatedQos.get(methodName);
181     if (priorityByAnnotation != null) {
182       return priorityByAnnotation;
183     }
184     if (param == null) {
185       return HConstants.NORMAL_QOS;
186     }
187     if (param instanceof MultiRequest) {
188       // The multi call has its priority set in the header.  All calls should work this way but
189       // only this one has been converted so far.  No priority == NORMAL_QOS.
190       return header.hasPriority()? header.getPriority(): HConstants.NORMAL_QOS;
191     }
192     String cls = param.getClass().getName();
193     Class<? extends Message> rpcArgClass = argumentToClassMap.get(cls);
194     RegionSpecifier regionSpecifier = null;
195     //check whether the request has reference to meta region or now.
196     try {
197       // Check if the param has a region specifier; the pb methods are hasRegion and getRegion if
198       // hasRegion returns true.  Not all listed methods have region specifier each time.  For
199       // example, the ScanRequest has it on setup but thereafter relies on the scannerid rather than
200       // send the region over every time.
201       Method hasRegion = methodMap.get("hasRegion").get(rpcArgClass);
202       if (hasRegion != null && (Boolean)hasRegion.invoke(param, (Object[])null)) {
203         Method getRegion = methodMap.get("getRegion").get(rpcArgClass);
204         regionSpecifier = (RegionSpecifier)getRegion.invoke(param, (Object[])null);
205         Region region = rpcServices.getRegion(regionSpecifier);
206         if (region.getRegionInfo().isSystemTable()) {
207           if (LOG.isTraceEnabled()) {
208             LOG.trace("High priority because region=" +
209               region.getRegionInfo().getRegionNameAsString());
210           }
211           return HConstants.SYSTEMTABLE_QOS;
212         }
213       }
214     } catch (Exception ex) {
215       // Not good throwing an exception out of here, a runtime anyways.  Let the query go into the
216       // server and have it throw the exception if still an issue.  Just mark it normal priority.
217       if (LOG.isTraceEnabled()) LOG.trace("Marking normal priority after getting exception=" + ex);
218       return HConstants.NORMAL_QOS;
219     }
220 
221     if (param instanceof ScanRequest) { // scanner methods...
222       ScanRequest request = (ScanRequest)param;
223       if (!request.hasScannerId()) {
224         return HConstants.NORMAL_QOS;
225       }
226       RegionScanner scanner = rpcServices.getScanner(request.getScannerId());
227       if (scanner != null && scanner.getRegionInfo().isSystemTable()) {
228         if (LOG.isTraceEnabled()) {
229           // Scanner requests are small in size so TextFormat version should not overwhelm log.
230           LOG.trace("High priority scanner request " + TextFormat.shortDebugString(request));
231         }
232         return HConstants.SYSTEMTABLE_QOS;
233       }
234     }
235 
236     // If meta is moving then all the rest of report the report state transitions will be
237     // blocked. We shouldn't be in the same queue.
238     if (param instanceof ReportRegionStateTransitionRequest) { // Regions are moving
239       ReportRegionStateTransitionRequest tRequest = (ReportRegionStateTransitionRequest) param;
240       for (RegionStateTransition transition : tRequest.getTransitionList()) {
241         if (transition.getRegionInfoList() != null) {
242           for (HBaseProtos.RegionInfo info : transition.getRegionInfoList()) {
243             TableName tn = ProtobufUtil.toTableName(info.getTableName());
244             if (tn.isSystemTable()) {
245               return HConstants.SYSTEMTABLE_QOS;
246             }
247           }
248         }
249       }
250     }
251     return HConstants.NORMAL_QOS;
252   }
253 
254   /**
255    * Based on the request content, returns the deadline of the request.
256    *
257    * @param header
258    * @param param
259    * @return Deadline of this request. 0 now, otherwise msec of 'delay'
260    */
261   @Override
262   public long getDeadline(RequestHeader header, Message param) {
263     if (param instanceof ScanRequest) {
264       ScanRequest request = (ScanRequest)param;
265       if (!request.hasScannerId()) {
266         return 0;
267       }
268 
269       // get the 'virtual time' of the scanner, and applies sqrt() to get a
270       // nice curve for the delay. More a scanner is used the less priority it gets.
271       // The weight is used to have more control on the delay.
272       long vtime = rpcServices.getScannerVirtualTime(request.getScannerId());
273       return Math.round(Math.sqrt(vtime * scanVirtualTimeWeight));
274     }
275     return 0;
276   }
277 
278   @VisibleForTesting
279   void setRegionServer(final HRegionServer hrs) {
280     this.rpcServices = hrs.getRSRpcServices();
281   }
282 }