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 java.io.IOException;
21  import java.util.Random;
22  import java.util.concurrent.ExecutorService;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.hadoop.conf.Configuration;
26  import org.apache.hadoop.hbase.HConstants;
27  import org.apache.hadoop.hbase.RegionLocations;
28  import org.apache.hadoop.hbase.ServerName;
29  import org.apache.hadoop.hbase.TableName;
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
32  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;
33  import org.apache.hadoop.hbase.security.User;
34  import org.apache.hadoop.hbase.security.UserProvider;
35  
36  import com.google.common.annotations.VisibleForTesting;
37  
38  /**
39   * Utility used by client connections.
40   */
41  @InterfaceAudience.Private
42  public class ConnectionUtils {
43  
44    private static final Random RANDOM = new Random();
45    /**
46     * Calculate pause time.
47     * Built on {@link HConstants#RETRY_BACKOFF}.
48     * @param pause
49     * @param tries
50     * @return How long to wait after <code>tries</code> retries
51     */
52    public static long getPauseTime(final long pause, final int tries) {
53      int ntries = tries;
54      if (ntries >= HConstants.RETRY_BACKOFF.length) {
55        ntries = HConstants.RETRY_BACKOFF.length - 1;
56      }
57      if (ntries < 0) {
58        ntries = 0;
59      }
60  
61      long normalPause = pause * HConstants.RETRY_BACKOFF[ntries];
62      long jitter =  (long)(normalPause * RANDOM.nextFloat() * 0.01f); // 1% possible jitter
63      return normalPause + jitter;
64    }
65  
66  
67    /**
68     * Adds / subs a 10% jitter to a pause time. Minimum is 1.
69     * @param pause the expected pause.
70     * @param jitter the jitter ratio, between 0 and 1, exclusive.
71     */
72    public static long addJitter(final long pause, final float jitter) {
73      float lag = pause * (RANDOM.nextFloat() - 0.5f) * jitter;
74      long newPause = pause + (long) lag;
75      if (newPause <= 0) {
76        return 1;
77      }
78      return newPause;
79    }
80  
81    /**
82     * @param conn The connection for which to replace the generator.
83     * @param cnm Replaces the nonce generator used, for testing.
84     * @return old nonce generator.
85     */
86    public static NonceGenerator injectNonceGeneratorForTesting(
87        ClusterConnection conn, NonceGenerator cnm) {
88      return ConnectionManager.injectNonceGeneratorForTesting(conn, cnm);
89    }
90  
91    /**
92     * Changes the configuration to set the number of retries needed when using HConnection
93     * internally, e.g. for  updating catalog tables, etc.
94     * Call this method before we create any Connections.
95     * @param c The Configuration instance to set the retries into.
96     * @param log Used to log what we set in here.
97     */
98    public static void setServerSideHConnectionRetriesConfig(
99        final Configuration c, final String sn, final Log log) {
100     // TODO: Fix this. Not all connections from server side should have 10 times the retries.
101     int hcRetries = c.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
102       HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
103     // Go big.  Multiply by 10.  If we can't get to meta after this many retries
104     // then something seriously wrong.
105     int serversideMultiplier = c.getInt("hbase.client.serverside.retries.multiplier", 10);
106     int retries = hcRetries * serversideMultiplier;
107     c.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, retries);
108     log.info(sn + " server-side HConnection retries=" + retries);
109   }
110 
111   /**
112    * Adapt a HConnection so that it can bypass the RPC layer (serialization,
113    * deserialization, networking, etc..) -- i.e. short-circuit -- when talking to a local server.
114    * @param conn the connection to adapt
115    * @param serverName the local server name
116    * @param admin the admin interface of the local server
117    * @param client the client interface of the local server
118    * @return an adapted/decorated HConnection
119    */
120   @Deprecated
121   public static ClusterConnection createShortCircuitHConnection(final Connection conn,
122       final ServerName serverName, final AdminService.BlockingInterface admin,
123       final ClientService.BlockingInterface client) {
124     return new ConnectionAdapter(conn) {
125       @Override
126       public AdminService.BlockingInterface getAdmin(
127           ServerName sn, boolean getMaster) throws IOException {
128         return serverName.equals(sn) ? admin : super.getAdmin(sn, getMaster);
129       }
130 
131       @Override
132       public ClientService.BlockingInterface getClient(
133           ServerName sn) throws IOException {
134         return serverName.equals(sn) ? client : super.getClient(sn);
135       }
136     };
137   }
138 
139   /**
140    * Creates a short-circuit connection that can bypass the RPC layer (serialization,
141    * deserialization, networking, etc..) when talking to a local server.
142    * @param conf the current configuration
143    * @param pool the thread pool to use for batch operations
144    * @param user the user the connection is for
145    * @param serverName the local server name
146    * @param admin the admin interface of the local server
147    * @param client the client interface of the local server
148    * @return a short-circuit connection.
149    * @throws IOException
150    */
151   public static ClusterConnection createShortCircuitConnection(final Configuration conf,
152     ExecutorService pool, User user, final ServerName serverName,
153     final AdminService.BlockingInterface admin, final ClientService.BlockingInterface client)
154     throws IOException {
155     if (user == null) {
156       user = UserProvider.instantiate(conf).getCurrent();
157     }
158     return new ConnectionManager.HConnectionImplementation(conf, false, pool, user) {
159       @Override
160       public AdminService.BlockingInterface getAdmin(ServerName sn, boolean getMaster)
161         throws IOException {
162         return serverName.equals(sn) ? admin : super.getAdmin(sn, getMaster);
163       }
164 
165       @Override
166       public ClientService.BlockingInterface getClient(ServerName sn) throws IOException {
167         return serverName.equals(sn) ? client : super.getClient(sn);
168       }
169     };
170   }
171 
172   /**
173    * Setup the connection class, so that it will not depend on master being online. Used for testing
174    * @param conf configuration to set
175    */
176   @VisibleForTesting
177   public static void setupMasterlessConnection(Configuration conf) {
178     conf.set(HConnection.HBASE_CLIENT_CONNECTION_IMPL,
179       MasterlessConnection.class.getName());
180   }
181 
182   /**
183    * Some tests shut down the master. But table availability is a master RPC which is performed on
184    * region re-lookups.
185    */
186   static class MasterlessConnection extends ConnectionManager.HConnectionImplementation {
187     MasterlessConnection(Configuration conf, boolean managed,
188       ExecutorService pool, User user) throws IOException {
189       super(conf, managed, pool, user);
190     }
191 
192     @Override
193     public boolean isTableDisabled(TableName tableName) throws IOException {
194       // treat all tables as enabled
195       return false;
196     }
197   }
198 }