View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.client;
20  
21  import static org.apache.hadoop.hbase.HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE;
22  import static org.junit.Assert.assertEquals;
23  import static org.junit.Assert.assertFalse;
24  import static org.junit.Assert.assertNotNull;
25  import static org.junit.Assert.assertNull;
26  import static org.junit.Assert.assertTrue;
27  import static org.junit.Assert.fail;
28  
29  import java.io.IOException;
30  import java.lang.reflect.Field;
31  import java.lang.reflect.Modifier;
32  import java.net.SocketTimeoutException;
33  import java.util.ArrayList;
34  import java.util.HashMap;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.Random;
38  import java.util.concurrent.ExecutorService;
39  import java.util.concurrent.SynchronousQueue;
40  import java.util.concurrent.ThreadPoolExecutor;
41  import java.util.concurrent.TimeUnit;
42  import java.util.concurrent.atomic.AtomicBoolean;
43  import java.util.concurrent.atomic.AtomicInteger;
44  import java.util.concurrent.atomic.AtomicLong;
45  import java.util.concurrent.atomic.AtomicReference;
46  
47  import org.apache.commons.logging.Log;
48  import org.apache.commons.logging.LogFactory;
49  import org.apache.hadoop.conf.Configuration;
50  import org.apache.hadoop.hbase.CategoryBasedTimeout;
51  import org.apache.hadoop.hbase.Cell;
52  import org.apache.hadoop.hbase.HBaseConfiguration;
53  import org.apache.hadoop.hbase.HBaseTestingUtility;
54  import org.apache.hadoop.hbase.HConstants;
55  import org.apache.hadoop.hbase.HRegionLocation;
56  import org.apache.hadoop.hbase.HTableDescriptor;
57  import org.apache.hadoop.hbase.RegionLocations;
58  import org.apache.hadoop.hbase.ServerName;
59  import org.apache.hadoop.hbase.TableName;
60  import org.apache.hadoop.hbase.Waiter;
61  import org.apache.hadoop.hbase.client.ConnectionManager.HConnectionImplementation;
62  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
63  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
64  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
65  import org.apache.hadoop.hbase.exceptions.ClientExceptionsUtil;
66  import org.apache.hadoop.hbase.exceptions.DeserializationException;
67  import org.apache.hadoop.hbase.exceptions.RegionMovedException;
68  import org.apache.hadoop.hbase.filter.Filter;
69  import org.apache.hadoop.hbase.filter.FilterBase;
70  import org.apache.hadoop.hbase.ipc.RpcClient;
71  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
72  import org.apache.hadoop.hbase.master.HMaster;
73  import org.apache.hadoop.hbase.regionserver.HRegionServer;
74  import org.apache.hadoop.hbase.regionserver.Region;
75  import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
76  import org.apache.hadoop.hbase.testclassification.LargeTests;
77  import org.apache.hadoop.hbase.util.Bytes;
78  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
79  import org.apache.hadoop.hbase.util.JVMClusterUtil;
80  import org.apache.hadoop.hbase.util.ManualEnvironmentEdge;
81  import org.apache.hadoop.hbase.util.Threads;
82  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
83  import org.junit.AfterClass;
84  import org.junit.Assert;
85  import org.junit.BeforeClass;
86  import org.junit.Ignore;
87  import org.junit.Rule;
88  import org.junit.Test;
89  import org.junit.experimental.categories.Category;
90  import org.junit.rules.TestRule;
91  
92  import com.google.common.collect.Lists;
93  
94  /**
95   * This class is for testing HBaseConnectionManager features
96   */
97  @Category({LargeTests.class})
98  public class TestHCM {
99    @Rule public final TestRule timeout = CategoryBasedTimeout.builder()
100       .withTimeout(this.getClass())
101       .withLookingForStuckThread(true)
102       .build();
103   private static final Log LOG = LogFactory.getLog(TestHCM.class);
104   private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
105   private static final TableName TABLE_NAME =
106       TableName.valueOf("test");
107   private static final TableName TABLE_NAME1 =
108       TableName.valueOf("test1");
109   private static final TableName TABLE_NAME2 =
110       TableName.valueOf("test2");
111   private static final TableName TABLE_NAME3 =
112       TableName.valueOf("test3");
113   private static final TableName TABLE_NAME4 =
114       TableName.valueOf("test4");
115   private static final byte[] FAM_NAM = Bytes.toBytes("f");
116   private static final byte[] ROW = Bytes.toBytes("bbb");
117   private static final byte[] ROW_X = Bytes.toBytes("xxx");
118   private static Random _randy = new Random();
119 
120 /**
121 * This copro sleeps 20 second. The first call it fails. The second time, it works.
122 */
123   public static class SleepAndFailFirstTime extends BaseRegionObserver {
124     static final AtomicLong ct = new AtomicLong(0);
125     static final String SLEEP_TIME_CONF_KEY =
126         "hbase.coprocessor.SleepAndFailFirstTime.sleepTime";
127     static final long DEFAULT_SLEEP_TIME = 20000;
128     static final AtomicLong sleepTime = new AtomicLong(DEFAULT_SLEEP_TIME);
129 
130     public SleepAndFailFirstTime() {
131     }
132 
133     @Override
134     public void postOpen(ObserverContext<RegionCoprocessorEnvironment> c) {
135       RegionCoprocessorEnvironment env = c.getEnvironment();
136       Configuration conf = env.getConfiguration();
137       sleepTime.set(conf.getLong(SLEEP_TIME_CONF_KEY, DEFAULT_SLEEP_TIME));
138     }
139 
140     @Override
141     public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> e,
142               final Get get, final List<Cell> results) throws IOException {
143       Threads.sleep(sleepTime.get());
144       if (ct.incrementAndGet() == 1){
145         throw new IOException("first call I fail");
146       }
147     }
148   }
149 
150   public static class SleepCoprocessor extends BaseRegionObserver {
151     public static final int SLEEP_TIME = 5000;
152     @Override
153     public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> e,
154         final Get get, final List<Cell> results) throws IOException {
155       Threads.sleep(SLEEP_TIME);
156     }
157   }
158 
159   @BeforeClass
160   public static void setUpBeforeClass() throws Exception {
161     TEST_UTIL.getConfiguration().setBoolean(HConstants.STATUS_PUBLISHED, true);
162     // Up the handlers; this test needs more than usual.
163     TEST_UTIL.getConfiguration().setInt(HConstants.REGION_SERVER_HIGH_PRIORITY_HANDLER_COUNT, 10);
164     TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
165     TEST_UTIL.startMiniCluster(2);
166   }
167 
168   @AfterClass public static void tearDownAfterClass() throws Exception {
169     TEST_UTIL.shutdownMiniCluster();
170   }
171 
172 
173   private static int getHConnectionManagerCacheSize(){
174     return HConnectionTestingUtility.getConnectionCount();
175   }
176 
177   @Test
178   public void testClusterConnection() throws IOException {
179     ThreadPoolExecutor otherPool = new ThreadPoolExecutor(1, 1,
180         5, TimeUnit.SECONDS,
181         new SynchronousQueue<Runnable>(),
182         Threads.newDaemonThreadFactory("test-hcm"));
183 
184     HConnection con1 = HConnectionManager.createConnection(TEST_UTIL.getConfiguration());
185     HConnection con2 = HConnectionManager.createConnection(TEST_UTIL.getConfiguration(), otherPool);
186     // make sure the internally created ExecutorService is the one passed
187     assertTrue(otherPool == ((HConnectionImplementation)con2).getCurrentBatchPool());
188 
189     String tableName = "testClusterConnection";
190     TEST_UTIL.createTable(tableName.getBytes(), FAM_NAM).close();
191     HTable t = (HTable)con1.getTable(tableName, otherPool);
192     // make sure passing a pool to the getTable does not trigger creation of an internal pool
193     assertNull("Internal Thread pool should be null", ((HConnectionImplementation)con1).getCurrentBatchPool());
194     // table should use the pool passed
195     assertTrue(otherPool == t.getPool());
196     t.close();
197 
198     t = (HTable)con2.getTable(tableName);
199     // table should use the connectin's internal pool
200     assertTrue(otherPool == t.getPool());
201     t.close();
202 
203     t = (HTable)con2.getTable(Bytes.toBytes(tableName));
204     // try other API too
205     assertTrue(otherPool == t.getPool());
206     t.close();
207 
208     t = (HTable)con2.getTable(TableName.valueOf(tableName));
209     // try other API too
210     assertTrue(otherPool == t.getPool());
211     t.close();
212 
213     t = (HTable)con1.getTable(tableName);
214     ExecutorService pool = ((HConnectionImplementation)con1).getCurrentBatchPool();
215     // make sure an internal pool was created
216     assertNotNull("An internal Thread pool should have been created", pool);
217     // and that the table is using it
218     assertTrue(t.getPool() == pool);
219     t.close();
220 
221     t = (HTable)con1.getTable(tableName);
222     // still using the *same* internal pool
223     assertTrue(t.getPool() == pool);
224     t.close();
225 
226     con1.close();
227     // if the pool was created on demand it should be closed upon connection close
228     assertTrue(pool.isShutdown());
229 
230     con2.close();
231     // if the pool is passed, it is not closed
232     assertFalse(otherPool.isShutdown());
233     otherPool.shutdownNow();
234   }
235 
236   /**
237    * Naive test to check that HConnection#getAdmin returns a properly constructed HBaseAdmin object
238    * @throws IOException Unable to construct admin
239    */
240   @Test
241   public void testAdminFactory() throws IOException {
242     Connection con1 = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
243     Admin admin = con1.getAdmin();
244     assertTrue(admin.getConnection() == con1);
245     assertTrue(admin.getConfiguration() == TEST_UTIL.getConfiguration());
246     con1.close();
247   }
248 
249   // Fails too often!  Needs work.  HBASE-12558
250   @Ignore @Test (expected = RegionServerStoppedException.class)
251   public void testClusterStatus() throws Exception {
252 
253     TableName tn =
254         TableName.valueOf("testClusterStatus");
255     byte[] cf = "cf".getBytes();
256     byte[] rk = "rk1".getBytes();
257 
258     JVMClusterUtil.RegionServerThread rs = TEST_UTIL.getHBaseCluster().startRegionServer();
259     rs.waitForServerOnline();
260     final ServerName sn = rs.getRegionServer().getServerName();
261 
262     HTable t = TEST_UTIL.createTable(tn, cf);
263     TEST_UTIL.waitTableAvailable(tn);
264 
265     while(TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().
266         getRegionStates().isRegionsInTransition()){
267       Thread.sleep(1);
268     }
269     final HConnectionImplementation hci =  (HConnectionImplementation)t.getConnection();
270     while (t.getRegionLocation(rk).getPort() != sn.getPort()){
271       TEST_UTIL.getHBaseAdmin().move(t.getRegionLocation(rk).getRegionInfo().
272           getEncodedNameAsBytes(), Bytes.toBytes(sn.toString()));
273       while(TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().
274           getRegionStates().isRegionsInTransition()){
275         Thread.sleep(1);
276       }
277       hci.clearRegionCache(tn);
278     }
279     Assert.assertNotNull(hci.clusterStatusListener);
280     TEST_UTIL.assertRegionOnServer(t.getRegionLocation(rk).getRegionInfo(), sn, 20000);
281 
282     Put p1 = new Put(rk);
283     p1.add(cf, "qual".getBytes(), "val".getBytes());
284     t.put(p1);
285 
286     rs.getRegionServer().abort("I'm dead");
287 
288     // We want the status to be updated. That's a least 10 second
289     TEST_UTIL.waitFor(40000, 1000, true, new Waiter.Predicate<Exception>() {
290       @Override
291       public boolean evaluate() throws Exception {
292         return TEST_UTIL.getHBaseCluster().getMaster().getServerManager().
293             getDeadServers().isDeadServer(sn);
294       }
295     });
296 
297     TEST_UTIL.waitFor(40000, 1000, true, new Waiter.Predicate<Exception>() {
298       @Override
299       public boolean evaluate() throws Exception {
300         return hci.clusterStatusListener.isDeadServer(sn);
301       }
302     });
303 
304     t.close();
305     hci.getClient(sn);  // will throw an exception: RegionServerStoppedException
306   }
307 
308   /**
309    * Test that we can handle connection close: it will trigger a retry, but the calls will
310    *  finish.
311    */
312   @Test
313   public void testConnectionCloseAllowsInterrupt() throws Exception {
314     testConnectionClose(true);
315   }
316 
317   @Test
318   public void testConnectionNotAllowsInterrupt() throws Exception {
319     testConnectionClose(false);
320   }
321 
322   /**
323    * Test that an operation can fail if we read the global operation timeout, even if the
324    * individual timeout is fine. We do that with:
325    * - client side: an operation timeout of 30 seconds
326    * - server side: we sleep 20 second at each attempt. The first work fails, the second one
327    * succeeds. But the client won't wait that much, because 20 + 20 > 30, so the client
328    * timeouted when the server answers.
329    */
330   @Test
331   public void testOperationTimeout() throws Exception {
332     HTableDescriptor hdt = TEST_UTIL.createTableDescriptor("HCM-testOperationTimeout");
333     hdt.addCoprocessor(SleepAndFailFirstTime.class.getName());
334     HTable table = TEST_UTIL.createTable(hdt, new byte[][]{FAM_NAM}, TEST_UTIL.getConfiguration());
335     table.setRpcTimeout(Integer.MAX_VALUE);
336     // Check that it works if the timeout is big enough
337     table.setOperationTimeout(120 * 1000);
338     table.get(new Get(FAM_NAM));
339 
340     // Resetting and retrying. Will fail this time, not enough time for the second try
341     SleepAndFailFirstTime.ct.set(0);
342     try {
343       table.setOperationTimeout(30 * 1000);
344       table.get(new Get(FAM_NAM));
345       Assert.fail("We expect an exception here");
346     } catch (SocketTimeoutException e) {
347       // The client has a CallTimeout class, but it's not shared.We're not very clean today,
348       //  in the general case you can expect the call to stop, but the exception may vary.
349       // In this test however, we're sure that it will be a socket timeout.
350       LOG.info("We received an exception, as expected ", e);
351     } catch (IOException e) {
352       Assert.fail("Wrong exception:" + e.getMessage());
353     } finally {
354       table.close();
355     }
356   }
357 
358   @Test(expected = RetriesExhaustedException.class)
359   public void testRpcTimeout() throws Exception {
360     HTableDescriptor hdt = TEST_UTIL.createTableDescriptor("HCM-testRpcTimeout");
361     hdt.addCoprocessor(SleepCoprocessor.class.getName());
362     Configuration c = new Configuration(TEST_UTIL.getConfiguration());
363 
364     try (Table t = TEST_UTIL.createTable(hdt, new byte[][] { FAM_NAM }, c)) {
365       assert t instanceof HTable;
366       HTable table = (HTable) t;
367       table.setRpcTimeout(SleepCoprocessor.SLEEP_TIME / 2);
368       table.setOperationTimeout(SleepCoprocessor.SLEEP_TIME * 100);
369       table.get(new Get(FAM_NAM));
370     }
371   }
372 
373   /**
374    * Test starting from 0 index when RpcRetryingCaller calculate the backoff time.
375    */
376   @Test
377   public void testRpcRetryingCallerSleep() throws Exception {
378     HTableDescriptor hdt = TEST_UTIL.createTableDescriptor("HCM-testRpcRetryingCallerSleep");
379     hdt.addCoprocessorWithSpec("|" + SleepAndFailFirstTime.class.getName() + "||"
380         + SleepAndFailFirstTime.SLEEP_TIME_CONF_KEY + "=2000");
381     TEST_UTIL.createTable(hdt, new byte[][] { FAM_NAM }).close();
382 
383     Configuration c = new Configuration(TEST_UTIL.getConfiguration());
384     c.setInt(HConstants.HBASE_CLIENT_PAUSE, 3000);
385     c.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 4000);
386 
387     Connection connection = ConnectionFactory.createConnection(c);
388     Table t = connection.getTable(TableName.valueOf("HCM-testRpcRetryingCallerSleep"));
389     if (t instanceof HTable) {
390       HTable table = (HTable) t;
391       table.setOperationTimeout(8000);
392       // Check that it works. Because 2s + 3s * RETRY_BACKOFF[0] + 2s < 8s
393       table.get(new Get(FAM_NAM));
394 
395       // Resetting and retrying.
396       SleepAndFailFirstTime.ct.set(0);
397       try {
398         table.setOperationTimeout(6000);
399         // Will fail this time. After sleep, there are not enough time for second retry
400         // Beacuse 2s + 3s + 2s > 6s
401         table.get(new Get(FAM_NAM));
402         Assert.fail("We expect an exception here");
403       } catch (SocketTimeoutException e) {
404         LOG.info("We received an exception, as expected ", e);
405       } catch (IOException e) {
406         Assert.fail("Wrong exception:" + e.getMessage());
407       } finally {
408         table.close();
409         connection.close();
410       }
411     }
412   }
413 
414   @Test
415   public void testCallableSleep() throws Exception {
416     long pauseTime;
417     long baseTime = 100;
418     TableName tableName = TableName.valueOf("HCM-testCallableSleep");
419     HTable table = TEST_UTIL.createTable(tableName, FAM_NAM);
420     RegionServerCallable<Object> regionServerCallable = new RegionServerCallable<Object>(
421         TEST_UTIL.getConnection(), tableName, ROW) {
422       public Object call(int timeout) throws IOException {
423         return null;
424       }
425     };
426 
427     regionServerCallable.prepare(false);
428     for (int i = 0; i < HConstants.RETRY_BACKOFF.length; i++) {
429       pauseTime = regionServerCallable.sleep(baseTime, i);
430       assertTrue(pauseTime >= (baseTime * HConstants.RETRY_BACKOFF[i]));
431       assertTrue(pauseTime <= (baseTime * HConstants.RETRY_BACKOFF[i] * 1.01f));
432     }
433 
434     RegionAdminServiceCallable<Object> regionAdminServiceCallable =
435         new RegionAdminServiceCallable<Object>(
436         (ClusterConnection) TEST_UTIL.getConnection(), new RpcControllerFactory(
437             TEST_UTIL.getConfiguration()), tableName, ROW) {
438       public Object call(int timeout) throws IOException {
439         return null;
440       }
441     };
442 
443     regionAdminServiceCallable.prepare(false);
444     for (int i = 0; i < HConstants.RETRY_BACKOFF.length; i++) {
445       pauseTime = regionAdminServiceCallable.sleep(baseTime, i);
446       assertTrue(pauseTime >= (baseTime * HConstants.RETRY_BACKOFF[i]));
447       assertTrue(pauseTime <= (baseTime * HConstants.RETRY_BACKOFF[i] * 1.01f));
448     }
449 
450     MasterCallable masterCallable = new MasterCallable((HConnection) TEST_UTIL.getConnection()) {
451       public Object call(int timeout) throws IOException {
452         return null;
453       }
454     };
455 
456     for (int i = 0; i < HConstants.RETRY_BACKOFF.length; i++) {
457       pauseTime = masterCallable.sleep(baseTime, i);
458       assertTrue(pauseTime >= (baseTime * HConstants.RETRY_BACKOFF[i]));
459       assertTrue(pauseTime <= (baseTime * HConstants.RETRY_BACKOFF[i] * 1.01f));
460     }
461   }
462 
463   private void testConnectionClose(boolean allowsInterrupt) throws Exception {
464     TableName tableName = TableName.valueOf("HCM-testConnectionClose" + allowsInterrupt);
465     TEST_UTIL.createTable(tableName, FAM_NAM).close();
466 
467     boolean previousBalance = TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, true);
468 
469     Configuration c2 = new Configuration(TEST_UTIL.getConfiguration());
470     // We want to work on a separate connection.
471     c2.set(HConstants.HBASE_CLIENT_INSTANCE_ID, String.valueOf(-1));
472     c2.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 100); // retry a lot
473     c2.setInt(HConstants.HBASE_CLIENT_PAUSE, 1); // don't wait between retries.
474     c2.setInt(RpcClient.FAILED_SERVER_EXPIRY_KEY, 0); // Server do not really expire
475     c2.setBoolean(RpcClient.SPECIFIC_WRITE_THREAD, allowsInterrupt);
476 
477     final HTable table = new HTable(c2, tableName);
478 
479     Put put = new Put(ROW);
480     put.add(FAM_NAM, ROW, ROW);
481     table.put(put);
482 
483     // 4 steps: ready=0; doGets=1; mustStop=2; stopped=3
484     final AtomicInteger step = new AtomicInteger(0);
485 
486     final AtomicReference<Throwable> failed = new AtomicReference<Throwable>(null);
487     Thread t = new Thread("testConnectionCloseThread") {
488       @Override
489       public void run() {
490         int done = 0;
491         try {
492           step.set(1);
493           while (step.get() == 1) {
494             Get get = new Get(ROW);
495             table.get(get);
496             done++;
497             if (done % 100 == 0)
498               LOG.info("done=" + done);
499           }
500         } catch (Throwable t) {
501           failed.set(t);
502           LOG.error(t);
503         }
504         step.set(3);
505       }
506     };
507     t.start();
508     TEST_UTIL.waitFor(20000, new Waiter.Predicate<Exception>() {
509       @Override
510       public boolean evaluate() throws Exception {
511         return step.get() == 1;
512       }
513     });
514 
515     ServerName sn = table.getRegionLocation(ROW).getServerName();
516     ConnectionManager.HConnectionImplementation conn =
517         (ConnectionManager.HConnectionImplementation) table.getConnection();
518     RpcClient rpcClient = conn.getRpcClient();
519 
520     LOG.info("Going to cancel connections. connection=" + conn.toString() + ", sn=" + sn);
521     for (int i = 0; i < 5000; i++) {
522       rpcClient.cancelConnections(sn);
523       Thread.sleep(5);
524     }
525 
526     step.compareAndSet(1, 2);
527     // The test may fail here if the thread doing the gets is stuck. The way to find
528     //  out what's happening is to look for the thread named 'testConnectionCloseThread'
529     TEST_UTIL.waitFor(40000, new Waiter.Predicate<Exception>() {
530       @Override
531       public boolean evaluate() throws Exception {
532         return step.get() == 3;
533       }
534     });
535     table.close();
536     Assert.assertTrue("Unexpected exception is " + failed.get(), failed.get() == null);
537     TEST_UTIL.getHBaseAdmin().setBalancerRunning(previousBalance, true);
538   }
539 
540   /**
541    * Test that connection can become idle without breaking everything.
542    */
543   @Test
544   public void testConnectionIdle() throws Exception {
545     TableName tableName = TableName.valueOf("HCM-testConnectionIdle");
546     TEST_UTIL.createTable(tableName, FAM_NAM).close();
547     int idleTime =  20000;
548     boolean previousBalance = TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, true);
549 
550     Configuration c2 = new Configuration(TEST_UTIL.getConfiguration());
551     // We want to work on a separate connection.
552     c2.set(HConstants.HBASE_CLIENT_INSTANCE_ID, String.valueOf(-1));
553     c2.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1); // Don't retry: retry = test failed
554     c2.setInt(RpcClient.IDLE_TIME, idleTime);
555 
556     final Table table = new HTable(c2, tableName);
557 
558     Put put = new Put(ROW);
559     put.add(FAM_NAM, ROW, ROW);
560     table.put(put);
561 
562     ManualEnvironmentEdge mee = new ManualEnvironmentEdge();
563     mee.setValue(System.currentTimeMillis());
564     EnvironmentEdgeManager.injectEdge(mee);
565     LOG.info("first get");
566     table.get(new Get(ROW));
567 
568     LOG.info("first get - changing the time & sleeping");
569     mee.incValue(idleTime + 1000);
570     Thread.sleep(1500); // we need to wait a little for the connection to be seen as idle.
571                         // 1500 = sleep time in RpcClient#waitForWork + a margin
572 
573     LOG.info("second get - connection has been marked idle in the middle");
574     // To check that the connection actually became idle would need to read some private
575     //  fields of RpcClient.
576     table.get(new Get(ROW));
577     mee.incValue(idleTime + 1000);
578 
579     LOG.info("third get - connection is idle, but the reader doesn't know yet");
580     // We're testing here a special case:
581     //  time limit reached BUT connection not yet reclaimed AND a new call.
582     //  in this situation, we don't close the connection, instead we use it immediately.
583     // If we're very unlucky we can have a race condition in the test: the connection is already
584     //  under closing when we do the get, so we have an exception, and we don't retry as the
585     //  retry number is 1. The probability is very very low, and seems acceptable for now. It's
586     //  a test issue only.
587     table.get(new Get(ROW));
588 
589     LOG.info("we're done - time will change back");
590 
591     table.close();
592     EnvironmentEdgeManager.reset();
593     TEST_UTIL.getHBaseAdmin().setBalancerRunning(previousBalance, true);
594   }
595 
596     /**
597      * Test that the connection to the dead server is cut immediately when we receive the
598      *  notification.
599      * @throws Exception
600      */
601   @Test
602   public void testConnectionCut() throws Exception {
603 
604     TableName tableName = TableName.valueOf("HCM-testConnectionCut");
605 
606     TEST_UTIL.createTable(tableName, FAM_NAM).close();
607     boolean previousBalance = TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, true);
608 
609     Configuration c2 = new Configuration(TEST_UTIL.getConfiguration());
610     // We want to work on a separate connection.
611     c2.set(HConstants.HBASE_CLIENT_INSTANCE_ID, String.valueOf(-1));
612     c2.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
613     c2.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 30 * 1000);
614 
615     HTable table = new HTable(c2, tableName);
616 
617     Put p = new Put(FAM_NAM);
618     p.add(FAM_NAM, FAM_NAM, FAM_NAM);
619     table.put(p);
620 
621     final HConnectionImplementation hci =  (HConnectionImplementation)table.getConnection();
622     final HRegionLocation loc = table.getRegionLocation(FAM_NAM);
623 
624     Get get = new Get(FAM_NAM);
625     Assert.assertNotNull(table.get(get));
626 
627     get = new Get(FAM_NAM);
628     get.setFilter(new BlockingFilter());
629 
630     // This thread will mark the server as dead while we're waiting during a get.
631     Thread t = new Thread() {
632       @Override
633       public void run() {
634         synchronized (syncBlockingFilter) {
635           try {
636             syncBlockingFilter.wait();
637           } catch (InterruptedException e) {
638             throw new RuntimeException(e);
639           }
640         }
641         hci.clusterStatusListener.deadServerHandler.newDead(loc.getServerName());
642       }
643     };
644 
645     t.start();
646     try {
647       table.get(get);
648       Assert.fail();
649     } catch (IOException expected) {
650       LOG.debug("Received: " + expected);
651       Assert.assertFalse(expected instanceof SocketTimeoutException);
652       Assert.assertFalse(syncBlockingFilter.get());
653     } finally {
654       syncBlockingFilter.set(true);
655       t.join();
656       HConnectionManager.getConnection(c2).close();
657       TEST_UTIL.getHBaseAdmin().setBalancerRunning(previousBalance, true);
658     }
659 
660     table.close();
661   }
662 
663   protected static final AtomicBoolean syncBlockingFilter = new AtomicBoolean(false);
664 
665   public static class BlockingFilter extends FilterBase {
666     @Override
667     public boolean filterRowKey(byte[] buffer, int offset, int length) throws IOException {
668       int i = 0;
669       while (i++ < 1000 && !syncBlockingFilter.get()) {
670         synchronized (syncBlockingFilter) {
671           syncBlockingFilter.notifyAll();
672         }
673         Threads.sleep(100);
674       }
675       syncBlockingFilter.set(true);
676       return false;
677     }
678     @Override
679     public ReturnCode filterKeyValue(Cell ignored) throws IOException {
680       return ReturnCode.INCLUDE;
681     }
682 
683     public static Filter parseFrom(final byte [] pbBytes) throws DeserializationException{
684       return new BlockingFilter();
685     }
686   }
687 
688   @Test (timeout=120000)
689   public void abortingHConnectionRemovesItselfFromHCM() throws Exception {
690     // Save off current HConnections
691     Map<HConnectionKey, HConnectionImplementation> oldHBaseInstances =
692         new HashMap<HConnectionKey, HConnectionImplementation>();
693     oldHBaseInstances.putAll(ConnectionManager.CONNECTION_INSTANCES);
694 
695     ConnectionManager.CONNECTION_INSTANCES.clear();
696 
697     try {
698       HConnection connection = HConnectionManager.getConnection(TEST_UTIL.getConfiguration());
699       connection.abort("test abortingHConnectionRemovesItselfFromHCM", new Exception(
700           "test abortingHConnectionRemovesItselfFromHCM"));
701       Assert.assertNotSame(connection,
702         HConnectionManager.getConnection(TEST_UTIL.getConfiguration()));
703     } finally {
704       // Put original HConnections back
705       ConnectionManager.CONNECTION_INSTANCES.clear();
706       ConnectionManager.CONNECTION_INSTANCES.putAll(oldHBaseInstances);
707     }
708   }
709 
710   /**
711    * Test that when we delete a location using the first row of a region
712    * that we really delete it.
713    * @throws Exception
714    */
715   @Test
716   public void testRegionCaching() throws Exception{
717     TEST_UTIL.createMultiRegionTable(TABLE_NAME, FAM_NAM).close();
718     Configuration conf =  new Configuration(TEST_UTIL.getConfiguration());
719     conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
720     HTable table = new HTable(conf, TABLE_NAME);
721 
722     TEST_UTIL.waitUntilAllRegionsAssigned(table.getName());
723     Put put = new Put(ROW);
724     put.add(FAM_NAM, ROW, ROW);
725     table.put(put);
726     ConnectionManager.HConnectionImplementation conn =
727       (ConnectionManager.HConnectionImplementation)table.getConnection();
728 
729     assertNotNull(conn.getCachedLocation(TABLE_NAME, ROW));
730 
731     final int nextPort = conn.getCachedLocation(TABLE_NAME, ROW).getRegionLocation().getPort() + 1;
732     HRegionLocation loc = conn.getCachedLocation(TABLE_NAME, ROW).getRegionLocation();
733     conn.updateCachedLocation(loc.getRegionInfo(), loc.getServerName(),
734         ServerName.valueOf("127.0.0.1", nextPort,
735         HConstants.LATEST_TIMESTAMP), HConstants.LATEST_TIMESTAMP);
736     Assert.assertEquals(conn.getCachedLocation(TABLE_NAME, ROW)
737       .getRegionLocation().getPort(), nextPort);
738 
739     conn.clearRegionCache(TABLE_NAME, ROW.clone());
740     RegionLocations rl = conn.getCachedLocation(TABLE_NAME, ROW);
741     assertNull("What is this location?? " + rl, rl);
742 
743     // We're now going to test getAllRegionLocations() whether or not cache all region locations
744     conn.clearRegionCache(TABLE_NAME);
745     conn.getRegionLocator(TABLE_NAME).getAllRegionLocations();
746     assertNotNull("Can't get cached location for row aaa",
747         conn.getCachedLocation(TABLE_NAME,Bytes.toBytes("aaa")));
748     for(byte[] startKey:KEYS_FOR_HBA_CREATE_TABLE){
749       assertNotNull("Can't get cached location for row "+
750           Bytes.toString(startKey),conn.getCachedLocation(TABLE_NAME,startKey));
751     }
752     // We're now going to move the region and check that it works for the client
753     // First a new put to add the location in the cache
754     conn.clearRegionCache(TABLE_NAME);
755     Assert.assertEquals(0, conn.getNumberOfCachedRegionLocations(TABLE_NAME));
756     Put put2 = new Put(ROW);
757     put2.add(FAM_NAM, ROW, ROW);
758     table.put(put2);
759     assertNotNull(conn.getCachedLocation(TABLE_NAME, ROW));
760     assertNotNull(conn.getCachedLocation(TableName.valueOf(TABLE_NAME.getName()), ROW.clone()));
761 
762     TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, false);
763     HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster();
764 
765     // We can wait for all regions to be online, that makes log reading easier when debugging
766     while (master.getAssignmentManager().getRegionStates().isRegionsInTransition()) {
767       Thread.sleep(1);
768     }
769 
770     // Now moving the region to the second server
771     HRegionLocation toMove = conn.getCachedLocation(TABLE_NAME, ROW).getRegionLocation();
772     byte[] regionName = toMove.getRegionInfo().getRegionName();
773     byte[] encodedRegionNameBytes = toMove.getRegionInfo().getEncodedNameAsBytes();
774 
775     // Choose the other server.
776     int curServerId = TEST_UTIL.getHBaseCluster().getServerWith(regionName);
777     int destServerId = (curServerId == 0 ? 1 : 0);
778 
779     HRegionServer curServer = TEST_UTIL.getHBaseCluster().getRegionServer(curServerId);
780     HRegionServer destServer = TEST_UTIL.getHBaseCluster().getRegionServer(destServerId);
781 
782     ServerName destServerName = destServer.getServerName();
783 
784     // Check that we are in the expected state
785     Assert.assertTrue(curServer != destServer);
786     Assert.assertFalse(curServer.getServerName().equals(destServer.getServerName()));
787     Assert.assertFalse( toMove.getPort() == destServerName.getPort());
788     Assert.assertNotNull(curServer.getOnlineRegion(regionName));
789     Assert.assertNull(destServer.getOnlineRegion(regionName));
790     Assert.assertFalse(TEST_UTIL.getMiniHBaseCluster().getMaster().
791         getAssignmentManager().getRegionStates().isRegionsInTransition());
792 
793     // Moving. It's possible that we don't have all the regions online at this point, so
794     //  the test must depends only on the region we're looking at.
795     LOG.info("Move starting region="+toMove.getRegionInfo().getRegionNameAsString());
796     TEST_UTIL.getHBaseAdmin().move(
797       toMove.getRegionInfo().getEncodedNameAsBytes(),
798       destServerName.getServerName().getBytes()
799     );
800 
801     while (destServer.getOnlineRegion(regionName) == null ||
802         destServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes) ||
803         curServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes) ||
804         master.getAssignmentManager().getRegionStates().isRegionsInTransition()) {
805       // wait for the move to be finished
806       Thread.sleep(1);
807     }
808 
809     LOG.info("Move finished for region="+toMove.getRegionInfo().getRegionNameAsString());
810 
811     // Check our new state.
812     Assert.assertNull(curServer.getOnlineRegion(regionName));
813     Assert.assertNotNull(destServer.getOnlineRegion(regionName));
814     Assert.assertFalse(destServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes));
815     Assert.assertFalse(curServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes));
816 
817 
818     // Cache was NOT updated and points to the wrong server
819     Assert.assertFalse(
820         conn.getCachedLocation(TABLE_NAME, ROW).getRegionLocation()
821           .getPort() == destServerName.getPort());
822 
823     // This part relies on a number of tries equals to 1.
824     // We do a put and expect the cache to be updated, even if we don't retry
825     LOG.info("Put starting");
826     Put put3 = new Put(ROW);
827     put3.add(FAM_NAM, ROW, ROW);
828     try {
829       table.put(put3);
830       Assert.fail("Unreachable point");
831     } catch (RetriesExhaustedWithDetailsException e){
832       LOG.info("Put done, exception caught: " + e.getClass());
833       Assert.assertEquals(1, e.getNumExceptions());
834       Assert.assertEquals(1, e.getCauses().size());
835       Assert.assertArrayEquals(e.getRow(0).getRow(), ROW);
836 
837       // Check that we unserialized the exception as expected
838       Throwable cause = ClientExceptionsUtil.findException(e.getCause(0));
839       Assert.assertNotNull(cause);
840       Assert.assertTrue(cause instanceof RegionMovedException);
841     }
842     Assert.assertNotNull("Cached connection is null", conn.getCachedLocation(TABLE_NAME, ROW));
843     Assert.assertEquals(
844         "Previous server was " + curServer.getServerName().getHostAndPort(),
845         destServerName.getPort(),
846         conn.getCachedLocation(TABLE_NAME, ROW).getRegionLocation().getPort());
847 
848     Assert.assertFalse(destServer.getRegionsInTransitionInRS()
849       .containsKey(encodedRegionNameBytes));
850     Assert.assertFalse(curServer.getRegionsInTransitionInRS()
851       .containsKey(encodedRegionNameBytes));
852 
853     // We move it back to do another test with a scan
854     LOG.info("Move starting region=" + toMove.getRegionInfo().getRegionNameAsString());
855     TEST_UTIL.getHBaseAdmin().move(
856       toMove.getRegionInfo().getEncodedNameAsBytes(),
857       curServer.getServerName().getServerName().getBytes()
858     );
859 
860     while (curServer.getOnlineRegion(regionName) == null ||
861         destServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes) ||
862         curServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes) ||
863         master.getAssignmentManager().getRegionStates().isRegionsInTransition()) {
864       // wait for the move to be finished
865       Thread.sleep(1);
866     }
867 
868     // Check our new state.
869     Assert.assertNotNull(curServer.getOnlineRegion(regionName));
870     Assert.assertNull(destServer.getOnlineRegion(regionName));
871     LOG.info("Move finished for region=" + toMove.getRegionInfo().getRegionNameAsString());
872 
873     // Cache was NOT updated and points to the wrong server
874     Assert.assertFalse(conn.getCachedLocation(TABLE_NAME, ROW).getRegionLocation().getPort() ==
875       curServer.getServerName().getPort());
876 
877     Scan sc = new Scan();
878     sc.setStopRow(ROW);
879     sc.setStartRow(ROW);
880 
881     // The scanner takes the max retries from the connection configuration, not the table as
882     // the put.
883     TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
884 
885     try {
886       ResultScanner rs = table.getScanner(sc);
887       while (rs.next() != null) {
888       }
889       Assert.fail("Unreachable point");
890     } catch (RetriesExhaustedException e) {
891       LOG.info("Scan done, expected exception caught: " + e.getClass());
892     }
893 
894     // Cache is updated with the right value.
895     Assert.assertNotNull(conn.getCachedLocation(TABLE_NAME, ROW));
896     Assert.assertEquals(
897       "Previous server was "+destServer.getServerName().getHostAndPort(),
898       curServer.getServerName().getPort(),
899       conn.getCachedLocation(TABLE_NAME, ROW).getRegionLocation().getPort());
900 
901     TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
902         HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
903     table.close();
904   }
905 
906   /**
907    * Test that Connection or Pool are not closed when managed externally
908    * @throws Exception
909    */
910   @Test
911   public void testConnectionManagement() throws Exception{
912     Table table0 = TEST_UTIL.createTable(TABLE_NAME1, FAM_NAM);
913     Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
914     HTable table = (HTable) conn.getTable(TABLE_NAME1);
915     table.close();
916     assertFalse(conn.isClosed());
917     assertFalse(table.getPool().isShutdown());
918     table = (HTable) conn.getTable(TABLE_NAME1);
919     table.close();
920     assertFalse(table.getPool().isShutdown());
921     conn.close();
922     assertTrue(table.getPool().isShutdown());
923     table0.close();
924   }
925 
926   /**
927    * Test that stale cache updates don't override newer cached values.
928    */
929   @Test
930   public void testCacheSeqNums() throws Exception{
931     HTable table = TEST_UTIL.createMultiRegionTable(TABLE_NAME2, FAM_NAM);
932     Put put = new Put(ROW);
933     put.add(FAM_NAM, ROW, ROW);
934     table.put(put);
935     ConnectionManager.HConnectionImplementation conn =
936       (ConnectionManager.HConnectionImplementation)table.getConnection();
937 
938     HRegionLocation location = conn.getCachedLocation(TABLE_NAME2, ROW).getRegionLocation();
939     assertNotNull(location);
940 
941     ServerName anySource = ServerName.valueOf(location.getHostname(), location.getPort() - 1, 0L);
942 
943     // Same server as already in cache reporting - overwrites any value despite seqNum.
944     int nextPort = location.getPort() + 1;
945     conn.updateCachedLocation(location.getRegionInfo(), location.getServerName(),
946         ServerName.valueOf("127.0.0.1", nextPort, 0), location.getSeqNum() - 1);
947     location = conn.getCachedLocation(TABLE_NAME2, ROW).getRegionLocation();
948     Assert.assertEquals(nextPort, location.getPort());
949 
950     // No source specified - same.
951     nextPort = location.getPort() + 1;
952     conn.updateCachedLocation(location.getRegionInfo(), location.getServerName(),
953         ServerName.valueOf("127.0.0.1", nextPort, 0), location.getSeqNum() - 1);
954     location = conn.getCachedLocation(TABLE_NAME2, ROW).getRegionLocation();
955     Assert.assertEquals(nextPort, location.getPort());
956 
957     // Higher seqNum - overwrites lower seqNum.
958     nextPort = location.getPort() + 1;
959     conn.updateCachedLocation(location.getRegionInfo(), anySource,
960         ServerName.valueOf("127.0.0.1", nextPort, 0), location.getSeqNum() + 1);
961     location = conn.getCachedLocation(TABLE_NAME2, ROW).getRegionLocation();
962     Assert.assertEquals(nextPort, location.getPort());
963 
964     // Lower seqNum - does not overwrite higher seqNum.
965     nextPort = location.getPort() + 1;
966     conn.updateCachedLocation(location.getRegionInfo(), anySource,
967         ServerName.valueOf("127.0.0.1", nextPort, 0), location.getSeqNum() - 1);
968     location = conn.getCachedLocation(TABLE_NAME2, ROW).getRegionLocation();
969     Assert.assertEquals(nextPort - 1, location.getPort());
970     table.close();
971   }
972 
973   /**
974    * Make sure that {@link Configuration} instances that are essentially the
975    * same map to the same {@link HConnection} instance.
976    */
977   @Test
978   public void testConnectionSameness() throws Exception {
979     Connection previousConnection = null;
980     for (int i = 0; i < 2; i++) {
981       // set random key to differentiate the connection from previous ones
982       Configuration configuration = TEST_UTIL.getConfiguration();
983       configuration.set("some_key", String.valueOf(_randy.nextInt()));
984       LOG.info("The hash code of the current configuration is: "
985           + configuration.hashCode());
986       Connection currentConnection = HConnectionManager
987           .getConnection(configuration);
988       if (previousConnection != null) {
989         assertTrue(
990             "Did not get the same connection even though its key didn't change",
991             previousConnection == currentConnection);
992       }
993       previousConnection = currentConnection;
994       // change the configuration, so that it is no longer reachable from the
995       // client's perspective. However, since its part of the LRU doubly linked
996       // list, it will eventually get thrown out, at which time it should also
997       // close the corresponding {@link HConnection}.
998       configuration.set("other_key", String.valueOf(_randy.nextInt()));
999     }
1000   }
1001 
1002   /**
1003    * Makes sure that there is no leaking of
1004    * {@link ConnectionManager.HConnectionImplementation} in the {@link HConnectionManager}
1005    * class.
1006    * @deprecated Tests deprecated functionality.  Remove in 1.0.
1007    */
1008   @Deprecated
1009   @Test
1010   public void testConnectionUniqueness() throws Exception {
1011     int zkmaxconnections = TEST_UTIL.getConfiguration().
1012       getInt(HConstants.ZOOKEEPER_MAX_CLIENT_CNXNS,
1013           HConstants.DEFAULT_ZOOKEPER_MAX_CLIENT_CNXNS);
1014     // Test up to a max that is < the maximum number of zk connections.  If we
1015     // go above zk connections, we just fall into cycle where we are failing
1016     // to set up a session and test runs for a long time.
1017     int maxConnections = Math.min(zkmaxconnections - 1, 20);
1018     List<HConnection> connections = new ArrayList<HConnection>(maxConnections);
1019     Connection previousConnection = null;
1020     try {
1021       for (int i = 0; i < maxConnections; i++) {
1022         // set random key to differentiate the connection from previous ones
1023         Configuration configuration = new Configuration(TEST_UTIL.getConfiguration());
1024         configuration.set("some_key", String.valueOf(_randy.nextInt()));
1025         configuration.set(HConstants.HBASE_CLIENT_INSTANCE_ID,
1026             String.valueOf(_randy.nextInt()));
1027         LOG.info("The hash code of the current configuration is: "
1028             + configuration.hashCode());
1029         HConnection currentConnection =
1030           HConnectionManager.getConnection(configuration);
1031         if (previousConnection != null) {
1032           assertTrue("Got the same connection even though its key changed!",
1033               previousConnection != currentConnection);
1034         }
1035         // change the configuration, so that it is no longer reachable from the
1036         // client's perspective. However, since its part of the LRU doubly linked
1037         // list, it will eventually get thrown out, at which time it should also
1038         // close the corresponding {@link HConnection}.
1039         configuration.set("other_key", String.valueOf(_randy.nextInt()));
1040 
1041         previousConnection = currentConnection;
1042         LOG.info("The current HConnectionManager#HBASE_INSTANCES cache size is: "
1043             + getHConnectionManagerCacheSize());
1044         Thread.sleep(50);
1045         connections.add(currentConnection);
1046       }
1047     } finally {
1048       for (Connection c: connections) {
1049         // Clean up connections made so we don't interfere w/ subsequent tests.
1050         HConnectionManager.deleteConnection(c.getConfiguration());
1051       }
1052     }
1053   }
1054 
1055   @Test
1056   public void testClosing() throws Exception {
1057     Configuration configuration =
1058       new Configuration(TEST_UTIL.getConfiguration());
1059     configuration.set(HConstants.HBASE_CLIENT_INSTANCE_ID,
1060         String.valueOf(_randy.nextInt()));
1061 
1062     Connection c1 = ConnectionFactory.createConnection(configuration);
1063     // We create two connections with the same key.
1064     Connection c2 = ConnectionFactory.createConnection(configuration);
1065 
1066     Connection c3 = HConnectionManager.getConnection(configuration);
1067     Connection c4 = HConnectionManager.getConnection(configuration);
1068     assertTrue(c3 == c4);
1069 
1070     c1.close();
1071     assertTrue(c1.isClosed());
1072     assertFalse(c2.isClosed());
1073     assertFalse(c3.isClosed());
1074 
1075     c3.close();
1076     // still a reference left
1077     assertFalse(c3.isClosed());
1078     c3.close();
1079     assertTrue(c3.isClosed());
1080     // c3 was removed from the cache
1081     Connection c5 = HConnectionManager.getConnection(configuration);
1082     assertTrue(c5 != c3);
1083 
1084     assertFalse(c2.isClosed());
1085     c2.close();
1086     assertTrue(c2.isClosed());
1087     c5.close();
1088     assertTrue(c5.isClosed());
1089   }
1090 
1091   /**
1092    * Trivial test to verify that nobody messes with
1093    * {@link HConnectionManager#createConnection(Configuration)}
1094    */
1095   @Test
1096   public void testCreateConnection() throws Exception {
1097     Configuration configuration = TEST_UTIL.getConfiguration();
1098     Connection c1 = ConnectionFactory.createConnection(configuration);
1099     Connection c2 = ConnectionFactory.createConnection(configuration);
1100     // created from the same configuration, yet they are different
1101     assertTrue(c1 != c2);
1102     assertTrue(c1.getConfiguration() == c2.getConfiguration());
1103     // make sure these were not cached
1104     Connection c3 = HConnectionManager.getConnection(configuration);
1105     assertTrue(c1 != c3);
1106     assertTrue(c2 != c3);
1107   }
1108 
1109 
1110   /**
1111    * This test checks that one can connect to the cluster with only the
1112    *  ZooKeeper quorum set. Other stuff like master address will be read
1113    *  from ZK by the client.
1114    */
1115   @Test
1116   public void testConnection() throws Exception{
1117     // We create an empty config and add the ZK address.
1118     Configuration c = new Configuration();
1119     c.set(HConstants.ZOOKEEPER_QUORUM,
1120       TEST_UTIL.getConfiguration().get(HConstants.ZOOKEEPER_QUORUM));
1121     c.set(HConstants.ZOOKEEPER_CLIENT_PORT ,
1122       TEST_UTIL.getConfiguration().get(HConstants.ZOOKEEPER_CLIENT_PORT));
1123 
1124     // This should be enough to connect
1125     HConnection conn = HConnectionManager.getConnection(c);
1126     assertTrue( conn.isMasterRunning() );
1127     conn.close();
1128   }
1129 
1130   private int setNumTries(HConnectionImplementation hci, int newVal) throws Exception {
1131     Field numTries = hci.getClass().getDeclaredField("numTries");
1132     numTries.setAccessible(true);
1133     Field modifiersField = Field.class.getDeclaredField("modifiers");
1134     modifiersField.setAccessible(true);
1135     modifiersField.setInt(numTries, numTries.getModifiers() & ~Modifier.FINAL);
1136     final int prevNumRetriesVal = (Integer)numTries.get(hci);
1137     numTries.set(hci, newVal);
1138 
1139     return prevNumRetriesVal;
1140   }
1141 
1142   @Test
1143   public void testMulti() throws Exception {
1144     HTable table = TEST_UTIL.createMultiRegionTable(TABLE_NAME3, FAM_NAM);
1145      try {
1146        ConnectionManager.HConnectionImplementation conn =
1147            ( ConnectionManager.HConnectionImplementation)table.getConnection();
1148 
1149        // We're now going to move the region and check that it works for the client
1150        // First a new put to add the location in the cache
1151        conn.clearRegionCache(TABLE_NAME3);
1152        Assert.assertEquals(0, conn.getNumberOfCachedRegionLocations(TABLE_NAME3));
1153 
1154        TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, false);
1155        HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster();
1156 
1157        // We can wait for all regions to be online, that makes log reading easier when debugging
1158        while (master.getAssignmentManager().getRegionStates().isRegionsInTransition()) {
1159          Thread.sleep(1);
1160        }
1161 
1162        Put put = new Put(ROW_X);
1163        put.add(FAM_NAM, ROW_X, ROW_X);
1164        table.put(put);
1165 
1166        // Now moving the region to the second server
1167        HRegionLocation toMove = conn.getCachedLocation(TABLE_NAME3, ROW_X).getRegionLocation();
1168        byte[] regionName = toMove.getRegionInfo().getRegionName();
1169        byte[] encodedRegionNameBytes = toMove.getRegionInfo().getEncodedNameAsBytes();
1170 
1171        // Choose the other server.
1172        int curServerId = TEST_UTIL.getHBaseCluster().getServerWith(regionName);
1173        int destServerId = (curServerId == 0 ? 1 : 0);
1174 
1175        HRegionServer curServer = TEST_UTIL.getHBaseCluster().getRegionServer(curServerId);
1176        HRegionServer destServer = TEST_UTIL.getHBaseCluster().getRegionServer(destServerId);
1177 
1178        ServerName destServerName = destServer.getServerName();
1179 
1180        //find another row in the cur server that is less than ROW_X
1181        List<Region> regions = curServer.getOnlineRegions(TABLE_NAME3);
1182        byte[] otherRow = null;
1183        for (Region region : regions) {
1184          if (!region.getRegionInfo().getEncodedName().equals(toMove.getRegionInfo().getEncodedName())
1185              && Bytes.BYTES_COMPARATOR.compare(region.getRegionInfo().getStartKey(), ROW_X) < 0) {
1186            otherRow = region.getRegionInfo().getStartKey();
1187            break;
1188          }
1189        }
1190        assertNotNull(otherRow);
1191        // If empty row, set it to first row.-f
1192        if (otherRow.length <= 0) otherRow = Bytes.toBytes("aaa");
1193        Put put2 = new Put(otherRow);
1194        put2.add(FAM_NAM, otherRow, otherRow);
1195        table.put(put2); //cache put2's location
1196 
1197        // Check that we are in the expected state
1198        Assert.assertTrue(curServer != destServer);
1199        Assert.assertNotEquals(curServer.getServerName(), destServer.getServerName());
1200        Assert.assertNotEquals(toMove.getPort(), destServerName.getPort());
1201        Assert.assertNotNull(curServer.getOnlineRegion(regionName));
1202        Assert.assertNull(destServer.getOnlineRegion(regionName));
1203        Assert.assertFalse(TEST_UTIL.getMiniHBaseCluster().getMaster().
1204            getAssignmentManager().getRegionStates().isRegionsInTransition());
1205 
1206        // Moving. It's possible that we don't have all the regions online at this point, so
1207        //  the test must depends only on the region we're looking at.
1208        LOG.info("Move starting region="+toMove.getRegionInfo().getRegionNameAsString());
1209        TEST_UTIL.getHBaseAdmin().move(
1210            toMove.getRegionInfo().getEncodedNameAsBytes(),
1211            destServerName.getServerName().getBytes()
1212            );
1213 
1214        while (destServer.getOnlineRegion(regionName) == null ||
1215            destServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes) ||
1216            curServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes) ||
1217            master.getAssignmentManager().getRegionStates().isRegionsInTransition()) {
1218          // wait for the move to be finished
1219          Thread.sleep(1);
1220         }
1221 
1222        LOG.info("Move finished for region="+toMove.getRegionInfo().getRegionNameAsString());
1223 
1224        // Check our new state.
1225        Assert.assertNull(curServer.getOnlineRegion(regionName));
1226        Assert.assertNotNull(destServer.getOnlineRegion(regionName));
1227        Assert.assertFalse(destServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes));
1228        Assert.assertFalse(curServer.getRegionsInTransitionInRS().containsKey(encodedRegionNameBytes));
1229 
1230 
1231        // Cache was NOT updated and points to the wrong server
1232        Assert.assertFalse(
1233            conn.getCachedLocation(TABLE_NAME3, ROW_X).getRegionLocation()
1234             .getPort() == destServerName.getPort());
1235 
1236        // Hijack the number of retry to fail after 2 tries
1237        final int prevNumRetriesVal = setNumTries(conn, 2);
1238 
1239        Put put3 = new Put(ROW_X);
1240        put3.add(FAM_NAM, ROW_X, ROW_X);
1241        Put put4 = new Put(otherRow);
1242        put4.add(FAM_NAM, otherRow, otherRow);
1243 
1244        // do multi
1245        table.batch(Lists.newArrayList(put4, put3)); // first should be a valid row,
1246        // second we get RegionMovedException.
1247 
1248        setNumTries(conn, prevNumRetriesVal);
1249      } finally {
1250        table.close();
1251      }
1252   }
1253 
1254   @Test
1255   public void testErrorBackoffTimeCalculation() throws Exception {
1256     // TODO: This test would seem to presume hardcoded RETRY_BACKOFF which it should not.
1257     final long ANY_PAUSE = 100;
1258     ServerName location = ServerName.valueOf("127.0.0.1", 1, 0);
1259     ServerName diffLocation = ServerName.valueOf("127.0.0.1", 2, 0);
1260 
1261     ManualEnvironmentEdge timeMachine = new ManualEnvironmentEdge();
1262     EnvironmentEdgeManager.injectEdge(timeMachine);
1263     try {
1264       long timeBase = timeMachine.currentTime();
1265       long largeAmountOfTime = ANY_PAUSE * 1000;
1266       ConnectionManager.ServerErrorTracker tracker =
1267           new ConnectionManager.ServerErrorTracker(largeAmountOfTime, 100);
1268 
1269       // The default backoff is 0.
1270       assertEquals(0, tracker.calculateBackoffTime(location, ANY_PAUSE));
1271 
1272       // Check some backoff values from HConstants sequence.
1273       tracker.reportServerError(location);
1274       assertEqualsWithJitter(ANY_PAUSE * HConstants.RETRY_BACKOFF[0],
1275         tracker.calculateBackoffTime(location, ANY_PAUSE));
1276       tracker.reportServerError(location);
1277       tracker.reportServerError(location);
1278       tracker.reportServerError(location);
1279       assertEqualsWithJitter(ANY_PAUSE * HConstants.RETRY_BACKOFF[3],
1280         tracker.calculateBackoffTime(location, ANY_PAUSE));
1281 
1282       // All of this shouldn't affect backoff for different location.
1283       assertEquals(0, tracker.calculateBackoffTime(diffLocation, ANY_PAUSE));
1284       tracker.reportServerError(diffLocation);
1285       assertEqualsWithJitter(ANY_PAUSE * HConstants.RETRY_BACKOFF[0],
1286         tracker.calculateBackoffTime(diffLocation, ANY_PAUSE));
1287 
1288       // Check with different base.
1289       assertEqualsWithJitter(ANY_PAUSE * 2 * HConstants.RETRY_BACKOFF[3],
1290           tracker.calculateBackoffTime(location, ANY_PAUSE * 2));
1291     } finally {
1292       EnvironmentEdgeManager.reset();
1293     }
1294   }
1295 
1296   private static void assertEqualsWithJitter(long expected, long actual) {
1297     assertEqualsWithJitter(expected, actual, expected);
1298   }
1299 
1300   private static void assertEqualsWithJitter(long expected, long actual, long jitterBase) {
1301     assertTrue("Value not within jitter: " + expected + " vs " + actual,
1302         Math.abs(actual - expected) <= (0.01f * jitterBase));
1303   }
1304 
1305   /**
1306    * Tests that a destroyed connection does not have a live zookeeper.
1307    * Below is timing based.  We put up a connection to a table and then close the connection while
1308    * having a background thread running that is forcing close of the connection to try and
1309    * provoke a close catastrophe; we are hoping for a car crash so we can see if we are leaking
1310    * zk connections.
1311    * @throws Exception
1312    */
1313   @Ignore ("Flakey test: See HBASE-8996")@Test
1314   public void testDeleteForZKConnLeak() throws Exception {
1315     TEST_UTIL.createTable(TABLE_NAME4, FAM_NAM);
1316     final Configuration config = HBaseConfiguration.create(TEST_UTIL.getConfiguration());
1317     config.setInt("zookeeper.recovery.retry", 1);
1318     config.setInt("zookeeper.recovery.retry.intervalmill", 1000);
1319     config.setInt("hbase.rpc.timeout", 2000);
1320     config.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
1321 
1322     ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 10,
1323       5, TimeUnit.SECONDS,
1324       new SynchronousQueue<Runnable>(),
1325       Threads.newDaemonThreadFactory("test-hcm-delete"));
1326 
1327     pool.submit(new Runnable() {
1328       @Override
1329       public void run() {
1330         while (!Thread.interrupted()) {
1331           try {
1332             HConnection conn = HConnectionManager.getConnection(config);
1333             LOG.info("Connection " + conn);
1334             HConnectionManager.deleteStaleConnection(conn);
1335             LOG.info("Connection closed " + conn);
1336             // TODO: This sleep time should be less than the time that it takes to open and close
1337             // a table.  Ideally we would do a few runs first to measure.  For now this is
1338             // timing based; hopefully we hit the bad condition.
1339             Threads.sleep(10);
1340           } catch (Exception e) {
1341           }
1342         }
1343       }
1344     });
1345 
1346     // Use connection multiple times.
1347     for (int i = 0; i < 30; i++) {
1348       Connection c1 = null;
1349       try {
1350         c1 = ConnectionManager.getConnectionInternal(config);
1351         LOG.info("HTable connection " + i + " " + c1);
1352         Table table = new HTable(config, TABLE_NAME4, pool);
1353         table.close();
1354         LOG.info("HTable connection " + i + " closed " + c1);
1355       } catch (Exception e) {
1356         LOG.info("We actually want this to happen!!!!  So we can see if we are leaking zk", e);
1357       } finally {
1358         if (c1 != null) {
1359           if (c1.isClosed()) {
1360             // cannot use getZooKeeper as method instantiates watcher if null
1361             Field zkwField = c1.getClass().getDeclaredField("keepAliveZookeeper");
1362             zkwField.setAccessible(true);
1363             Object watcher = zkwField.get(c1);
1364 
1365             if (watcher != null) {
1366               if (((ZooKeeperWatcher)watcher).getRecoverableZooKeeper().getState().isAlive()) {
1367                 // non-synchronized access to watcher; sleep and check again in case zk connection
1368                 // hasn't been cleaned up yet.
1369                 Thread.sleep(1000);
1370                 if (((ZooKeeperWatcher) watcher).getRecoverableZooKeeper().getState().isAlive()) {
1371                   pool.shutdownNow();
1372                   fail("Live zookeeper in closed connection");
1373                 }
1374               }
1375             }
1376           }
1377           c1.close();
1378         }
1379       }
1380     }
1381     pool.shutdownNow();
1382   }
1383 
1384   @Test
1385   public void testConnectionRideOverClusterRestart() throws IOException, InterruptedException {
1386     Configuration config = new Configuration(TEST_UTIL.getConfiguration());
1387 
1388     TableName tableName = TableName.valueOf("testConnectionRideOverClusterRestart");
1389     TEST_UTIL.createTable(tableName.getName(), new byte[][] {FAM_NAM}, config).close();
1390 
1391     Connection connection = ConnectionFactory.createConnection(config);
1392     Table table = connection.getTable(tableName);
1393 
1394     // this will cache the meta location and table's region location
1395     table.get(new Get(Bytes.toBytes("foo")));
1396 
1397     // restart HBase
1398     TEST_UTIL.shutdownMiniHBaseCluster();
1399     TEST_UTIL.restartHBaseCluster(2);
1400     // this should be able to discover new locations for meta and table's region
1401     table.get(new Get(Bytes.toBytes("foo")));
1402     TEST_UTIL.deleteTable(tableName);
1403     table.close();
1404     connection.close();
1405   }
1406 }