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  
19  package org.apache.hadoop.hbase.client;
20  
21  import java.io.IOException;
22  import java.net.UnknownHostException;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.conf.Configuration;
28  import org.apache.hadoop.hbase.Cell;
29  import org.apache.hadoop.hbase.CellScanner;
30  import org.apache.hadoop.hbase.DoNotRetryIOException;
31  import org.apache.hadoop.hbase.HRegionInfo;
32  import org.apache.hadoop.hbase.HRegionLocation;
33  import org.apache.hadoop.hbase.KeyValueUtil;
34  import org.apache.hadoop.hbase.NotServingRegionException;
35  import org.apache.hadoop.hbase.RemoteExceptionHandler;
36  import org.apache.hadoop.hbase.TableName;
37  import org.apache.hadoop.hbase.UnknownScannerException;
38  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
39  import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
40  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
41  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
42  import org.apache.hadoop.hbase.protobuf.RequestConverter;
43  import org.apache.hadoop.hbase.protobuf.ResponseConverter;
44  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
45  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
46  import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
47  import org.apache.hadoop.ipc.RemoteException;
48  import org.apache.hadoop.net.DNS;
49  
50  import com.google.protobuf.RpcController;
51  import com.google.protobuf.ServiceException;
52  import com.google.protobuf.TextFormat;
53  
54  /**
55   * Scanner operations such as create, next, etc.
56   * Used by {@link ResultScanner}s made by {@link HTable}. Passed to a retrying caller such as
57   * {@link RpcRetryingCaller} so fails are retried.
58   */
59  @InterfaceAudience.Private
60  public class ScannerCallable extends RegionServerCallable<Result[]> {
61    public static final String LOG_SCANNER_LATENCY_CUTOFF
62      = "hbase.client.log.scanner.latency.cutoff";
63    public static final String LOG_SCANNER_ACTIVITY = "hbase.client.log.scanner.activity";
64  
65    public static final Log LOG = LogFactory.getLog(ScannerCallable.class);
66    private long scannerId = -1L;
67    protected boolean instantiated = false;
68    private boolean closed = false;
69    private Scan scan;
70    private int caching = 1;
71    protected ScanMetrics scanMetrics;
72    private boolean logScannerActivity = false;
73    private int logCutOffLatency = 1000;
74    private static String myAddress;
75    static {
76      try {
77        myAddress = DNS.getDefaultHost("default", "default");
78      } catch (UnknownHostException uhe) {
79        LOG.error("cannot determine my address", uhe);
80      }
81    }
82  
83    // indicate if it is a remote server call
84    protected boolean isRegionServerRemote = true;
85    private long nextCallSeq = 0;
86    protected final PayloadCarryingRpcController controller;
87    
88    /**
89     * @param connection which connection
90     * @param tableName table callable is on
91     * @param scan the scan to execute
92     * @param scanMetrics the ScanMetrics to used, if it is null, ScannerCallable won't collect
93     *          metrics
94     * @param controller to use when writing the rpc
95     */
96    public ScannerCallable (HConnection connection, TableName tableName, Scan scan,
97        ScanMetrics scanMetrics, PayloadCarryingRpcController controller) {
98      super(connection, tableName, scan.getStartRow());
99      this.scan = scan;
100     this.scanMetrics = scanMetrics;
101     Configuration conf = connection.getConfiguration();
102     logScannerActivity = conf.getBoolean(LOG_SCANNER_ACTIVITY, false);
103     logCutOffLatency = conf.getInt(LOG_SCANNER_LATENCY_CUTOFF, 1000);
104     this.controller = controller;
105   }
106 
107   /**
108    * @deprecated Use {@link #ScannerCallable(HConnection, TableName, Scan, 
109    *  ScanMetrics, PayloadCarryingRpcController)}
110    */
111   @Deprecated
112   public ScannerCallable (HConnection connection, final byte [] tableName, Scan scan,
113       ScanMetrics scanMetrics) {
114     this(connection, TableName.valueOf(tableName), scan, scanMetrics, RpcControllerFactory
115         .instantiate(connection.getConfiguration()).newController());
116   }
117 
118   /**
119    * @param reload force reload of server location
120    * @throws IOException
121    */
122   @Override
123   public void prepare(boolean reload) throws IOException {
124     if (!instantiated || reload) {
125       super.prepare(reload);
126       checkIfRegionServerIsRemote();
127       instantiated = true;
128     }
129 
130     // check how often we retry.
131     // HConnectionManager will call instantiateServer with reload==true
132     // if and only if for retries.
133     if (reload && this.scanMetrics != null) {
134       this.scanMetrics.countOfRPCRetries.incrementAndGet();
135       if (isRegionServerRemote) {
136         this.scanMetrics.countOfRemoteRPCRetries.incrementAndGet();
137       }
138     }
139   }
140 
141   /**
142    * compare the local machine hostname with region server's hostname
143    * to decide if hbase client connects to a remote region server
144    */
145   protected void checkIfRegionServerIsRemote() {
146     if (getLocation().getHostname().equalsIgnoreCase(myAddress)) {
147       isRegionServerRemote = false;
148     } else {
149       isRegionServerRemote = true;
150     }
151   }
152 
153   /**
154    * @see java.util.concurrent.Callable#call()
155    */
156   @SuppressWarnings("deprecation")
157   public Result [] call() throws IOException {
158     if (closed) {
159       if (scannerId != -1) {
160         close();
161       }
162     } else {
163       if (scannerId == -1L) {
164         this.scannerId = openScanner();
165       } else {
166         Result [] rrs = null;
167         ScanRequest request = null;
168         try {
169           incRPCcallsMetrics();
170           request = RequestConverter.buildScanRequest(scannerId, caching, false, nextCallSeq);
171           ScanResponse response = null;
172           try {
173             controller.setPriority(getTableName());
174             response = getStub().scan(controller, request);
175             // Client and RS maintain a nextCallSeq number during the scan. Every next() call
176             // from client to server will increment this number in both sides. Client passes this
177             // number along with the request and at RS side both the incoming nextCallSeq and its
178             // nextCallSeq will be matched. In case of a timeout this increment at the client side
179             // should not happen. If at the server side fetching of next batch of data was over,
180             // there will be mismatch in the nextCallSeq number. Server will throw
181             // OutOfOrderScannerNextException and then client will reopen the scanner with startrow
182             // as the last successfully retrieved row.
183             // See HBASE-5974
184             nextCallSeq++;
185             long timestamp = System.currentTimeMillis();
186             // Results are returned via controller
187             CellScanner cellScanner = controller.cellScanner();
188             rrs = ResponseConverter.getResults(cellScanner, response);
189             if (logScannerActivity) {
190               long now = System.currentTimeMillis();
191               if (now - timestamp > logCutOffLatency) {
192                 int rows = rrs == null ? 0 : rrs.length;
193                 LOG.info("Took " + (now-timestamp) + "ms to fetch "
194                   + rows + " rows from scanner=" + scannerId);
195               }
196             }
197             if (response.hasMoreResults()
198                 && !response.getMoreResults()) {
199               scannerId = -1L;
200               closed = true;
201               return null;
202             }
203           } catch (ServiceException se) {
204             throw ProtobufUtil.getRemoteException(se);
205           }
206           updateResultsMetrics(rrs);
207         } catch (IOException e) {
208           if (logScannerActivity) {
209             LOG.info("Got exception making request " + TextFormat.shortDebugString(request)
210               + " to " + getLocation(), e);
211           }
212           IOException ioe = e;
213           if (e instanceof RemoteException) {
214             ioe = RemoteExceptionHandler.decodeRemoteException((RemoteException)e);
215           }
216           if (logScannerActivity && (ioe instanceof UnknownScannerException)) {
217             try {
218               HRegionLocation location =
219                 getConnection().relocateRegion(getTableName(), scan.getStartRow());
220               LOG.info("Scanner=" + scannerId
221                 + " expired, current region location is " + location.toString());
222             } catch (Throwable t) {
223               LOG.info("Failed to relocate region", t);
224             }
225           }
226           // The below convertion of exceptions into DoNotRetryExceptions is a little strange.
227           // Why not just have these exceptions implment DNRIOE you ask?  Well, usually we want
228           // ServerCallable#withRetries to just retry when it gets these exceptions.  In here in
229           // a scan when doing a next in particular, we want to break out and get the scanner to
230           // reset itself up again.  Throwing a DNRIOE is how we signal this to happen (its ugly,
231           // yeah and hard to follow and in need of a refactor).
232           if (ioe instanceof NotServingRegionException) {
233             // Throw a DNRE so that we break out of cycle of calling NSRE
234             // when what we need is to open scanner against new location.
235             // Attach NSRE to signal client that it needs to re-setup scanner.
236             if (this.scanMetrics != null) {
237               this.scanMetrics.countOfNSRE.incrementAndGet();
238             }
239             throw new DoNotRetryIOException("Resetting the scanner -- see exception cause", ioe);
240           } else if (ioe instanceof RegionServerStoppedException) {
241             // Throw a DNRE so that we break out of cycle of the retries and instead go and
242             // open scanner against new location.
243             throw new DoNotRetryIOException("Resetting the scanner -- see exception cause", ioe);
244           } else {
245             // The outer layers will retry
246             throw ioe;
247           }
248         }
249         return rrs;
250       }
251     }
252     return null;
253   }
254 
255   private void incRPCcallsMetrics() {
256     if (this.scanMetrics == null) {
257       return;
258     }
259     this.scanMetrics.countOfRPCcalls.incrementAndGet();
260     if (isRegionServerRemote) {
261       this.scanMetrics.countOfRemoteRPCcalls.incrementAndGet();
262     }
263   }
264 
265   private void updateResultsMetrics(Result[] rrs) {
266     if (this.scanMetrics == null || rrs == null || rrs.length == 0) {
267       return;
268     }
269     long resultSize = 0;
270     for (Result rr : rrs) {
271       for (Cell kv : rr.rawCells()) {
272         // TODO add getLength to Cell/use CellUtil#estimatedSizeOf
273         resultSize += KeyValueUtil.ensureKeyValue(kv).getLength();
274       }
275     }
276     this.scanMetrics.countOfBytesInResults.addAndGet(resultSize);
277     if (isRegionServerRemote) {
278       this.scanMetrics.countOfBytesInRemoteResults.addAndGet(resultSize);
279     }
280   }
281 
282   private void close() {
283     if (this.scannerId == -1L) {
284       return;
285     }
286     try {
287       incRPCcallsMetrics();
288       ScanRequest request =
289         RequestConverter.buildScanRequest(this.scannerId, 0, true);
290       try {
291         getStub().scan(null, request);
292       } catch (ServiceException se) {
293         throw ProtobufUtil.getRemoteException(se);
294       }
295     } catch (IOException e) {
296       LOG.warn("Ignore, probably already closed", e);
297     }
298     this.scannerId = -1L;
299   }
300 
301   protected long openScanner() throws IOException {
302     incRPCcallsMetrics();
303     ScanRequest request =
304       RequestConverter.buildScanRequest(
305         getLocation().getRegionInfo().getRegionName(),
306         this.scan, 0, false);
307     try {
308       ScanResponse response = getStub().scan(null, request);
309       long id = response.getScannerId();
310       if (logScannerActivity) {
311         LOG.info("Open scanner=" + id + " for scan=" + scan.toString()
312           + " on region " + getLocation().toString());
313       }
314       return id;
315     } catch (ServiceException se) {
316       throw ProtobufUtil.getRemoteException(se);
317     }
318   }
319 
320   protected Scan getScan() {
321     return scan;
322   }
323 
324   /**
325    * Call this when the next invocation of call should close the scanner
326    */
327   public void setClose() {
328     this.closed = true;
329   }
330 
331   /**
332    * @return the HRegionInfo for the current region
333    */
334   public HRegionInfo getHRegionInfo() {
335     if (!instantiated) {
336       return null;
337     }
338     return getLocation().getRegionInfo();
339   }
340 
341   /**
342    * Get the number of rows that will be fetched on next
343    * @return the number of rows for caching
344    */
345   public int getCaching() {
346     return caching;
347   }
348 
349   /**
350    * Set the number of rows that will be fetched on next
351    * @param caching the number of rows for caching
352    */
353   public void setCaching(int caching) {
354     this.caching = caching;
355   }
356 }