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