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.regionserver;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertNotNull;
023import static org.junit.Assert.assertTrue;
024
025import java.io.IOException;
026import java.util.List;
027import java.util.Optional;
028import java.util.concurrent.CompletableFuture;
029import java.util.concurrent.ExecutorService;
030import java.util.concurrent.Executors;
031import java.util.concurrent.atomic.AtomicInteger;
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.fs.FileSystem;
034import org.apache.hadoop.fs.Path;
035import org.apache.hadoop.hbase.HBaseClassTestRule;
036import org.apache.hadoop.hbase.HBaseTestingUtil;
037import org.apache.hadoop.hbase.HConstants;
038import org.apache.hadoop.hbase.SingleProcessHBaseCluster;
039import org.apache.hadoop.hbase.StartTestingClusterOption;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.Waiter;
042import org.apache.hadoop.hbase.client.Admin;
043import org.apache.hadoop.hbase.client.Durability;
044import org.apache.hadoop.hbase.client.Put;
045import org.apache.hadoop.hbase.client.RegionInfo;
046import org.apache.hadoop.hbase.client.Table;
047import org.apache.hadoop.hbase.client.TableDescriptor;
048import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
049import org.apache.hadoop.hbase.coprocessor.CoreCoprocessor;
050import org.apache.hadoop.hbase.coprocessor.HasRegionServerServices;
051import org.apache.hadoop.hbase.coprocessor.ObserverContext;
052import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
053import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
054import org.apache.hadoop.hbase.coprocessor.RegionObserver;
055import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessor;
056import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
057import org.apache.hadoop.hbase.coprocessor.RegionServerObserver;
058import org.apache.hadoop.hbase.testclassification.MediumTests;
059import org.apache.hadoop.hbase.testclassification.RegionServerTests;
060import org.apache.hadoop.hbase.util.Bytes;
061import org.apache.hadoop.hbase.util.JVMClusterUtil;
062import org.apache.hadoop.hbase.wal.WAL;
063import org.apache.hadoop.hbase.wal.WALEdit;
064import org.apache.hadoop.hdfs.DFSConfigKeys;
065import org.apache.hadoop.hdfs.MiniDFSCluster;
066import org.junit.After;
067import org.junit.Before;
068import org.junit.ClassRule;
069import org.junit.Test;
070import org.junit.experimental.categories.Category;
071import org.slf4j.Logger;
072import org.slf4j.LoggerFactory;
073
074/**
075 * Tests around regionserver shutdown and abort
076 */
077@Category({RegionServerTests.class, MediumTests.class})
078public class TestRegionServerAbort {
079
080  @ClassRule
081  public static final HBaseClassTestRule CLASS_RULE =
082      HBaseClassTestRule.forClass(TestRegionServerAbort.class);
083
084  private static final byte[] FAMILY_BYTES = Bytes.toBytes("f");
085
086  private static final Logger LOG = LoggerFactory.getLogger(TestRegionServerAbort.class);
087
088  private HBaseTestingUtil testUtil;
089  private Configuration conf;
090  private MiniDFSCluster dfsCluster;
091  private SingleProcessHBaseCluster cluster;
092
093  @Before
094  public void setup() throws Exception {
095    testUtil = new HBaseTestingUtil();
096    conf = testUtil.getConfiguration();
097    conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY,
098        StopBlockingRegionObserver.class.getName());
099    conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
100        StopBlockingRegionObserver.class.getName());
101    // make sure we have multiple blocks so that the client does not prefetch all block locations
102    conf.set("dfs.blocksize", Long.toString(100 * 1024));
103    // prefetch the first block
104    conf.set(DFSConfigKeys.DFS_CLIENT_READ_PREFETCH_SIZE_KEY, Long.toString(100 * 1024));
105    conf.set(HConstants.REGION_IMPL, ErrorThrowingHRegion.class.getName());
106
107    testUtil.startMiniZKCluster();
108    dfsCluster = testUtil.startMiniDFSCluster(2);
109    StartTestingClusterOption option =
110      StartTestingClusterOption.builder().numRegionServers(2).build();
111    cluster = testUtil.startMiniHBaseCluster(option);
112  }
113
114  @After
115  public void tearDown() throws Exception {
116    String className = StopBlockingRegionObserver.class.getName();
117    for (JVMClusterUtil.RegionServerThread t : cluster.getRegionServerThreads()) {
118      HRegionServer rs = t.getRegionServer();
119      RegionServerCoprocessorHost cpHost = rs.getRegionServerCoprocessorHost();
120      StopBlockingRegionObserver cp = (StopBlockingRegionObserver)cpHost.findCoprocessor(className);
121      cp.setStopAllowed(true);
122    }
123    testUtil.shutdownMiniCluster();
124  }
125
126  /**
127   * Test that a regionserver is able to abort properly, even when a coprocessor
128   * throws an exception in preStopRegionServer().
129   */
130  @Test
131  public void testAbortFromRPC() throws Exception {
132    TableName tableName = TableName.valueOf("testAbortFromRPC");
133    // create a test table
134    Table table = testUtil.createTable(tableName, FAMILY_BYTES);
135
136    // write some edits
137    testUtil.loadTable(table, FAMILY_BYTES);
138    LOG.info("Wrote data");
139    // force a flush
140    cluster.flushcache(tableName);
141    LOG.info("Flushed table");
142
143    // Send a poisoned put to trigger the abort
144    Put put = new Put(new byte[]{0, 0, 0, 0});
145    put.addColumn(FAMILY_BYTES, Bytes.toBytes("c"), new byte[]{});
146    put.setAttribute(StopBlockingRegionObserver.DO_ABORT, new byte[]{1});
147
148    List<HRegion> regions = cluster.findRegionsForTable(tableName);
149    HRegion firstRegion = cluster.findRegionsForTable(tableName).get(0);
150    table.put(put);
151    // Verify that the regionserver is stopped
152    assertNotNull(firstRegion);
153    assertNotNull(firstRegion.getRegionServerServices());
154    LOG.info("isAborted = " + firstRegion.getRegionServerServices().isAborted());
155    assertTrue(firstRegion.getRegionServerServices().isAborted());
156    LOG.info("isStopped = " + firstRegion.getRegionServerServices().isStopped());
157    assertTrue(firstRegion.getRegionServerServices().isStopped());
158  }
159
160  /**
161   * Test that a coprocessor is able to override a normal regionserver stop request.
162   */
163  @Test
164  public void testStopOverrideFromCoprocessor() throws Exception {
165    Admin admin = testUtil.getAdmin();
166    HRegionServer regionserver = cluster.getRegionServer(0);
167    admin.stopRegionServer(regionserver.getServerName().getAddress().toString());
168
169    // regionserver should have failed to stop due to coprocessor
170    assertFalse(cluster.getRegionServer(0).isAborted());
171    assertFalse(cluster.getRegionServer(0).isStopped());
172  }
173
174  /**
175   * Tests that only a single abort is processed when multiple aborts are requested.
176   */
177  @Test
178  public void testMultiAbort() {
179    assertTrue(cluster.getRegionServerThreads().size() > 0);
180    JVMClusterUtil.RegionServerThread t = cluster.getRegionServerThreads().get(0);
181    assertTrue(t.isAlive());
182    HRegionServer rs = t.getRegionServer();
183    assertFalse(rs.isAborted());
184    RegionServerCoprocessorHost cpHost = rs.getRegionServerCoprocessorHost();
185    StopBlockingRegionObserver cp = (StopBlockingRegionObserver)cpHost.findCoprocessor(
186        StopBlockingRegionObserver.class.getName());
187    // Enable clean abort.
188    cp.setStopAllowed(true);
189    // Issue two aborts in quick succession.
190    // We need a thread pool here, otherwise the abort() runs into SecurityException when running
191    // from the fork join pool when setting the context classloader.
192    ExecutorService executor = Executors.newFixedThreadPool(2);
193    try {
194      CompletableFuture.runAsync(() -> rs.abort("Abort 1"), executor);
195      CompletableFuture.runAsync(() -> rs.abort("Abort 2"), executor);
196      long testTimeoutMs = 10 * 1000;
197      Waiter.waitFor(cluster.getConf(), testTimeoutMs, (Waiter.Predicate<Exception>) rs::isStopped);
198      // Make sure only one abort is received.
199      assertEquals(1, cp.getNumAbortsRequested());
200    } finally {
201      executor.shutdownNow();
202    }
203  }
204
205  @CoreCoprocessor
206  public static class StopBlockingRegionObserver
207      implements RegionServerCoprocessor, RegionCoprocessor, RegionServerObserver, RegionObserver {
208    public static final String DO_ABORT = "DO_ABORT";
209    private boolean stopAllowed;
210    private AtomicInteger abortCount = new AtomicInteger();
211
212    @Override
213    public Optional<RegionObserver> getRegionObserver() {
214      return Optional.of(this);
215    }
216
217    @Override
218    public Optional<RegionServerObserver> getRegionServerObserver() {
219      return Optional.of(this);
220    }
221
222    @Override
223    public void prePut(ObserverContext<RegionCoprocessorEnvironment> c, Put put, WALEdit edit,
224                       Durability durability) throws IOException {
225      if (put.getAttribute(DO_ABORT) != null) {
226        // TODO: Change this so it throws a CP Abort Exception instead.
227        RegionServerServices rss =
228            ((HasRegionServerServices)c.getEnvironment()).getRegionServerServices();
229        String str = "Aborting for test";
230        LOG.info(str  + " " + rss.getServerName());
231        rss.abort(str, new Throwable(str));
232      }
233    }
234
235    @Override
236    public void preStopRegionServer(ObserverContext<RegionServerCoprocessorEnvironment> env)
237        throws IOException {
238      abortCount.incrementAndGet();
239      if (!stopAllowed) {
240        throw new IOException("Stop not allowed");
241      }
242    }
243
244    public int getNumAbortsRequested() {
245      return abortCount.get();
246    }
247
248    public void setStopAllowed(boolean allowed) {
249      this.stopAllowed = allowed;
250    }
251  }
252
253  /**
254   * Throws an exception during store file refresh in order to trigger a regionserver abort.
255   */
256  public static class ErrorThrowingHRegion extends HRegion {
257    public ErrorThrowingHRegion(Path tableDir, WAL wal, FileSystem fs, Configuration confParam,
258                                RegionInfo regionInfo, TableDescriptor htd,
259                                RegionServerServices rsServices) {
260      super(tableDir, wal, fs, confParam, regionInfo, htd, rsServices);
261    }
262
263    public ErrorThrowingHRegion(HRegionFileSystem fs, WAL wal, Configuration confParam,
264                                TableDescriptor htd, RegionServerServices rsServices) {
265      super(fs, wal, confParam, htd, rsServices);
266    }
267
268    @Override
269    protected boolean refreshStoreFiles(boolean force) throws IOException {
270      // forced when called through RegionScannerImpl.handleFileNotFound()
271      if (force) {
272        throw new IOException("Failing file refresh for testing");
273      }
274      return super.refreshStoreFiles(force);
275    }
276  }
277}