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.client;
19  
20  import static org.apache.hadoop.hbase.client.ConnectionUtils.filterCells;
21  
22  import java.io.IOException;
23  import java.util.ArrayDeque;
24  import java.util.ArrayList;
25  import java.util.Deque;
26  import java.util.List;
27  
28  import org.apache.hadoop.hbase.Cell;
29  import org.apache.hadoop.hbase.CellUtil;
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.hbase.util.Bytes;
32  
33  /**
34   * A scan result cache for batched scan, i.e,
35   * {@code scan.getBatch() > 0 && !scan.getAllowPartialResults()}.
36   * <p>
37   * If user setBatch(5) and rpc returns 3+5+5+5+3 cells, we should return 5+5+5+5+1 to user. setBatch
38   * doesn't mean setAllowPartialResult(true).
39   */
40  @InterfaceAudience.Private
41  public class BatchScanResultCache implements ScanResultCache {
42  
43    private final int batch;
44  
45    // used to filter out the cells that already returned to user as we always start from the
46    // beginning of a row when retry.
47    private Cell lastCell;
48  
49    private boolean lastResultPartial;
50  
51    private final Deque<Result> partialResults = new ArrayDeque<>();
52  
53    private int numCellsOfPartialResults;
54  
55    private int numberOfCompleteRows;
56  
57    public BatchScanResultCache(int batch) {
58      this.batch = batch;
59    }
60  
61    private void recordLastResult(Result result) {
62      lastCell = result.rawCells()[result.rawCells().length - 1];
63      lastResultPartial = result.mayHaveMoreCellsInRow();
64    }
65  
66    private Result createCompletedResult() throws IOException {
67      numberOfCompleteRows++;
68      Result result = Result.createCompleteResult(partialResults);
69      partialResults.clear();
70      numCellsOfPartialResults = 0;
71      return result;
72    }
73  
74    // Add new result to the partial list and return a batched Result if caching size exceed batching
75    // limit. As the RS will also respect the scan.getBatch, we can make sure that we will get only
76    // one Result back at most(or null, which means we do not have enough cells).
77    private Result regroupResults(Result result) {
78      partialResults.addLast(result);
79      numCellsOfPartialResults += result.size();
80      if (numCellsOfPartialResults < batch) {
81        return null;
82      }
83      Cell[] cells = new Cell[batch];
84      int cellCount = 0;
85      boolean stale = false;
86      for (;;) {
87        Result r = partialResults.pollFirst();
88        stale = stale || r.isStale();
89        int newCellCount = cellCount + r.size();
90        if (newCellCount > batch) {
91          // We have more cells than expected, so split the current result
92          int len = batch - cellCount;
93          System.arraycopy(r.rawCells(), 0, cells, cellCount, len);
94          Cell[] remainingCells = new Cell[r.size() - len];
95          System.arraycopy(r.rawCells(), len, remainingCells, 0, r.size() - len);
96          partialResults.addFirst(
97            Result.create(remainingCells, r.getExists(), r.isStale(), r.mayHaveMoreCellsInRow()));
98          break;
99        }
100       System.arraycopy(r.rawCells(), 0, cells, cellCount, r.size());
101       if (newCellCount == batch) {
102         break;
103       }
104       cellCount = newCellCount;
105     }
106     numCellsOfPartialResults -= batch;
107     return Result.create(cells, null, stale,
108       result.mayHaveMoreCellsInRow() || !partialResults.isEmpty());
109   }
110 
111   @Override
112   public Result[] addAndGet(Result[] results, boolean isHeartbeatMessage) throws IOException {
113     if (results.length == 0) {
114       if (!isHeartbeatMessage) {
115         if (!partialResults.isEmpty()) {
116           return new Result[] { createCompletedResult() };
117         }
118         if (lastResultPartial) {
119           // An empty non heartbeat result indicate that there must be a row change. So if the
120           // lastResultPartial is true then we need to increase numberOfCompleteRows.
121           numberOfCompleteRows++;
122         }
123       }
124       return EMPTY_RESULT_ARRAY;
125     }
126     List<Result> regroupedResults = new ArrayList<>();
127     for (Result result : results) {
128       result = filterCells(result, lastCell);
129       if (result == null) {
130         continue;
131       }
132       if (!partialResults.isEmpty()) {
133         if (!Bytes.equals(partialResults.peek().getRow(), result.getRow())) {
134           // there is a row change
135           regroupedResults.add(createCompletedResult());
136         }
137       } else if (lastResultPartial && !CellUtil.matchingRow(lastCell, result.getRow())) {
138         // As for batched scan we may return partial results to user if we reach the batch limit, so
139         // here we need to use lastCell to determine if there is row change and increase
140         // numberOfCompleteRows.
141         numberOfCompleteRows++;
142       }
143       // check if we have a row change
144       if (!partialResults.isEmpty() &&
145           !Bytes.equals(partialResults.peek().getRow(), result.getRow())) {
146         regroupedResults.add(createCompletedResult());
147       }
148       Result regroupedResult = regroupResults(result);
149       if (regroupedResult != null) {
150         if (!regroupedResult.mayHaveMoreCellsInRow()) {
151           numberOfCompleteRows++;
152         }
153         regroupedResults.add(regroupedResult);
154         // only update last cell when we actually return it to user.
155         recordLastResult(regroupedResult);
156       }
157       if (!result.mayHaveMoreCellsInRow() && !partialResults.isEmpty()) {
158         // We are done for this row
159         regroupedResults.add(createCompletedResult());
160       }
161     }
162     return regroupedResults.toArray(new Result[0]);
163   }
164 
165   @Override
166   public void clear() {
167     partialResults.clear();
168     numCellsOfPartialResults = 0;
169   }
170 
171   @Override
172   public int numberOfCompleteRows() {
173     return numberOfCompleteRows;
174   }
175 }