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  
20  package org.apache.hadoop.hbase.tool;
21  
22  import com.google.common.collect.Iterables;
23  
24  import org.apache.hadoop.hbase.HBaseTestingUtility;
25  import org.apache.hadoop.hbase.HColumnDescriptor;
26  import org.apache.hadoop.hbase.HConstants;
27  import org.apache.hadoop.hbase.HRegionInfo;
28  import org.apache.hadoop.hbase.ServerName;
29  import org.apache.hadoop.hbase.TableName;
30  import org.apache.hadoop.hbase.client.HTable;
31  import org.apache.hadoop.hbase.client.Put;
32  import org.apache.hadoop.hbase.client.Table;
33  import org.apache.hadoop.hbase.testclassification.MediumTests;
34  import org.apache.hadoop.hbase.util.Bytes;
35  import org.apache.hadoop.util.ToolRunner;
36  import org.apache.log4j.Appender;
37  import org.apache.log4j.LogManager;
38  import org.apache.log4j.spi.LoggingEvent;
39  
40  import org.junit.After;
41  import org.junit.Before;
42  import org.junit.Ignore;
43  import org.junit.Test;
44  import org.junit.experimental.categories.Category;
45  import org.junit.runner.RunWith;
46  import org.mockito.ArgumentMatcher;
47  import org.mockito.Mock;
48  import org.mockito.runners.MockitoJUnitRunner;
49  
50  import java.util.Map;
51  import java.util.concurrent.ExecutorService;
52  import java.util.concurrent.ScheduledThreadPoolExecutor;
53  
54  import static org.junit.Assert.assertEquals;
55  import static org.junit.Assert.assertFalse;
56  import static org.junit.Assert.assertNotEquals;
57  import static org.junit.Assert.assertNotNull;
58  import static org.junit.Assert.assertTrue;
59  import static org.mockito.Matchers.anyLong;
60  import static org.mockito.Matchers.eq;
61  import static org.mockito.Matchers.isA;
62  import static org.mockito.Matchers.argThat;
63  import static org.mockito.Mockito.*;
64  
65  @RunWith(MockitoJUnitRunner.class)
66  @Category({MediumTests.class})
67  public class TestCanaryTool {
68  
69    private HBaseTestingUtility testingUtility;
70    private static final byte[] FAMILY = Bytes.toBytes("f");
71    private static final byte[] COLUMN = Bytes.toBytes("col");
72  
73    @Before
74    public void setUp() throws Exception {
75      testingUtility = new HBaseTestingUtility();
76      testingUtility.startMiniCluster();
77      LogManager.getRootLogger().addAppender(mockAppender);
78    }
79  
80    @After
81    public void tearDown() throws Exception {
82      testingUtility.shutdownMiniCluster();
83      LogManager.getRootLogger().removeAppender(mockAppender);
84    }
85  
86    @Mock
87    Appender mockAppender;
88  
89    @Test
90    public void testBasicZookeeperCanaryWorks() throws Exception {
91      final String[] args = { "-t", "10000", "-zookeeper" };
92      testZookeeperCanaryWithArgs(args);
93    }
94  
95    @Test
96    public void testZookeeperCanaryPermittedFailuresArgumentWorks() throws Exception {
97      final String[] args = { "-t", "10000", "-zookeeper", "-treatFailureAsError", "-permittedZookeeperFailures", "1" };
98      testZookeeperCanaryWithArgs(args);
99    }
100 
101   @Test
102   public void testBasicCanaryWorks() throws Exception {
103     TableName tableName = TableName.valueOf("testTable");
104     HTable table = testingUtility.createTable(tableName, new byte[][] { FAMILY });
105     // insert some test rows
106     for (int i=0; i<1000; i++) {
107       byte[] iBytes = Bytes.toBytes(i);
108       Put p = new Put(iBytes);
109       p.addColumn(FAMILY, COLUMN, iBytes);
110       table.put(p);
111     }
112     ExecutorService executor = new ScheduledThreadPoolExecutor(1);
113     CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
114     CanaryTool canary = new CanaryTool(executor, sink);
115     String[] args = { "-writeSniffing", "-t", "10000", tableName.getNameAsString() };
116     assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));
117     assertEquals("verify no read error count", 0, canary.getReadFailures().size());
118     assertEquals("verify no write error count", 0, canary.getWriteFailures().size());
119     verify(sink, atLeastOnce()).publishReadTiming(isA(ServerName.class), isA(HRegionInfo.class), isA(HColumnDescriptor.class), anyLong());
120   }
121 
122   @Test
123   public void testCanaryRegionTaskResult() throws Exception {
124     TableName tableName = TableName.valueOf("testCanaryRegionTaskResult");
125     HTable table = testingUtility.createTable(tableName, new byte[][]{FAMILY});
126     // insert some test rows
127     for (int i = 0; i < 1000; i++) {
128       byte[] iBytes = Bytes.toBytes(i);
129       Put p = new Put(iBytes);
130       p.addColumn(FAMILY, COLUMN, iBytes);
131       table.put(p);
132     }
133     ExecutorService executor = new ScheduledThreadPoolExecutor(1);
134     CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
135     CanaryTool canary = new CanaryTool(executor, sink);
136     String[] args = { "-writeSniffing", "-t", "10000", "testCanaryRegionTaskResult" };
137     assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));
138 
139     assertTrue("verify read success count > 0", sink.getReadSuccessCount() > 0);
140     assertTrue("verify write success count > 0", sink.getWriteSuccessCount() > 0);
141     verify(sink, atLeastOnce()).publishReadTiming(isA(ServerName.class), isA(HRegionInfo.class),
142       isA(HColumnDescriptor.class), anyLong());
143     verify(sink, atLeastOnce()).publishWriteTiming(isA(ServerName.class), isA(HRegionInfo.class),
144       isA(HColumnDescriptor.class), anyLong());
145 
146     assertTrue("canary should expect to scan at least 1 region",
147         sink.getTotalExpectedRegions() > 0);
148     Map<String, CanaryTool.RegionTaskResult> regionMap = sink.getRegionMap();
149     assertFalse("verify region map has size > 0", regionMap.isEmpty());
150 
151     for (String regionName : regionMap.keySet()) {
152       CanaryTool.RegionTaskResult res = regionMap.get(regionName);
153       assertNotNull("verify each expected region has a RegionTaskResult object in the map", res);
154       assertNotNull("verify getRegionNameAsString()", regionName);
155       assertNotNull("verify getRegionInfo()", res.getRegionInfo());
156       assertNotNull("verify getTableName()", res.getTableName());
157       assertNotNull("verify getTableNameAsString()", res.getTableNameAsString());
158       assertNotNull("verify getServerName()", res.getServerName());
159       assertNotNull("verify getServerNameAsString()", res.getServerNameAsString());
160 
161       if (regionName.contains(CanaryTool.DEFAULT_WRITE_TABLE_NAME.getNameAsString())) {
162         assertTrue("write to region " + regionName + " succeeded", res.isWriteSuccess());
163         assertTrue("write took some time", res.getWriteLatency() > -1);
164       } else {
165         assertTrue("read from region " + regionName + " succeeded", res.isReadSuccess());
166         assertTrue("read took some time", res.getReadLatency() > -1);
167       }
168     }
169   }
170 
171   @Test
172   @Ignore("Intermittent argument matching failures, see HBASE-18813")
173   public void testReadTableTimeouts() throws Exception {
174     final TableName [] tableNames = new TableName[2];
175     tableNames[0] = TableName.valueOf("testReadTableTimeouts1");
176     tableNames[1] = TableName.valueOf("testReadTableTimeouts2");
177     // Create 2 test tables.
178     for (int j = 0; j<2; j++) {
179       Table table = testingUtility.createTable(tableNames[j], new byte[][] { FAMILY });
180       // insert some test rows
181       for (int i=0; i<1000; i++) {
182         byte[] iBytes = Bytes.toBytes(i + j);
183         Put p = new Put(iBytes);
184         p.addColumn(FAMILY, COLUMN, iBytes);
185         table.put(p);
186       }
187     }
188     ExecutorService executor = new ScheduledThreadPoolExecutor(1);
189     CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
190     CanaryTool canary = new CanaryTool(executor, sink);
191     String configuredTimeoutStr = tableNames[0].getNameAsString() + "=" + Long.MAX_VALUE + "," +
192       tableNames[1].getNameAsString() + "=0";
193     String[] args = { "-readTableTimeouts", configuredTimeoutStr, tableNames[0].getNameAsString(), tableNames[1].getNameAsString()};
194     ToolRunner.run(testingUtility.getConfiguration(), canary, args);
195     verify(sink, times(tableNames.length)).initializeAndGetReadLatencyForTable(isA(String.class));
196     for (int i=0; i<2; i++) {
197       assertNotEquals("verify non-null read latency", null, sink.getReadLatencyMap().get(tableNames[i].getNameAsString()));
198       assertNotEquals("verify non-zero read latency", 0L, sink.getReadLatencyMap().get(tableNames[i].getNameAsString()));
199     }
200     // One table's timeout is set for 0 ms and thus, should lead to an error.
201     verify(mockAppender, times(1)).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
202       @Override
203       public boolean matches(Object argument) {
204         return ((LoggingEvent) argument).getRenderedMessage().contains("exceeded the configured read timeout.");
205       }
206     }));
207     verify(mockAppender, times(2)).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
208       @Override
209       public boolean matches(Object argument) {
210         return ((LoggingEvent) argument).getRenderedMessage().contains("Configured read timeout");
211       }
212     }));
213   }
214 
215   @Test
216   @Ignore("Intermittent argument matching failures, see HBASE-18813")
217   public void testWriteTableTimeout() throws Exception {
218     ExecutorService executor = new ScheduledThreadPoolExecutor(1);
219     CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
220     CanaryTool canary = new CanaryTool(executor, sink);
221     String[] args = { "-writeSniffing", "-writeTableTimeout", String.valueOf(Long.MAX_VALUE)};
222     ToolRunner.run(testingUtility.getConfiguration(), canary, args);
223     assertNotEquals("verify non-null write latency", null, sink.getWriteLatency());
224     assertNotEquals("verify non-zero write latency", 0L, sink.getWriteLatency());
225     verify(mockAppender, times(1)).doAppend(argThat(
226         new ArgumentMatcher<LoggingEvent>() {
227           @Override
228           public boolean matches(Object argument) {
229             return ((LoggingEvent) argument).getRenderedMessage().contains("Configured write timeout");
230           }
231         }));
232   }
233 
234   //no table created, so there should be no regions
235   @Test
236   public void testRegionserverNoRegions() throws Exception {
237     runRegionserverCanary();
238     verify(mockAppender).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
239       @Override
240       public boolean matches(Object argument) {
241         return ((LoggingEvent) argument).getRenderedMessage().contains("Regionserver not serving any regions");
242       }
243     }));
244   }
245 
246   //by creating a table, there shouldn't be any region servers not serving any regions
247   @Test
248   public void testRegionserverWithRegions() throws Exception {
249     TableName tableName = TableName.valueOf("testTable");
250     testingUtility.createTable(tableName, new byte[][] { FAMILY });
251     runRegionserverCanary();
252     verify(mockAppender, never()).doAppend(argThat(new ArgumentMatcher<LoggingEvent>() {
253       @Override
254       public boolean matches(Object argument) {
255         return ((LoggingEvent) argument).getRenderedMessage().contains("Regionserver not serving any regions");
256       }
257     }));
258   }
259 
260   @Test
261   public void testRawScanConfig() throws Exception {
262     TableName tableName = TableName.valueOf("testTableRawScan");
263     Table table = testingUtility.createTable(tableName, new byte[][] { FAMILY });
264     // insert some test rows
265     for (int i=0; i<1000; i++) {
266       byte[] iBytes = Bytes.toBytes(i);
267       Put p = new Put(iBytes);
268       p.addColumn(FAMILY, COLUMN, iBytes);
269       table.put(p);
270     }
271     ExecutorService executor = new ScheduledThreadPoolExecutor(1);
272     CanaryTool.RegionStdOutSink sink = spy(new CanaryTool.RegionStdOutSink());
273     CanaryTool canary = new CanaryTool(executor, sink);
274     String[] args = { "-t", "10000", "testTableRawScan" };
275     org.apache.hadoop.conf.Configuration conf =
276       new org.apache.hadoop.conf.Configuration(testingUtility.getConfiguration());
277     conf.setBoolean(HConstants.HBASE_CANARY_READ_RAW_SCAN_KEY, true);
278     ToolRunner.run(conf, canary, args);
279     verify(sink, atLeastOnce())
280         .publishReadTiming(isA(ServerName.class), isA(HRegionInfo.class), isA(HColumnDescriptor.class), anyLong());
281     assertEquals("verify no read error count", 0, canary.getReadFailures().size());
282   }
283 
284   private void runRegionserverCanary() throws Exception {
285     ExecutorService executor = new ScheduledThreadPoolExecutor(1);
286     CanaryTool canary = new CanaryTool(executor, new CanaryTool.RegionServerStdOutSink());
287     String[] args = { "-t", "10000", "-regionserver"};
288     ToolRunner.run(testingUtility.getConfiguration(), canary, args);
289     assertEquals("verify no read error count", 0, canary.getReadFailures().size());
290   }
291 
292   private void testZookeeperCanaryWithArgs(String[] args) throws Exception {
293     Integer port =
294       Iterables.getOnlyElement(testingUtility.getZkCluster().getClientPortList(), null);
295     testingUtility.getConfiguration().set(HConstants.ZOOKEEPER_QUORUM,
296       "localhost:" + port + "/hbase");
297     ExecutorService executor = new ScheduledThreadPoolExecutor(2);
298     CanaryTool.ZookeeperStdOutSink sink = spy(new CanaryTool.ZookeeperStdOutSink());
299     CanaryTool canary = new CanaryTool(executor, sink);
300     assertEquals(0, ToolRunner.run(testingUtility.getConfiguration(), canary, args));
301 
302     String baseZnode = testingUtility.getConfiguration()
303       .get(HConstants.ZOOKEEPER_ZNODE_PARENT, HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
304     verify(sink, atLeastOnce())
305       .publishReadTiming(eq(baseZnode), eq("localhost:" + port), anyLong());
306   }
307 }