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