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    AsyncRegistry registry = AsyncRegistryFactory.getRegistry(TEST_UTIL.getConfiguration());
102    CONN = new AsyncConnectionImpl(TEST_UTIL.getConfiguration(), registry,
103      registry.getClusterId().get(), User.getCurrent());
104    LOCATOR = CONN.getLocator();
105  }
106
107  @AfterClass
108  public static void tearDown() throws Exception {
109    IOUtils.closeQuietly(CONN);
110    TEST_UTIL.shutdownMiniCluster();
111  }
112
113  @After
114  public void tearDownAfterTest() {
115    LOCATOR.clearCache();
116  }
117
118  @Test
119  public void testTimeout() throws InterruptedException, ExecutionException {
120    SLEEP_MS = 1000;
121    long startNs = System.nanoTime();
122    try {
123      LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
124        TimeUnit.MILLISECONDS.toNanos(500)).get();
125      fail();
126    } catch (ExecutionException e) {
127      assertThat(e.getCause(), instanceOf(TimeoutIOException.class));
128    }
129    long costMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
130    assertTrue(costMs >= 500);
131    assertTrue(costMs < 1000);
132    // wait for the background task finish
133    Thread.sleep(2000);
134    // Now the location should be in cache, so we will not visit meta again.
135    HRegionLocation loc = LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW,
136      RegionLocateType.CURRENT, TimeUnit.MILLISECONDS.toNanos(500)).get();
137    assertEquals(loc.getServerName(),
138      TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName());
139  }
140
141  @Test
142  public void testNoCompletionException() {
143    // make sure that we do not get CompletionException
144    SLEEP_MS = 0;
145    AtomicReference<Throwable> errorHolder = new AtomicReference<>();
146    try {
147      LOCATOR.getRegionLocation(TableName.valueOf("NotExist"), EMPTY_START_ROW,
148        RegionLocateType.CURRENT, TimeUnit.SECONDS.toNanos(1))
149        .whenComplete((r, e) -> errorHolder.set(e)).join();
150      fail();
151    } catch (CompletionException e) {
152      // join will return a CompletionException, which is OK
153      assertThat(e.getCause(), instanceOf(TableNotFoundException.class));
154    }
155    // but we need to make sure that we do not get a CompletionException in the callback
156    assertThat(errorHolder.get(), instanceOf(TableNotFoundException.class));
157  }
158}