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.HConstants.EMPTY_END_ROW;
21  import static org.apache.hadoop.hbase.HConstants.EMPTY_START_ROW;
22  
23  import com.google.common.annotations.VisibleForTesting;
24  
25  import java.io.IOException;
26  import java.util.Arrays;
27  import java.util.Comparator;
28  import java.util.concurrent.ExecutorService;
29  import java.util.concurrent.ThreadLocalRandom;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.Cell;
34  import org.apache.hadoop.hbase.CellComparator;
35  import org.apache.hadoop.hbase.CellUtil;
36  import org.apache.hadoop.hbase.HConstants;
37  import org.apache.hadoop.hbase.HRegionInfo;
38  import org.apache.hadoop.hbase.ServerName;
39  import org.apache.hadoop.hbase.TableName;
40  import org.apache.hadoop.hbase.classification.InterfaceAudience;
41  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
42  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;
43  import org.apache.hadoop.hbase.security.User;
44  import org.apache.hadoop.hbase.security.UserProvider;
45  import org.apache.hadoop.hbase.util.Bytes;
46  
47  /**
48   * Utility used by client connections.
49   */
50  @InterfaceAudience.Private
51  public class ConnectionUtils {
52  
53    /**
54     * Calculate pause time.
55     * Built on {@link HConstants#RETRY_BACKOFF}.
56     * @param pause
57     * @param tries
58     * @return How long to wait after <code>tries</code> retries
59     */
60    public static long getPauseTime(final long pause, final int tries) {
61      int ntries = tries;
62      if (ntries >= HConstants.RETRY_BACKOFF.length) {
63        ntries = HConstants.RETRY_BACKOFF.length - 1;
64      }
65      if (ntries < 0) {
66        ntries = 0;
67      }
68  
69      long normalPause = pause * HConstants.RETRY_BACKOFF[ntries];
70      // 1% possible jitter
71      long jitter = (long) (normalPause * ThreadLocalRandom.current().nextFloat() * 0.01f);
72      return normalPause + jitter;
73    }
74  
75  
76    /**
77     * @param conn The connection for which to replace the generator.
78     * @param cnm Replaces the nonce generator used, for testing.
79     * @return old nonce generator.
80     */
81    public static NonceGenerator injectNonceGeneratorForTesting(
82        ClusterConnection conn, NonceGenerator cnm) {
83      return ConnectionManager.injectNonceGeneratorForTesting(conn, cnm);
84    }
85  
86    /**
87     * Changes the configuration to set the number of retries needed when using HConnection
88     * internally, e.g. for  updating catalog tables, etc.
89     * Call this method before we create any Connections.
90     * @param c The Configuration instance to set the retries into.
91     * @param log Used to log what we set in here.
92     */
93    public static void setServerSideHConnectionRetriesConfig(
94        final Configuration c, final String sn, final Log log) {
95      // TODO: Fix this. Not all connections from server side should have 10 times the retries.
96      int hcRetries = c.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
97        HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
98      // Go big.  Multiply by 10.  If we can't get to meta after this many retries
99      // then something seriously wrong.
100     int serversideMultiplier = c.getInt("hbase.client.serverside.retries.multiplier", 10);
101     int retries = hcRetries * serversideMultiplier;
102     c.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, retries);
103     log.info(sn + " server-side HConnection retries=" + retries);
104   }
105 
106   /**
107    * Adapt a HConnection so that it can bypass the RPC layer (serialization,
108    * deserialization, networking, etc..) -- i.e. short-circuit -- when talking to a local server.
109    * @param conn the connection to adapt
110    * @param serverName the local server name
111    * @param admin the admin interface of the local server
112    * @param client the client interface of the local server
113    * @return an adapted/decorated HConnection
114    */
115   @Deprecated
116   public static ClusterConnection createShortCircuitHConnection(final Connection conn,
117       final ServerName serverName, final AdminService.BlockingInterface admin,
118       final ClientService.BlockingInterface client) {
119     return new ConnectionAdapter(conn) {
120       @Override
121       public AdminService.BlockingInterface getAdmin(
122           ServerName sn, boolean getMaster) throws IOException {
123         return serverName.equals(sn) ? admin : super.getAdmin(sn, getMaster);
124       }
125 
126       @Override
127       public ClientService.BlockingInterface getClient(
128           ServerName sn) throws IOException {
129         return serverName.equals(sn) ? client : super.getClient(sn);
130       }
131     };
132   }
133 
134   /**
135    * Creates a short-circuit connection that can bypass the RPC layer (serialization,
136    * deserialization, networking, etc..) when talking to a local server.
137    * @param conf the current configuration
138    * @param pool the thread pool to use for batch operations
139    * @param user the user the connection is for
140    * @param serverName the local server name
141    * @param admin the admin interface of the local server
142    * @param client the client interface of the local server
143    * @return a short-circuit connection.
144    * @throws IOException
145    */
146   public static ClusterConnection createShortCircuitConnection(final Configuration conf,
147     ExecutorService pool, User user, final ServerName serverName,
148     final AdminService.BlockingInterface admin, final ClientService.BlockingInterface client)
149     throws IOException {
150     if (user == null) {
151       user = UserProvider.instantiate(conf).getCurrent();
152     }
153     return new ConnectionManager.HConnectionImplementation(conf, false, pool, user) {
154       @Override
155       public AdminService.BlockingInterface getAdmin(ServerName sn, boolean getMaster)
156         throws IOException {
157         return serverName.equals(sn) ? admin : super.getAdmin(sn, getMaster);
158       }
159 
160       @Override
161       public ClientService.BlockingInterface getClient(ServerName sn) throws IOException {
162         return serverName.equals(sn) ? client : super.getClient(sn);
163       }
164     };
165   }
166 
167   /**
168    * Setup the connection class, so that it will not depend on master being online. Used for testing
169    * @param conf configuration to set
170    */
171   @VisibleForTesting
172   public static void setupMasterlessConnection(Configuration conf) {
173     conf.set(HConnection.HBASE_CLIENT_CONNECTION_IMPL,
174       MasterlessConnection.class.getName());
175   }
176 
177   /**
178    * Some tests shut down the master. But table availability is a master RPC which is performed on
179    * region re-lookups.
180    */
181   static class MasterlessConnection extends ConnectionManager.HConnectionImplementation {
182     MasterlessConnection(Configuration conf, boolean managed,
183       ExecutorService pool, User user) throws IOException {
184       super(conf, managed, pool, user);
185     }
186 
187     @Override
188     public boolean isTableDisabled(TableName tableName) throws IOException {
189       // treat all tables as enabled
190       return false;
191     }
192   }
193 
194   // A byte array in which all elements are the max byte, and it is used to
195   // construct closest front row
196   static final byte[] MAX_BYTE_ARRAY = Bytes.createMaxByteArray(9);
197 
198   /**
199    * Create the closest row after the specified row
200    */
201   static byte[] createClosestRowAfter(byte[] row) {
202     return Arrays.copyOf(row, row.length + 1);
203   }
204 
205   /**
206    * Create a row before the specified row and very close to the specified row.
207    */
208   static byte[] createCloseRowBefore(byte[] row) {
209     if (row.length == 0) {
210       return MAX_BYTE_ARRAY;
211     }
212     if (row[row.length - 1] == 0) {
213       return Arrays.copyOf(row, row.length - 1);
214     } else {
215       byte[] nextRow = new byte[row.length + MAX_BYTE_ARRAY.length];
216       System.arraycopy(row, 0, nextRow, 0, row.length - 1);
217       nextRow[row.length - 1] = (byte) ((row[row.length - 1] & 0xFF) - 1);
218       System.arraycopy(MAX_BYTE_ARRAY, 0, nextRow, row.length, MAX_BYTE_ARRAY.length);
219       return nextRow;
220     }
221   }
222 
223   static boolean isEmptyStartRow(byte[] row) {
224     return Bytes.equals(row, EMPTY_START_ROW);
225   }
226 
227   static boolean isEmptyStopRow(byte[] row) {
228     return Bytes.equals(row, EMPTY_END_ROW);
229   }
230 
231   private static final Comparator<Cell> COMPARE_WITHOUT_ROW = new Comparator<Cell>() {
232 
233     @Override
234     public int compare(Cell o1, Cell o2) {
235       return CellComparator.compareWithoutRow(o1, o2);
236     }
237   };
238 
239   static Result filterCells(Result result, Cell keepCellsAfter) {
240     if (keepCellsAfter == null) {
241       // do not need to filter
242       return result;
243     }
244     // not the same row
245     if (!CellUtil.matchingRow(keepCellsAfter, result.getRow(), 0, result.getRow().length)) {
246       return result;
247     }
248     Cell[] rawCells = result.rawCells();
249     int index = Arrays.binarySearch(rawCells, keepCellsAfter, COMPARE_WITHOUT_ROW);
250     if (index < 0) {
251       index = -index - 1;
252     } else {
253       index++;
254     }
255     if (index == 0) {
256       return result;
257     }
258     if (index == rawCells.length) {
259       return null;
260     }
261     return Result.create(Arrays.copyOfRange(rawCells, index, rawCells.length), null,
262       result.isStale(), result.mayHaveMoreCellsInRow());
263   }
264 
265   static boolean noMoreResultsForScan(Scan scan, HRegionInfo info) {
266     if (isEmptyStopRow(info.getEndKey())) {
267       return true;
268     }
269     if (isEmptyStopRow(scan.getStopRow())) {
270       return false;
271     }
272     int c = Bytes.compareTo(info.getEndKey(), scan.getStopRow());
273     // 1. if our stop row is less than the endKey of the region
274     // 2. if our stop row is equal to the endKey of the region and we do not include the stop row
275     // for scan.
276     return c > 0 || (c == 0 && !scan.includeStopRow());
277   }
278 
279   static boolean noMoreResultsForReverseScan(Scan scan, HRegionInfo info) {
280     if (isEmptyStartRow(info.getStartKey())) {
281       return true;
282     }
283     if (isEmptyStopRow(scan.getStopRow())) {
284       return false;
285     }
286     // no need to test the inclusive of the stop row as the start key of a region is included in
287     // the region.
288     return Bytes.compareTo(info.getStartKey(), scan.getStopRow()) <= 0;
289   }
290 
291   public static ScanResultCache createScanResultCache(Scan scan) {
292     if (scan.getAllowPartialResults()) {
293       return new AllowPartialScanResultCache();
294     } else if (scan.getBatch() > 0) {
295       return new BatchScanResultCache(scan.getBatch());
296     } else {
297       return new CompleteScanResultCache();
298     }
299   }
300 }