001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import static org.apache.hadoop.hbase.HConstants.EMPTY_START_ROW;
021import static org.apache.hadoop.hbase.HConstants.HBASE_CLIENT_META_OPERATION_TIMEOUT;
022import static org.apache.hadoop.hbase.coprocessor.CoprocessorHost.REGION_COPROCESSOR_CONF_KEY;
023import static org.hamcrest.CoreMatchers.instanceOf;
024import static org.junit.Assert.assertEquals;
025import static org.junit.Assert.assertThat;
026import static org.junit.Assert.assertTrue;
027import static org.junit.Assert.fail;
028
029import java.io.IOException;
030import java.util.Optional;
031import java.util.concurrent.CompletionException;
032import java.util.concurrent.ExecutionException;
033import java.util.concurrent.TimeUnit;
034import java.util.concurrent.atomic.AtomicReference;
035import org.apache.commons.io.IOUtils;
036import org.apache.hadoop.conf.Configuration;
037import org.apache.hadoop.hbase.HBaseClassTestRule;
038import org.apache.hadoop.hbase.HBaseTestingUtility;
039import org.apache.hadoop.hbase.HRegionLocation;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.TableNotFoundException;
042import org.apache.hadoop.hbase.coprocessor.ObserverContext;
043import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
044import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
045import org.apache.hadoop.hbase.coprocessor.RegionObserver;
046import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
047import org.apache.hadoop.hbase.security.User;
048import org.apache.hadoop.hbase.testclassification.ClientTests;
049import org.apache.hadoop.hbase.testclassification.MediumTests;
050import org.apache.hadoop.hbase.util.Bytes;
051import org.apache.hadoop.hbase.util.Threads;
052import org.junit.After;
053import org.junit.AfterClass;
054import org.junit.BeforeClass;
055import org.junit.ClassRule;
056import org.junit.Test;
057import org.junit.experimental.categories.Category;
058
059@Category({ MediumTests.class, ClientTests.class })
060public class TestAsyncRegionLocator {
061
062  @ClassRule
063  public static final HBaseClassTestRule CLASS_RULE =
064    HBaseClassTestRule.forClass(TestAsyncRegionLocator.class);
065
066  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
067
068  private static TableName TABLE_NAME = TableName.valueOf("async");
069
070  private static byte[] FAMILY = Bytes.toBytes("cf");
071
072  private static AsyncConnectionImpl CONN;
073
074  private static AsyncRegionLocator LOCATOR;
075
076  private static volatile long SLEEP_MS = 0L;
077
078  public static class SleepRegionObserver implements RegionCoprocessor, RegionObserver {
079    @Override
080    public Optional<RegionObserver> getRegionObserver() {
081      return Optional.of(this);
082    }
083
084    @Override
085    public void preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> e, Scan scan)
086        throws IOException {
087      if (SLEEP_MS > 0) {
088        Threads.sleepWithoutInterrupt(SLEEP_MS);
089      }
090    }
091  }
092
093  @BeforeClass
094  public static void setUp() throws Exception {
095    Configuration conf = TEST_UTIL.getConfiguration();
096    conf.set(REGION_COPROCESSOR_CONF_KEY, SleepRegionObserver.class.getName());
097    conf.setLong(HBASE_CLIENT_META_OPERATION_TIMEOUT, 2000);
098    TEST_UTIL.startMiniCluster(1);
099    TEST_UTIL.createTable(TABLE_NAME, FAMILY);
100    TEST_UTIL.waitTableAvailable(TABLE_NAME);
101    ConnectionRegistry registry =
102        ConnectionRegistryFactory.getRegistry(TEST_UTIL.getConfiguration());
103    CONN = new AsyncConnectionImpl(TEST_UTIL.getConfiguration(), registry,
104      registry.getClusterId().get(), User.getCurrent());
105    LOCATOR = CONN.getLocator();
106  }
107
108  @AfterClass
109  public static void tearDown() throws Exception {
110    IOUtils.closeQuietly(CONN);
111    TEST_UTIL.shutdownMiniCluster();
112  }
113
114  @After
115  public void tearDownAfterTest() {
116    LOCATOR.clearCache();
117  }
118
119  @Test
120  public void testTimeout() throws InterruptedException, ExecutionException {
121    SLEEP_MS = 1000;
122    long startNs = System.nanoTime();
123    try {
124      LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
125        TimeUnit.MILLISECONDS.toNanos(500)).get();
126      fail();
127    } catch (ExecutionException e) {
128      assertThat(e.getCause(), instanceOf(TimeoutIOException.class));
129    }
130    long costMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
131    assertTrue(costMs >= 500);
132    assertTrue(costMs < 1000);
133    // wait for the background task finish
134    Thread.sleep(2000);
135    // Now the location should be in cache, so we will not visit meta again.
136    HRegionLocation loc = LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW,
137      RegionLocateType.CURRENT, TimeUnit.MILLISECONDS.toNanos(500)).get();
138    assertEquals(loc.getServerName(),
139      TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName());
140  }
141
142  @Test
143  public void testNoCompletionException() {
144    // make sure that we do not get CompletionException
145    SLEEP_MS = 0;
146    AtomicReference<Throwable> errorHolder = new AtomicReference<>();
147    try {
148      LOCATOR.getRegionLocation(TableName.valueOf("NotExist"), EMPTY_START_ROW,
149        RegionLocateType.CURRENT, TimeUnit.SECONDS.toNanos(1))
150        .whenComplete((r, e) -> errorHolder.set(e)).join();
151      fail();
152    } catch (CompletionException e) {
153      // join will return a CompletionException, which is OK
154      assertThat(e.getCause(), instanceOf(TableNotFoundException.class));
155    }
156    // but we need to make sure that we do not get a CompletionException in the callback
157    assertThat(errorHolder.get(), instanceOf(TableNotFoundException.class));
158  }
159}