001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import static org.apache.hadoop.hbase.HConstants.EMPTY_END_ROW;
021import static org.apache.hadoop.hbase.HConstants.EMPTY_START_ROW;
022import static org.apache.hadoop.hbase.client.ConnectionUtils.*;
023
024import java.io.IOException;
025import java.util.concurrent.CompletableFuture;
026import java.util.concurrent.TimeUnit;
027
028import org.apache.hadoop.hbase.HRegionLocation;
029import org.apache.hadoop.hbase.TableName;
030import org.apache.yetus.audience.InterfaceAudience;
031import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
032import org.apache.hadoop.hbase.ipc.HBaseRpcController;
033import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
034import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ClientService;
035import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ClientService.Interface;
036import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ScanRequest;
037import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ScanResponse;
038
039/**
040 * The asynchronous client scanner implementation.
041 * <p>
042 * Here we will call OpenScanner first and use the returned scannerId to create a
043 * {@link AsyncScanSingleRegionRpcRetryingCaller} to do the real scan operation. The return value of
044 * {@link AsyncScanSingleRegionRpcRetryingCaller} will tell us whether open a new scanner or finish
045 * scan.
046 */
047@InterfaceAudience.Private
048class AsyncClientScanner {
049
050  // We will use this scan object during the whole scan operation. The
051  // AsyncScanSingleRegionRpcRetryingCaller will modify this scan object directly.
052  private final Scan scan;
053
054  private final ScanMetrics scanMetrics;
055
056  private final AdvancedScanResultConsumer consumer;
057
058  private final TableName tableName;
059
060  private final AsyncConnectionImpl conn;
061
062  private final long pauseNs;
063
064  private final int maxAttempts;
065
066  private final long scanTimeoutNs;
067
068  private final long rpcTimeoutNs;
069
070  private final int startLogErrorsCnt;
071
072  private final ScanResultCache resultCache;
073
074  public AsyncClientScanner(Scan scan, AdvancedScanResultConsumer consumer, TableName tableName,
075      AsyncConnectionImpl conn, long pauseNs, int maxAttempts, long scanTimeoutNs,
076      long rpcTimeoutNs, int startLogErrorsCnt) {
077    if (scan.getStartRow() == null) {
078      scan.withStartRow(EMPTY_START_ROW, scan.includeStartRow());
079    }
080    if (scan.getStopRow() == null) {
081      scan.withStopRow(EMPTY_END_ROW, scan.includeStopRow());
082    }
083    this.scan = scan;
084    this.consumer = consumer;
085    this.tableName = tableName;
086    this.conn = conn;
087    this.pauseNs = pauseNs;
088    this.maxAttempts = maxAttempts;
089    this.scanTimeoutNs = scanTimeoutNs;
090    this.rpcTimeoutNs = rpcTimeoutNs;
091    this.startLogErrorsCnt = startLogErrorsCnt;
092    this.resultCache = createScanResultCache(scan);
093    if (scan.isScanMetricsEnabled()) {
094      this.scanMetrics = new ScanMetrics();
095      consumer.onScanMetricsCreated(scanMetrics);
096    } else {
097      this.scanMetrics = null;
098    }
099  }
100
101  private static final class OpenScannerResponse {
102
103    public final HRegionLocation loc;
104
105    public final boolean isRegionServerRemote;
106
107    public final ClientService.Interface stub;
108
109    public final HBaseRpcController controller;
110
111    public final ScanResponse resp;
112
113    public OpenScannerResponse(HRegionLocation loc, boolean isRegionServerRemote, Interface stub,
114        HBaseRpcController controller, ScanResponse resp) {
115      this.loc = loc;
116      this.isRegionServerRemote = isRegionServerRemote;
117      this.stub = stub;
118      this.controller = controller;
119      this.resp = resp;
120    }
121  }
122
123  private int openScannerTries;
124
125  private CompletableFuture<OpenScannerResponse> callOpenScanner(HBaseRpcController controller,
126      HRegionLocation loc, ClientService.Interface stub) {
127    boolean isRegionServerRemote = isRemote(loc.getHostname());
128    incRPCCallsMetrics(scanMetrics, isRegionServerRemote);
129    if (openScannerTries > 1) {
130      incRPCRetriesMetrics(scanMetrics, isRegionServerRemote);
131    }
132    openScannerTries++;
133    CompletableFuture<OpenScannerResponse> future = new CompletableFuture<>();
134    try {
135      ScanRequest request = RequestConverter.buildScanRequest(loc.getRegionInfo().getRegionName(),
136        scan, scan.getCaching(), false);
137      stub.scan(controller, request, resp -> {
138        if (controller.failed()) {
139          future.completeExceptionally(controller.getFailed());
140          return;
141        }
142        future.complete(new OpenScannerResponse(loc, isRegionServerRemote, stub, controller, resp));
143      });
144    } catch (IOException e) {
145      future.completeExceptionally(e);
146    }
147    return future;
148  }
149
150  private void startScan(OpenScannerResponse resp) {
151    conn.callerFactory.scanSingleRegion().id(resp.resp.getScannerId()).location(resp.loc)
152        .remote(resp.isRegionServerRemote)
153        .scannerLeaseTimeoutPeriod(resp.resp.getTtl(), TimeUnit.MILLISECONDS).stub(resp.stub)
154        .setScan(scan).metrics(scanMetrics).consumer(consumer).resultCache(resultCache)
155        .rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
156        .scanTimeout(scanTimeoutNs, TimeUnit.NANOSECONDS).pause(pauseNs, TimeUnit.NANOSECONDS)
157        .maxAttempts(maxAttempts).startLogErrorsCnt(startLogErrorsCnt)
158        .start(resp.controller, resp.resp).whenComplete((hasMore, error) -> {
159          if (error != null) {
160            consumer.onError(error);
161            return;
162          }
163          if (hasMore) {
164            openScanner();
165          } else {
166            consumer.onComplete();
167          }
168        });
169  }
170
171  private void openScanner() {
172    incRegionCountMetrics(scanMetrics);
173    openScannerTries = 1;
174    conn.callerFactory.<OpenScannerResponse> single().table(tableName).row(scan.getStartRow())
175        .locateType(getLocateType(scan)).rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
176        .operationTimeout(scanTimeoutNs, TimeUnit.NANOSECONDS).pause(pauseNs, TimeUnit.NANOSECONDS)
177        .maxAttempts(maxAttempts).startLogErrorsCnt(startLogErrorsCnt).action(this::callOpenScanner)
178        .call().whenComplete((resp, error) -> {
179          if (error != null) {
180            consumer.onError(error);
181            return;
182          }
183          startScan(resp);
184        });
185  }
186
187  public void start() {
188    openScanner();
189  }
190}