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.io.InterruptedIOException;
23  import java.net.UnknownHostException;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.hbase.Cell;
30  import org.apache.hadoop.hbase.CellScanner;
31  import org.apache.hadoop.hbase.CellUtil;
32  import org.apache.hadoop.hbase.DoNotRetryIOException;
33  import org.apache.hadoop.hbase.HBaseIOException;
34  import org.apache.hadoop.hbase.HRegionInfo;
35  import org.apache.hadoop.hbase.HRegionLocation;
36  import org.apache.hadoop.hbase.NotServingRegionException;
37  import org.apache.hadoop.hbase.RegionLocations;
38  import org.apache.hadoop.hbase.RemoteExceptionHandler;
39  import org.apache.hadoop.hbase.ServerName;
40  import org.apache.hadoop.hbase.TableName;
41  import org.apache.hadoop.hbase.UnknownScannerException;
42  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
43  import org.apache.hadoop.hbase.exceptions.ScannerResetException;
44  import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
45  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
46  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
47  import org.apache.hadoop.hbase.protobuf.RequestConverter;
48  import org.apache.hadoop.hbase.protobuf.ResponseConverter;
49  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
50  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
51  import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
52  import org.apache.hadoop.ipc.RemoteException;
53  import org.apache.hadoop.net.DNS;
54  
55  import com.google.protobuf.ServiceException;
56  import com.google.protobuf.TextFormat;
57  
58  /**
59   * Scanner operations such as create, next, etc.
60   * Used by {@link ResultScanner}s made by {@link HTable}. Passed to a retrying caller such as
61   * {@link RpcRetryingCaller} so fails are retried.
62   */
63  @InterfaceAudience.Private
64  public class ScannerCallable extends RegionServerCallable<Result[]> {
65    public static final String LOG_SCANNER_LATENCY_CUTOFF
66      = "hbase.client.log.scanner.latency.cutoff";
67    public static final String LOG_SCANNER_ACTIVITY = "hbase.client.log.scanner.activity";
68  
69    public static final Log LOG = LogFactory.getLog(ScannerCallable.class);
70    protected long scannerId = -1L;
71    protected boolean instantiated = false;
72    protected boolean closed = false;
73    protected boolean renew = false;
74    private Scan scan;
75    private int caching = 1;
76    protected final ClusterConnection cConnection;
77    protected ScanMetrics scanMetrics;
78    private boolean logScannerActivity = false;
79    private int logCutOffLatency = 1000;
80    private static String myAddress;
81    protected final int id;
82    protected boolean serverHasMoreResultsContext;
83    protected boolean serverHasMoreResults;
84  
85    /**
86     * Saves whether or not the most recent response from the server was a heartbeat message.
87     * Heartbeat messages are identified by the flag {@link ScanResponse#getHeartbeatMessage()}
88     */
89    protected boolean heartbeatMessage = false;
90    static {
91      try {
92        myAddress = DNS.getDefaultHost("default", "default");
93      } catch (UnknownHostException uhe) {
94        LOG.error("cannot determine my address", uhe);
95      }
96    }
97  
98    // indicate if it is a remote server call
99    protected boolean isRegionServerRemote = true;
100   private long nextCallSeq = 0;
101   protected RpcControllerFactory controllerFactory;
102   protected PayloadCarryingRpcController controller;
103 
104   /**
105    * @param connection which connection
106    * @param tableName table callable is on
107    * @param scan the scan to execute
108    * @param scanMetrics the ScanMetrics to used, if it is null,
109    *        ScannerCallable won't collect metrics
110    * @param rpcControllerFactory factory to use when creating
111    *        {@link com.google.protobuf.RpcController}
112    */
113   public ScannerCallable (ClusterConnection connection, TableName tableName, Scan scan,
114       ScanMetrics scanMetrics, RpcControllerFactory rpcControllerFactory) {
115     this(connection, tableName, scan, scanMetrics, rpcControllerFactory, 0);
116   }
117   /**
118    *
119    * @param connection
120    * @param tableName
121    * @param scan
122    * @param scanMetrics
123    * @param id the replicaId
124    */
125   public ScannerCallable (ClusterConnection connection, TableName tableName, Scan scan,
126       ScanMetrics scanMetrics, RpcControllerFactory rpcControllerFactory, int id) {
127     super(connection, tableName, scan.getStartRow());
128     this.id = id;
129     this.cConnection = connection;
130     this.scan = scan;
131     this.scanMetrics = scanMetrics;
132     Configuration conf = connection.getConfiguration();
133     logScannerActivity = conf.getBoolean(LOG_SCANNER_ACTIVITY, false);
134     logCutOffLatency = conf.getInt(LOG_SCANNER_LATENCY_CUTOFF, 1000);
135     this.controllerFactory = rpcControllerFactory;
136   }
137 
138   PayloadCarryingRpcController getController() {
139     return controller;
140   }
141 
142   /**
143    * @param reload force reload of server location
144    * @throws IOException
145    */
146   @Override
147   public void prepare(boolean reload) throws IOException {
148     if (Thread.interrupted()) {
149       throw new InterruptedIOException();
150     }
151     RegionLocations rl = RpcRetryingCallerWithReadReplicas.getRegionLocations(!reload,
152         id, getConnection(), getTableName(), getRow());
153     location = id < rl.size() ? rl.getRegionLocation(id) : null;
154     if (location == null || location.getServerName() == null) {
155       // With this exception, there will be a retry. The location can be null for a replica
156       //  when the table is created or after a split.
157       throw new HBaseIOException("There is no location for replica id #" + id);
158     }
159     ServerName dest = location.getServerName();
160     setStub(super.getConnection().getClient(dest));
161     if (!instantiated || reload) {
162       checkIfRegionServerIsRemote();
163       instantiated = true;
164     }
165 
166     // check how often we retry.
167     // HConnectionManager will call instantiateServer with reload==true
168     // if and only if for retries.
169     if (reload && this.scanMetrics != null) {
170       this.scanMetrics.countOfRPCRetries.incrementAndGet();
171       if (isRegionServerRemote) {
172         this.scanMetrics.countOfRemoteRPCRetries.incrementAndGet();
173       }
174     }
175   }
176 
177   /**
178    * compare the local machine hostname with region server's hostname
179    * to decide if hbase client connects to a remote region server
180    */
181   protected void checkIfRegionServerIsRemote() {
182     if (getLocation().getHostname().equalsIgnoreCase(myAddress)) {
183       isRegionServerRemote = false;
184     } else {
185       isRegionServerRemote = true;
186     }
187   }
188 
189 
190   @Override
191   public Result [] call(int callTimeout) throws IOException {
192     if (Thread.interrupted()) {
193       throw new InterruptedIOException();
194     }
195     if (closed) {
196       if (scannerId != -1) {
197         close();
198       }
199     } else {
200       if (scannerId == -1L) {
201         this.scannerId = openScanner();
202       } else {
203         Result [] rrs = null;
204         ScanRequest request = null;
205         // Reset the heartbeat flag prior to each RPC in case an exception is thrown by the server
206         setHeartbeatMessage(false);
207         try {
208           incRPCcallsMetrics();
209           request = RequestConverter.buildScanRequest(scannerId, caching, false, nextCallSeq, renew);
210           ScanResponse response = null;
211           controller = controllerFactory.newController();
212           controller.setPriority(getTableName());
213           controller.setCallTimeout(callTimeout);
214           try {
215             response = getStub().scan(controller, request);
216             // Client and RS maintain a nextCallSeq number during the scan. Every next() call
217             // from client to server will increment this number in both sides. Client passes this
218             // number along with the request and at RS side both the incoming nextCallSeq and its
219             // nextCallSeq will be matched. In case of a timeout this increment at the client side
220             // should not happen. If at the server side fetching of next batch of data was over,
221             // there will be mismatch in the nextCallSeq number. Server will throw
222             // OutOfOrderScannerNextException and then client will reopen the scanner with startrow
223             // as the last successfully retrieved row.
224             // See HBASE-5974
225             nextCallSeq++;
226             long timestamp = System.currentTimeMillis();
227             setHeartbeatMessage(response.hasHeartbeatMessage() && response.getHeartbeatMessage());
228             // Results are returned via controller
229             CellScanner cellScanner = controller.cellScanner();
230             rrs = ResponseConverter.getResults(cellScanner, response);
231             if (logScannerActivity) {
232               long now = System.currentTimeMillis();
233               if (now - timestamp > logCutOffLatency) {
234                 int rows = rrs == null ? 0 : rrs.length;
235                 LOG.info("Took " + (now-timestamp) + "ms to fetch "
236                   + rows + " rows from scanner=" + scannerId);
237               }
238             }
239             // moreResults is only used for the case where a filter exhausts all elements
240             if (response.hasMoreResults() && !response.getMoreResults()) {
241               scannerId = -1L;
242               closed = true;
243               // Implied that no results were returned back, either.
244               return null;
245             }
246             // moreResultsInRegion explicitly defines when a RS may choose to terminate a batch due
247             // to size or quantity of results in the response.
248             if (response.hasMoreResultsInRegion()) {
249               // Set what the RS said
250               setHasMoreResultsContext(true);
251               setServerHasMoreResults(response.getMoreResultsInRegion());
252             } else {
253               // Server didn't respond whether it has more results or not.
254               setHasMoreResultsContext(false);
255             }
256           } catch (ServiceException se) {
257             throw ProtobufUtil.getRemoteException(se);
258           }
259           updateResultsMetrics(rrs);
260         } catch (IOException e) {
261           if (logScannerActivity) {
262             LOG.info("Got exception making request " + TextFormat.shortDebugString(request)
263               + " to " + getLocation(), e);
264           }
265           IOException ioe = e;
266           if (e instanceof RemoteException) {
267             ioe = RemoteExceptionHandler.decodeRemoteException((RemoteException)e);
268           }
269           if (logScannerActivity) {
270             if (ioe instanceof UnknownScannerException) {
271               try {
272                 HRegionLocation location =
273                     getConnection().relocateRegion(getTableName(), scan.getStartRow());
274                 LOG.info("Scanner=" + scannerId
275                   + " expired, current region location is " + location.toString());
276               } catch (Throwable t) {
277                 LOG.info("Failed to relocate region", t);
278               }
279             } else if (ioe instanceof ScannerResetException) {
280               LOG.info("Scanner=" + scannerId + " has received an exception, and the server "
281                   + "asked us to reset the scanner state.", ioe);
282             }
283           }
284           // The below convertion of exceptions into DoNotRetryExceptions is a little strange.
285           // Why not just have these exceptions implment DNRIOE you ask?  Well, usually we want
286           // ServerCallable#withRetries to just retry when it gets these exceptions.  In here in
287           // a scan when doing a next in particular, we want to break out and get the scanner to
288           // reset itself up again.  Throwing a DNRIOE is how we signal this to happen (its ugly,
289           // yeah and hard to follow and in need of a refactor).
290           if (ioe instanceof NotServingRegionException) {
291             // Throw a DNRE so that we break out of cycle of calling NSRE
292             // when what we need is to open scanner against new location.
293             // Attach NSRE to signal client that it needs to re-setup scanner.
294             if (this.scanMetrics != null) {
295               this.scanMetrics.countOfNSRE.incrementAndGet();
296             }
297             throw new DoNotRetryIOException("Resetting the scanner -- see exception cause", ioe);
298           } else if (ioe instanceof RegionServerStoppedException) {
299             // Throw a DNRE so that we break out of cycle of the retries and instead go and
300             // open scanner against new location.
301             throw new DoNotRetryIOException("Resetting the scanner -- see exception cause", ioe);
302           } else {
303             // The outer layers will retry
304             throw ioe;
305           }
306         }
307         return rrs;
308       }
309     }
310     return null;
311   }
312 
313   /**
314    * @return true when the most recent RPC response indicated that the response was a heartbeat
315    *         message. Heartbeat messages are sent back from the server when the processing of the
316    *         scan request exceeds a certain time threshold. Heartbeats allow the server to avoid
317    *         timeouts during long running scan operations.
318    */
319   protected boolean isHeartbeatMessage() {
320     return heartbeatMessage;
321   }
322 
323   protected void setHeartbeatMessage(boolean heartbeatMessage) {
324     this.heartbeatMessage = heartbeatMessage;
325   }
326 
327   private void incRPCcallsMetrics() {
328     if (this.scanMetrics == null) {
329       return;
330     }
331     this.scanMetrics.countOfRPCcalls.incrementAndGet();
332     if (isRegionServerRemote) {
333       this.scanMetrics.countOfRemoteRPCcalls.incrementAndGet();
334     }
335   }
336 
337   protected void updateResultsMetrics(Result[] rrs) {
338     if (this.scanMetrics == null || rrs == null || rrs.length == 0) {
339       return;
340     }
341     long resultSize = 0;
342     for (Result rr : rrs) {
343       for (Cell cell : rr.rawCells()) {
344         resultSize += CellUtil.estimatedSerializedSizeOf(cell);
345       }
346     }
347     this.scanMetrics.countOfBytesInResults.addAndGet(resultSize);
348     if (isRegionServerRemote) {
349       this.scanMetrics.countOfBytesInRemoteResults.addAndGet(resultSize);
350     }
351   }
352 
353   private void close() {
354     if (this.scannerId == -1L) {
355       return;
356     }
357     try {
358       incRPCcallsMetrics();
359       ScanRequest request =
360         RequestConverter.buildScanRequest(this.scannerId, 0, true);
361       try {
362         getStub().scan(null, request);
363       } catch (ServiceException se) {
364         throw ProtobufUtil.getRemoteException(se);
365       }
366     } catch (IOException e) {
367       LOG.warn("Ignore, probably already closed", e);
368     }
369     this.scannerId = -1L;
370   }
371 
372   protected long openScanner() throws IOException {
373     incRPCcallsMetrics();
374     ScanRequest request =
375       RequestConverter.buildScanRequest(
376         getLocation().getRegionInfo().getRegionName(),
377         this.scan, 0, false);
378     try {
379       ScanResponse response = getStub().scan(null, request);
380       long id = response.getScannerId();
381       if (logScannerActivity) {
382         LOG.info("Open scanner=" + id + " for scan=" + scan.toString()
383           + " on region " + getLocation().toString());
384       }
385       return id;
386     } catch (ServiceException se) {
387       throw ProtobufUtil.getRemoteException(se);
388     }
389   }
390 
391   protected Scan getScan() {
392     return scan;
393   }
394 
395   /**
396    * Call this when the next invocation of call should close the scanner
397    */
398   public void setClose() {
399     this.closed = true;
400   }
401 
402   /**
403    * Indicate whether we make a call only to renew the lease, but without affected the scanner in
404    * any other way.
405    * @param val true if only the lease should be renewed
406    */
407   public void setRenew(boolean val) {
408     this.renew = val;
409   }
410 
411   /**
412    * @return the HRegionInfo for the current region
413    */
414   @Override
415   public HRegionInfo getHRegionInfo() {
416     if (!instantiated) {
417       return null;
418     }
419     return getLocation().getRegionInfo();
420   }
421 
422   /**
423    * Get the number of rows that will be fetched on next
424    * @return the number of rows for caching
425    */
426   public int getCaching() {
427     return caching;
428   }
429 
430   @Override
431   public ClusterConnection getConnection() {
432     return cConnection;
433   }
434 
435   /**
436    * Set the number of rows that will be fetched on next
437    * @param caching the number of rows for caching
438    */
439   public void setCaching(int caching) {
440     this.caching = caching;
441   }
442 
443   public ScannerCallable getScannerCallableForReplica(int id) {
444     ScannerCallable s = new ScannerCallable(this.getConnection(), this.tableName,
445         this.getScan(), this.scanMetrics, controllerFactory, id);
446     s.setCaching(this.caching);
447     return s;
448   }
449 
450   /**
451    * Should the client attempt to fetch more results from this region
452    * @return True if the client should attempt to fetch more results, false otherwise.
453    */
454   protected boolean getServerHasMoreResults() {
455     assert serverHasMoreResultsContext;
456     return this.serverHasMoreResults;
457   }
458 
459   protected void setServerHasMoreResults(boolean serverHasMoreResults) {
460     this.serverHasMoreResults = serverHasMoreResults;
461   }
462 
463   /**
464    * Did the server respond with information about whether more results might exist.
465    * Not guaranteed to respond with older server versions
466    * @return True if the server responded with information about more results.
467    */
468   protected boolean hasMoreResultsContext() {
469     return serverHasMoreResultsContext;
470   }
471 
472   protected void setHasMoreResultsContext(boolean serverHasMoreResultsContext) {
473     this.serverHasMoreResultsContext = serverHasMoreResultsContext;
474   }
475 }