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.hbase.HConstants;
27  import org.apache.hadoop.hbase.NotServingRegionException;
28  import org.apache.hadoop.hbase.ipc.PriorityFunction;
29  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
30  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest;
31  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest;
32  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
33  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest;
34  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest;
35  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
36  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiRequest;
37  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateRequest;
38  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
39  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier;
40  import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader;
41  import org.apache.hadoop.hbase.regionserver.HRegionServer.QosPriority;
42  
43  import com.google.common.annotations.VisibleForTesting;
44  import com.google.protobuf.Message;
45  import com.google.protobuf.TextFormat;
46  
47  
48  /**
49   * Reads special method annotations and table names to figure a priority for use by QoS facility in
50   * ipc; e.g: rpcs to hbase:meta get priority.
51   */
52  // TODO: Remove.  This is doing way too much work just to figure a priority.  Do as Elliott
53  // suggests and just have the client specify a priority.
54  
55  //The logic for figuring out high priority RPCs is as follows:
56  //1. if the method is annotated with a QosPriority of QOS_HIGH,
57  //   that is honored
58  //2. parse out the protobuf message and see if the request is for meta
59  //   region, and if so, treat it as a high priority RPC
60  //Some optimizations for (2) are done here -
61  //Clients send the argument classname as part of making the RPC. The server
62  //decides whether to deserialize the proto argument message based on the
63  //pre-established set of argument classes (knownArgumentClasses below).
64  //This prevents the server from having to deserialize all proto argument
65  //messages prematurely.
66  //All the argument classes declare a 'getRegion' method that returns a
67  //RegionSpecifier object. Methods can be invoked on the returned object
68  //to figure out whether it is a meta region or not.
69  class AnnotationReadingPriorityFunction implements PriorityFunction {
70    public static final Log LOG =
71      LogFactory.getLog(AnnotationReadingPriorityFunction.class.getName());
72    private final Map<String, Integer> annotatedQos;
73    //We need to mock the regionserver instance for some unit tests (set via
74    //setRegionServer method.
75    private HRegionServer hRegionServer;
76    @SuppressWarnings("unchecked")
77    private final Class<? extends Message>[] knownArgumentClasses = new Class[]{
78        GetRegionInfoRequest.class,
79        GetStoreFileRequest.class,
80        CloseRegionRequest.class,
81        FlushRegionRequest.class,
82        SplitRegionRequest.class,
83        CompactRegionRequest.class,
84        GetRequest.class,
85        MutateRequest.class,
86        ScanRequest.class
87    };
88  
89    // Some caches for helping performance
90    private final Map<String, Class<? extends Message>> argumentToClassMap =
91      new HashMap<String, Class<? extends Message>>();
92    private final Map<String, Map<Class<? extends Message>, Method>> methodMap =
93      new HashMap<String, Map<Class<? extends Message>, Method>>();
94  
95    AnnotationReadingPriorityFunction(final HRegionServer hrs) {
96      this.hRegionServer = hrs;
97      Map<String, Integer> qosMap = new HashMap<String, Integer>();
98      for (Method m : HRegionServer.class.getMethods()) {
99        QosPriority p = m.getAnnotation(QosPriority.class);
100       if (p != null) {
101         // Since we protobuf'd, and then subsequently, when we went with pb style, method names
102         // are capitalized.  This meant that this brittle compare of method names gotten by
103         // reflection no longer matched the method names coming in over pb.  TODO: Get rid of this
104         // check.  For now, workaround is to capitalize the names we got from reflection so they
105         // have chance of matching the pb ones.
106         String capitalizedMethodName = capitalize(m.getName());
107         qosMap.put(capitalizedMethodName, p.priority());
108       }
109     }
110     this.annotatedQos = qosMap;
111     if (methodMap.get("getRegion") == null) {
112       methodMap.put("hasRegion", new HashMap<Class<? extends Message>, Method>());
113       methodMap.put("getRegion", new HashMap<Class<? extends Message>, Method>());
114     }
115     for (Class<? extends Message> cls : knownArgumentClasses) {
116       argumentToClassMap.put(cls.getName(), cls);
117       try {
118         methodMap.get("hasRegion").put(cls, cls.getDeclaredMethod("hasRegion"));
119         methodMap.get("getRegion").put(cls, cls.getDeclaredMethod("getRegion"));
120       } catch (Exception e) {
121         throw new RuntimeException(e);
122       }
123     }
124   }
125 
126   private String capitalize(final String s) {
127     StringBuilder strBuilder = new StringBuilder(s);
128     strBuilder.setCharAt(0, Character.toUpperCase(strBuilder.charAt(0)));
129     return strBuilder.toString();
130   }
131 
132   public boolean isMetaRegion(byte[] regionName) {
133     HRegion region;
134     try {
135       region = hRegionServer.getRegion(regionName);
136     } catch (NotServingRegionException ignored) {
137       return false;
138     }
139     return region.getRegionInfo().isMetaTable();
140   }
141 
142   @Override
143   public int getPriority(RequestHeader header, Message param) {
144     String methodName = header.getMethodName();
145     Integer priorityByAnnotation = annotatedQos.get(methodName);
146     if (priorityByAnnotation != null) {
147       return priorityByAnnotation;
148     }
149     if (param == null) {
150       return HConstants.NORMAL_QOS;
151     }
152     if (methodName.equalsIgnoreCase("multi") && param instanceof MultiRequest) {
153       // The multi call has its priority set in the header.  All calls should work this way but
154       // only this one has been converted so far.  No priority == NORMAL_QOS.
155       return header.hasPriority()? header.getPriority(): HConstants.NORMAL_QOS;
156     }
157     String cls = param.getClass().getName();
158     Class<? extends Message> rpcArgClass = argumentToClassMap.get(cls);
159     RegionSpecifier regionSpecifier = null;
160     //check whether the request has reference to meta region or now.
161     try {
162       // Check if the param has a region specifier; the pb methods are hasRegion and getRegion if
163       // hasRegion returns true.  Not all listed methods have region specifier each time.  For
164       // example, the ScanRequest has it on setup but thereafter relies on the scannerid rather than
165       // send the region over every time.
166       Method hasRegion = methodMap.get("hasRegion").get(rpcArgClass);
167       if (hasRegion != null && (Boolean)hasRegion.invoke(param, (Object[])null)) {
168         Method getRegion = methodMap.get("getRegion").get(rpcArgClass);
169         regionSpecifier = (RegionSpecifier)getRegion.invoke(param, (Object[])null);
170         HRegion region = hRegionServer.getRegion(regionSpecifier);
171         if (region.getRegionInfo().isMetaTable()) {
172           if (LOG.isTraceEnabled()) {
173             LOG.trace("High priority because region=" + region.getRegionNameAsString());
174           }
175           return HConstants.HIGH_QOS;
176         }
177       }
178     } catch (Exception ex) {
179       // Not good throwing an exception out of here, a runtime anyways.  Let the query go into the
180       // server and have it throw the exception if still an issue.  Just mark it normal priority.
181       if (LOG.isTraceEnabled()) LOG.trace("Marking normal priority after getting exception=" + ex);
182       return HConstants.NORMAL_QOS;
183     }
184 
185     if (methodName.equalsIgnoreCase("scan")) { // scanner methods...
186       ScanRequest request = (ScanRequest)param;
187       if (!request.hasScannerId()) {
188         return HConstants.NORMAL_QOS;
189       }
190       RegionScanner scanner = hRegionServer.getScanner(request.getScannerId());
191       if (scanner != null && scanner.getRegionInfo().isMetaRegion()) {
192         if (LOG.isTraceEnabled()) {
193           // Scanner requests are small in size so TextFormat version should not overwhelm log.
194           LOG.trace("High priority scanner request " + TextFormat.shortDebugString(request));
195         }
196         return HConstants.HIGH_QOS;
197       }
198     }
199     return HConstants.NORMAL_QOS;
200   }
201 
202   @VisibleForTesting
203   void setRegionServer(final HRegionServer hrs) {
204     this.hRegionServer = hrs;
205   }
206 }