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