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.master.procedure;
019
020import java.io.IOException;
021import java.io.UncheckedIOException;
022import java.util.concurrent.CountDownLatch;
023import java.util.concurrent.Future;
024import java.util.concurrent.TimeUnit;
025import org.apache.hadoop.conf.Configuration;
026import org.apache.hadoop.hbase.HBaseClassTestRule;
027import org.apache.hadoop.hbase.HBaseTestingUtil;
028import org.apache.hadoop.hbase.StartTestingClusterOption;
029import org.apache.hadoop.hbase.TableName;
030import org.apache.hadoop.hbase.client.Admin;
031import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
032import org.apache.hadoop.hbase.client.Put;
033import org.apache.hadoop.hbase.client.Table;
034import org.apache.hadoop.hbase.client.TableDescriptor;
035import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
036import org.apache.hadoop.hbase.master.HMaster;
037import org.apache.hadoop.hbase.master.assignment.AssignmentManager;
038import org.apache.hadoop.hbase.procedure2.Procedure;
039import org.apache.hadoop.hbase.testclassification.MasterTests;
040import org.apache.hadoop.hbase.testclassification.MediumTests;
041import org.apache.hadoop.hbase.util.Bytes;
042import org.apache.hadoop.metrics2.impl.JmxCacheBuster;
043import org.junit.AfterClass;
044import org.junit.BeforeClass;
045import org.junit.ClassRule;
046import org.junit.Test;
047import org.junit.experimental.categories.Category;
048import org.slf4j.Logger;
049import org.slf4j.LoggerFactory;
050
051import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProcedureProtos.CreateTableState;
052
053@Category({ MasterTests.class, MediumTests.class })
054public class TestCreateTableNoRegionServer {
055
056  @ClassRule
057  public static final HBaseClassTestRule CLASS_RULE =
058    HBaseClassTestRule.forClass(TestCreateTableNoRegionServer.class);
059
060  private static final Logger LOG = LoggerFactory.getLogger(TestCreateTableNoRegionServer.class);
061
062  private static final HBaseTestingUtil UTIL = new HBaseTestingUtil();
063
064  private static TableName TABLE_NAME = TableName.valueOf("test");
065
066  private static byte[] FAMILY = Bytes.toBytes("f1");
067
068  private static CountDownLatch ARRIVE;
069
070  private static CountDownLatch RESUME;
071
072  public static final class HMasterForTest extends HMaster {
073
074    public HMasterForTest(Configuration conf) throws IOException {
075      super(conf);
076    }
077
078    private boolean isInAssignRegionsState() {
079      try {
080        for (StackTraceElement e : Thread.currentThread().getStackTrace()) {
081          if (
082            e.getClassName().equals(CreateTableProcedure.class.getName())
083              && e.getMethodName().equals("executeFromState")
084          ) {
085            for (Procedure<?> proc : getProcedures()) {
086              if (
087                proc instanceof CreateTableProcedure && !proc.isFinished()
088                  && ((CreateTableProcedure) proc).getCurrentStateId()
089                      == CreateTableState.CREATE_TABLE_ASSIGN_REGIONS_VALUE
090              ) {
091                return true;
092              }
093            }
094          }
095        }
096      } catch (IOException e) {
097        throw new UncheckedIOException(e);
098      }
099      return false;
100    }
101
102    @Override
103    public AssignmentManager getAssignmentManager() {
104      if (ARRIVE != null && isInAssignRegionsState()) {
105        ARRIVE.countDown();
106        ARRIVE = null;
107        try {
108          RESUME.await();
109        } catch (InterruptedException e) {
110        }
111      }
112      return super.getAssignmentManager();
113    }
114  }
115
116  @BeforeClass
117  public static void setUp() throws Exception {
118    UTIL.startMiniCluster(
119      StartTestingClusterOption.builder().masterClass(HMasterForTest.class).build());
120    // this may cause dead lock if there is no live region server and want to start a new server.
121    // In JmxCacheBuster we will reinitialize the metrics system so it will get some metrics which
122    // will need to access meta, since there is no region server, the request will hang there for a
123    // long time while holding the lock of MetricsSystemImpl, but when start a new region server, we
124    // also need to update metrics in handleReportForDutyResponse, since we are all in the same
125    // process and uses the same metrics instance, we hit dead lock.
126    JmxCacheBuster.stop();
127  }
128
129  @AfterClass
130  public static void tearDown() throws Exception {
131    UTIL.shutdownMiniCluster();
132  }
133
134  @Test
135  public void testCreate() throws Exception {
136    TableDescriptor td = TableDescriptorBuilder.newBuilder(TABLE_NAME)
137      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILY)).build();
138    Admin admin = UTIL.getAdmin();
139    ARRIVE = new CountDownLatch(1);
140    RESUME = new CountDownLatch(1);
141    Future<Void> future = admin.createTableAsync(td);
142    ARRIVE.await();
143
144    UTIL.getMiniHBaseCluster().stopRegionServer(0).join();
145
146    // make sure we the region server is done.
147    UTIL.waitFor(30000,
148      () -> UTIL.getMiniHBaseCluster().getMaster().getServerManager().getOnlineServers().isEmpty());
149    RESUME.countDown();
150
151    Thread.sleep(10000);
152    // the procedure should still be in the CREATE_TABLE_ASSIGN_REGIONS state, but here, we just
153    // warn it as it may cause more serious problem later.
154    for (Procedure<?> proc : UTIL.getMiniHBaseCluster().getMaster().getProcedures()) {
155      if (
156        proc instanceof CreateTableProcedure && !proc.isFinished()
157          && ((CreateTableProcedure) proc).getCurrentStateId()
158              != CreateTableState.CREATE_TABLE_ASSIGN_REGIONS_VALUE
159      ) {
160        LOG.warn("Create table procedure {} assigned regions without a region server!", proc);
161      }
162    }
163    UTIL.getMiniHBaseCluster().startRegionServer();
164    // the creation should finally be done
165    future.get(30, TimeUnit.SECONDS);
166    // make sure we could put to the table
167    try (Table table =
168      UTIL.getConnection().getTableBuilder(TABLE_NAME, null).setOperationTimeout(5000).build()) {
169      table.put(new Put(Bytes.toBytes(0)).addColumn(FAMILY, Bytes.toBytes("q"), Bytes.toBytes(0)));
170    }
171  }
172}