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