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