1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.OutputStream;
23 import java.lang.reflect.Field;
24 import java.lang.reflect.Modifier;
25 import java.net.BindException;
26 import java.net.InetAddress;
27 import java.net.ServerSocket;
28 import java.net.Socket;
29 import java.net.UnknownHostException;
30 import java.security.MessageDigest;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.NavigableSet;
39 import java.util.Properties;
40 import java.util.Random;
41 import java.util.Set;
42 import java.util.TreeSet;
43 import java.util.UUID;
44 import java.util.concurrent.TimeUnit;
45
46 import org.apache.commons.io.FileUtils;
47 import org.apache.commons.lang.RandomStringUtils;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50 import org.apache.commons.logging.impl.Jdk14Logger;
51 import org.apache.commons.logging.impl.Log4JLogger;
52 import org.apache.hadoop.conf.Configuration;
53 import org.apache.hadoop.fs.FileSystem;
54 import org.apache.hadoop.fs.Path;
55 import org.apache.hadoop.hbase.Waiter.ExplainingPredicate;
56 import org.apache.hadoop.hbase.Waiter.Predicate;
57 import org.apache.hadoop.hbase.classification.InterfaceAudience;
58 import org.apache.hadoop.hbase.classification.InterfaceStability;
59 import org.apache.hadoop.hbase.client.Admin;
60 import org.apache.hadoop.hbase.client.Connection;
61 import org.apache.hadoop.hbase.client.ConnectionFactory;
62 import org.apache.hadoop.hbase.client.Consistency;
63 import org.apache.hadoop.hbase.client.Delete;
64 import org.apache.hadoop.hbase.client.Durability;
65 import org.apache.hadoop.hbase.client.Get;
66 import org.apache.hadoop.hbase.client.HBaseAdmin;
67 import org.apache.hadoop.hbase.client.HConnection;
68 import org.apache.hadoop.hbase.client.HTable;
69 import org.apache.hadoop.hbase.client.Put;
70 import org.apache.hadoop.hbase.client.RegionLocator;
71 import org.apache.hadoop.hbase.client.Result;
72 import org.apache.hadoop.hbase.client.ResultScanner;
73 import org.apache.hadoop.hbase.client.Scan;
74 import org.apache.hadoop.hbase.client.Table;
75 import org.apache.hadoop.hbase.fs.HFileSystem;
76 import org.apache.hadoop.hbase.io.compress.Compression;
77 import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
78 import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
79 import org.apache.hadoop.hbase.io.hfile.ChecksumUtil;
80 import org.apache.hadoop.hbase.io.hfile.HFile;
81 import org.apache.hadoop.hbase.ipc.RpcServerInterface;
82 import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
83 import org.apache.hadoop.hbase.mapreduce.MapreduceTestingShim;
84 import org.apache.hadoop.hbase.master.HMaster;
85 import org.apache.hadoop.hbase.master.AssignmentManager;
86 import org.apache.hadoop.hbase.master.RegionStates;
87 import org.apache.hadoop.hbase.master.ServerManager;
88 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
89 import org.apache.hadoop.hbase.regionserver.BloomType;
90 import org.apache.hadoop.hbase.regionserver.HRegion;
91 import org.apache.hadoop.hbase.regionserver.HRegionServer;
92 import org.apache.hadoop.hbase.regionserver.HStore;
93 import org.apache.hadoop.hbase.regionserver.InternalScanner;
94 import org.apache.hadoop.hbase.regionserver.Region;
95 import org.apache.hadoop.hbase.regionserver.RegionServerServices;
96 import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
97 import org.apache.hadoop.hbase.regionserver.wal.MetricsWAL;
98 import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
99 import org.apache.hadoop.hbase.security.HBaseKerberosUtils;
100 import org.apache.hadoop.hbase.security.User;
101 import org.apache.hadoop.hbase.security.visibility.VisibilityLabelsCache;
102 import org.apache.hadoop.hbase.tool.Canary;
103 import org.apache.hadoop.hbase.util.Bytes;
104 import org.apache.hadoop.hbase.util.FSTableDescriptors;
105 import org.apache.hadoop.hbase.util.FSUtils;
106 import org.apache.hadoop.hbase.util.JVMClusterUtil;
107 import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread;
108 import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
109 import org.apache.hadoop.hbase.util.Pair;
110 import org.apache.hadoop.hbase.util.RegionSplitter;
111 import org.apache.hadoop.hbase.util.RetryCounter;
112 import org.apache.hadoop.hbase.util.Threads;
113 import org.apache.hadoop.hbase.wal.WAL;
114 import org.apache.hadoop.hbase.wal.WALFactory;
115 import org.apache.hadoop.hbase.zookeeper.EmptyWatcher;
116 import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
117 import org.apache.hadoop.hbase.zookeeper.ZKAssign;
118 import org.apache.hadoop.hbase.zookeeper.ZKConfig;
119 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
120 import org.apache.hadoop.hdfs.DFSClient;
121 import org.apache.hadoop.hdfs.DistributedFileSystem;
122 import org.apache.hadoop.hdfs.MiniDFSCluster;
123 import org.apache.hadoop.hdfs.server.namenode.EditLogFileOutputStream;
124 import org.apache.hadoop.mapred.JobConf;
125 import org.apache.hadoop.mapred.MiniMRCluster;
126 import org.apache.hadoop.mapred.TaskLog;
127 import org.apache.hadoop.minikdc.MiniKdc;
128 import org.apache.zookeeper.KeeperException;
129 import org.apache.zookeeper.KeeperException.NodeExistsException;
130 import org.apache.zookeeper.WatchedEvent;
131 import org.apache.zookeeper.ZooKeeper;
132 import org.apache.zookeeper.ZooKeeper.States;
133
134 import static org.junit.Assert.assertEquals;
135 import static org.junit.Assert.assertTrue;
136 import static org.junit.Assert.fail;
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152 @InterfaceAudience.Public
153 @InterfaceStability.Evolving
154 @SuppressWarnings("deprecation")
155 public class HBaseTestingUtility extends HBaseCommonTestingUtility {
156 private MiniZooKeeperCluster zkCluster = null;
157
158 public static final String REGIONS_PER_SERVER_KEY = "hbase.test.regions-per-server";
159
160
161
162
163 public static final int DEFAULT_REGIONS_PER_SERVER = 3;
164
165
166 public static final String PRESPLIT_TEST_TABLE_KEY = "hbase.test.pre-split-table";
167 public static final boolean PRESPLIT_TEST_TABLE = true;
168
169 public static final String USE_LOCAL_FILESYSTEM = "hbase.test.local.fileSystem";
170
171
172
173
174 private boolean passedZkCluster = false;
175 private MiniDFSCluster dfsCluster = null;
176
177 private volatile HBaseCluster hbaseCluster = null;
178 private MiniMRCluster mrCluster = null;
179
180
181 private volatile boolean miniClusterRunning;
182
183 private String hadoopLogDir;
184
185
186 private File clusterTestDir = null;
187
188
189
190 private Path dataTestDirOnTestFS = null;
191
192
193
194
195 private volatile Connection connection;
196
197
198
199
200
201
202
203
204 @Deprecated
205 private static final String TEST_DIRECTORY_KEY = "test.build.data";
206
207
208 private static String FS_URI;
209
210
211 private static final Set<Integer> takenRandomPorts = new HashSet<Integer>();
212
213
214 public static final List<Object[]> COMPRESSION_ALGORITHMS_PARAMETERIZED =
215 Arrays.asList(new Object[][] {
216 { Compression.Algorithm.NONE },
217 { Compression.Algorithm.GZ }
218 });
219
220
221 public static final List<Object[]> BOOLEAN_PARAMETERIZED =
222 Arrays.asList(new Object[][] {
223 { new Boolean(false) },
224 { new Boolean(true) }
225 });
226
227
228 public static final List<Object[]> MEMSTORETS_TAGS_PARAMETRIZED = memStoreTSAndTagsCombination() ;
229
230 public static final Compression.Algorithm[] COMPRESSION_ALGORITHMS ={
231 Compression.Algorithm.NONE, Compression.Algorithm.GZ
232 };
233
234
235
236
237
238 private static List<Object[]> bloomAndCompressionCombinations() {
239 List<Object[]> configurations = new ArrayList<Object[]>();
240 for (Compression.Algorithm comprAlgo :
241 HBaseTestingUtility.COMPRESSION_ALGORITHMS) {
242 for (BloomType bloomType : BloomType.values()) {
243 configurations.add(new Object[] { comprAlgo, bloomType });
244 }
245 }
246 return Collections.unmodifiableList(configurations);
247 }
248
249
250
251
252 private static List<Object[]> memStoreTSAndTagsCombination() {
253 List<Object[]> configurations = new ArrayList<Object[]>();
254 configurations.add(new Object[] { false, false });
255 configurations.add(new Object[] { false, true });
256 configurations.add(new Object[] { true, false });
257 configurations.add(new Object[] { true, true });
258 return Collections.unmodifiableList(configurations);
259 }
260
261 public static final Collection<Object[]> BLOOM_AND_COMPRESSION_COMBINATIONS =
262 bloomAndCompressionCombinations();
263
264 public HBaseTestingUtility() {
265 this(HBaseConfiguration.create());
266 }
267
268 public HBaseTestingUtility(Configuration conf) {
269 super(conf);
270
271
272 ChecksumUtil.generateExceptionForChecksumFailureForTest(true);
273 }
274
275
276
277
278
279
280
281 public static HBaseTestingUtility createLocalHTU() {
282 Configuration c = HBaseConfiguration.create();
283 return createLocalHTU(c);
284 }
285
286
287
288
289
290
291
292
293 public static HBaseTestingUtility createLocalHTU(Configuration c) {
294 HBaseTestingUtility htu = new HBaseTestingUtility(c);
295 String dataTestDir = htu.getDataTestDir().toString();
296 htu.getConfiguration().set(HConstants.HBASE_DIR, dataTestDir);
297 LOG.debug("Setting " + HConstants.HBASE_DIR + " to " + dataTestDir);
298 return htu;
299 }
300
301
302
303
304 public static void closeRegion(final Region r) throws IOException {
305 if (r != null) {
306 ((HRegion)r).close();
307 }
308 }
309
310
311
312
313
314
315
316
317
318
319
320
321 @Override
322 public Configuration getConfiguration() {
323 return super.getConfiguration();
324 }
325
326 public void setHBaseCluster(HBaseCluster hbaseCluster) {
327 this.hbaseCluster = hbaseCluster;
328 }
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346 @Override
347 protected Path setupDataTestDir() {
348 Path testPath = super.setupDataTestDir();
349 if (null == testPath) {
350 return null;
351 }
352
353 createSubDirAndSystemProperty(
354 "hadoop.log.dir",
355 testPath, "hadoop-log-dir");
356
357
358
359 createSubDirAndSystemProperty(
360 "hadoop.tmp.dir",
361 testPath, "hadoop-tmp-dir");
362
363
364 createSubDir(
365 "mapreduce.cluster.local.dir",
366 testPath, "mapred-local-dir");
367
368 return testPath;
369 }
370
371 public void setJobWithoutMRCluster() throws IOException {
372 conf.set("hbase.fs.tmp.dir", getDataTestDirOnTestFS("hbase-staging").toString());
373 conf.setBoolean(HBaseTestingUtility.USE_LOCAL_FILESYSTEM, true);
374 }
375
376 private void createSubDirAndSystemProperty(
377 String propertyName, Path parent, String subDirName){
378
379 String sysValue = System.getProperty(propertyName);
380
381 if (sysValue != null) {
382
383
384 LOG.info("System.getProperty(\""+propertyName+"\") already set to: "+
385 sysValue + " so I do NOT create it in " + parent);
386 String confValue = conf.get(propertyName);
387 if (confValue != null && !confValue.endsWith(sysValue)){
388 LOG.warn(
389 propertyName + " property value differs in configuration and system: "+
390 "Configuration="+confValue+" while System="+sysValue+
391 " Erasing configuration value by system value."
392 );
393 }
394 conf.set(propertyName, sysValue);
395 } else {
396
397 createSubDir(propertyName, parent, subDirName);
398 System.setProperty(propertyName, conf.get(propertyName));
399 }
400 }
401
402
403
404
405
406
407
408 private Path getBaseTestDirOnTestFS() throws IOException {
409 FileSystem fs = getTestFileSystem();
410 return new Path(fs.getWorkingDirectory(), "test-data");
411 }
412
413
414
415
416 public HTableDescriptor getMetaTableDescriptor() {
417 try {
418 return new FSTableDescriptors(conf).get(TableName.META_TABLE_NAME);
419 } catch (IOException e) {
420 throw new RuntimeException("Unable to create META table descriptor", e);
421 }
422 }
423
424
425
426
427
428
429 Path getClusterTestDir() {
430 if (clusterTestDir == null){
431 setupClusterTestDir();
432 }
433 return new Path(clusterTestDir.getAbsolutePath());
434 }
435
436
437
438
439 private void setupClusterTestDir() {
440 if (clusterTestDir != null) {
441 return;
442 }
443
444
445
446 Path testDir = getDataTestDir("dfscluster_" + UUID.randomUUID().toString());
447 clusterTestDir = new File(testDir.toString()).getAbsoluteFile();
448
449 boolean b = deleteOnExit();
450 if (b) clusterTestDir.deleteOnExit();
451 conf.set(TEST_DIRECTORY_KEY, clusterTestDir.getPath());
452 LOG.info("Created new mini-cluster data directory: " + clusterTestDir + ", deleteOnExit=" + b);
453 }
454
455
456
457
458
459
460
461 public Path getDataTestDirOnTestFS() throws IOException {
462 if (dataTestDirOnTestFS == null) {
463 setupDataTestDirOnTestFS();
464 }
465
466 return dataTestDirOnTestFS;
467 }
468
469
470
471
472
473
474
475
476 public Path getDataTestDirOnTestFS(final String subdirName) throws IOException {
477 return new Path(getDataTestDirOnTestFS(), subdirName);
478 }
479
480
481
482
483
484 private void setupDataTestDirOnTestFS() throws IOException {
485 if (dataTestDirOnTestFS != null) {
486 LOG.warn("Data test on test fs dir already setup in "
487 + dataTestDirOnTestFS.toString());
488 return;
489 }
490 dataTestDirOnTestFS = getNewDataTestDirOnTestFS();
491 }
492
493
494
495
496 private Path getNewDataTestDirOnTestFS() throws IOException {
497
498
499
500
501 FileSystem fs = getTestFileSystem();
502 Path newDataTestDir = null;
503 if (fs.getUri().getScheme().equals(FileSystem.getLocal(conf).getUri().getScheme())) {
504 File dataTestDir = new File(getDataTestDir().toString());
505 if (deleteOnExit()) dataTestDir.deleteOnExit();
506 newDataTestDir = new Path(dataTestDir.getAbsolutePath());
507 } else {
508 Path base = getBaseTestDirOnTestFS();
509 String randomStr = UUID.randomUUID().toString();
510 newDataTestDir = new Path(base, randomStr);
511 if (deleteOnExit()) fs.deleteOnExit(newDataTestDir);
512 }
513 return newDataTestDir;
514 }
515
516
517
518
519
520
521 public boolean cleanupDataTestDirOnTestFS() throws IOException {
522 boolean ret = getTestFileSystem().delete(dataTestDirOnTestFS, true);
523 if (ret)
524 dataTestDirOnTestFS = null;
525 return ret;
526 }
527
528
529
530
531
532
533 public boolean cleanupDataTestDirOnTestFS(String subdirName) throws IOException {
534 Path cpath = getDataTestDirOnTestFS(subdirName);
535 return getTestFileSystem().delete(cpath, true);
536 }
537
538
539
540
541
542
543
544
545 public MiniDFSCluster startMiniDFSCluster(int servers) throws Exception {
546 return startMiniDFSCluster(servers, null);
547 }
548
549
550
551
552
553
554
555
556
557
558
559
560 public MiniDFSCluster startMiniDFSCluster(final String hosts[])
561 throws Exception {
562 if ( hosts != null && hosts.length != 0) {
563 return startMiniDFSCluster(hosts.length, hosts);
564 } else {
565 return startMiniDFSCluster(1, null);
566 }
567 }
568
569
570
571
572
573
574
575
576
577
578 public MiniDFSCluster startMiniDFSCluster(int servers, final String hosts[])
579 throws Exception {
580 createDirsAndSetProperties();
581 EditLogFileOutputStream.setShouldSkipFsyncForTesting(true);
582
583
584 org.apache.log4j.Logger.getLogger(org.apache.hadoop.metrics2.util.MBeans.class).
585 setLevel(org.apache.log4j.Level.ERROR);
586 org.apache.log4j.Logger.getLogger(org.apache.hadoop.metrics2.impl.MetricsSystemImpl.class).
587 setLevel(org.apache.log4j.Level.ERROR);
588
589
590 this.dfsCluster = new MiniDFSCluster(0, this.conf, servers, true, true,
591 true, null, null, hosts, null);
592
593
594 setFs();
595
596
597 this.dfsCluster.waitClusterUp();
598
599
600 dataTestDirOnTestFS = null;
601
602 return this.dfsCluster;
603 }
604
605 private void setFs() throws IOException {
606 if(this.dfsCluster == null){
607 LOG.info("Skipping setting fs because dfsCluster is null");
608 return;
609 }
610 FileSystem fs = this.dfsCluster.getFileSystem();
611 FSUtils.setFsDefault(this.conf, new Path(fs.getUri()));
612 if (this.conf.getBoolean(USE_LOCAL_FILESYSTEM, false)) {
613 FSUtils.setFsDefault(this.conf, new Path("file:///"));
614 }
615 }
616
617 public MiniDFSCluster startMiniDFSCluster(int servers, final String racks[], String hosts[])
618 throws Exception {
619 createDirsAndSetProperties();
620 this.dfsCluster = new MiniDFSCluster(0, this.conf, servers, true, true,
621 true, null, racks, hosts, null);
622
623
624 FileSystem fs = this.dfsCluster.getFileSystem();
625 FSUtils.setFsDefault(this.conf, new Path(fs.getUri()));
626
627
628 this.dfsCluster.waitClusterUp();
629
630
631 dataTestDirOnTestFS = null;
632
633 return this.dfsCluster;
634 }
635
636 public MiniDFSCluster startMiniDFSClusterForTestWAL(int namenodePort) throws IOException {
637 createDirsAndSetProperties();
638 dfsCluster = new MiniDFSCluster(namenodePort, conf, 5, false, true, true, null,
639 null, null, null);
640 return dfsCluster;
641 }
642
643
644 private void createDirsAndSetProperties() throws IOException {
645 setupClusterTestDir();
646 System.setProperty(TEST_DIRECTORY_KEY, clusterTestDir.getPath());
647 createDirAndSetProperty("cache_data", "test.cache.data");
648 createDirAndSetProperty("hadoop_tmp", "hadoop.tmp.dir");
649 hadoopLogDir = createDirAndSetProperty("hadoop_logs", "hadoop.log.dir");
650 createDirAndSetProperty("mapred_local", "mapreduce.cluster.local.dir");
651 createDirAndSetProperty("mapred_temp", "mapreduce.cluster.temp.dir");
652 enableShortCircuit();
653
654 Path root = getDataTestDirOnTestFS("hadoop");
655 conf.set(MapreduceTestingShim.getMROutputDirProp(),
656 new Path(root, "mapred-output-dir").toString());
657 conf.set("mapreduce.jobtracker.system.dir", new Path(root, "mapred-system-dir").toString());
658 conf.set("mapreduce.jobtracker.staging.root.dir",
659 new Path(root, "mapreduce-jobtracker-staging-root-dir").toString());
660 conf.set("mapreduce.job.working.dir", new Path(root, "mapred-working-dir").toString());
661 }
662
663
664
665
666
667
668
669 public boolean isReadShortCircuitOn(){
670 final String propName = "hbase.tests.use.shortcircuit.reads";
671 String readOnProp = System.getProperty(propName);
672 if (readOnProp != null){
673 return Boolean.parseBoolean(readOnProp);
674 } else {
675 return conf.getBoolean(propName, false);
676 }
677 }
678
679
680
681
682 private void enableShortCircuit() {
683 if (isReadShortCircuitOn()) {
684 String curUser = System.getProperty("user.name");
685 LOG.info("read short circuit is ON for user " + curUser);
686
687 conf.set("dfs.block.local-path-access.user", curUser);
688
689 conf.setBoolean("dfs.client.read.shortcircuit", true);
690
691 conf.setBoolean("dfs.client.read.shortcircuit.skip.checksum", true);
692 } else {
693 LOG.info("read short circuit is OFF");
694 }
695 }
696
697 private String createDirAndSetProperty(final String relPath, String property) {
698 String path = getDataTestDir(relPath).toString();
699 System.setProperty(property, path);
700 conf.set(property, path);
701 new File(path).mkdirs();
702 LOG.info("Setting " + property + " to " + path + " in system properties and HBase conf");
703 return path;
704 }
705
706
707
708
709
710
711 public void shutdownMiniDFSCluster() throws IOException {
712 if (this.dfsCluster != null) {
713
714 this.dfsCluster.shutdown();
715 dfsCluster = null;
716 dataTestDirOnTestFS = null;
717 FSUtils.setFsDefault(this.conf, new Path("file:///"));
718 }
719 }
720
721
722
723
724
725
726
727
728 public MiniZooKeeperCluster startMiniZKCluster() throws Exception {
729 return startMiniZKCluster(1);
730 }
731
732
733
734
735
736
737
738
739
740 public MiniZooKeeperCluster startMiniZKCluster(
741 final int zooKeeperServerNum,
742 final int ... clientPortList)
743 throws Exception {
744 setupClusterTestDir();
745 return startMiniZKCluster(clusterTestDir, zooKeeperServerNum, clientPortList);
746 }
747
748 private MiniZooKeeperCluster startMiniZKCluster(final File dir)
749 throws Exception {
750 return startMiniZKCluster(dir, 1, null);
751 }
752
753
754
755
756
757 private MiniZooKeeperCluster startMiniZKCluster(final File dir,
758 final int zooKeeperServerNum,
759 final int [] clientPortList)
760 throws Exception {
761 if (this.zkCluster != null) {
762 throw new IOException("Cluster already running at " + dir);
763 }
764 this.passedZkCluster = false;
765 this.zkCluster = new MiniZooKeeperCluster(this.getConfiguration());
766 final int defPort = this.conf.getInt("test.hbase.zookeeper.property.clientPort", 0);
767 if (defPort > 0){
768
769 this.zkCluster.setDefaultClientPort(defPort);
770 }
771
772 if (clientPortList != null) {
773
774 int clientPortListSize = (clientPortList.length <= zooKeeperServerNum) ?
775 clientPortList.length : zooKeeperServerNum;
776 for (int i=0; i < clientPortListSize; i++) {
777 this.zkCluster.addClientPort(clientPortList[i]);
778 }
779 }
780 int clientPort = this.zkCluster.startup(dir,zooKeeperServerNum);
781 this.conf.set(HConstants.ZOOKEEPER_CLIENT_PORT,
782 Integer.toString(clientPort));
783 return this.zkCluster;
784 }
785
786
787
788
789
790
791
792 public void shutdownMiniZKCluster() throws IOException {
793 if (this.zkCluster != null) {
794 this.zkCluster.shutdown();
795 this.zkCluster = null;
796 }
797 }
798
799
800
801
802
803
804
805 public MiniHBaseCluster startMiniCluster() throws Exception {
806 return startMiniCluster(1, 1);
807 }
808
809
810
811
812
813
814
815
816
817 public MiniHBaseCluster startMiniCluster(final int numSlaves, boolean create)
818 throws Exception {
819 return startMiniCluster(1, numSlaves, create);
820 }
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835 public MiniHBaseCluster startMiniCluster(final int numSlaves)
836 throws Exception {
837 return startMiniCluster(1, numSlaves, false);
838 }
839
840
841
842
843
844
845
846
847 public MiniHBaseCluster startMiniCluster(final int numMasters,
848 final int numSlaves, boolean create)
849 throws Exception {
850 return startMiniCluster(numMasters, numSlaves, null, create);
851 }
852
853
854
855
856
857
858
859 public MiniHBaseCluster startMiniCluster(final int numMasters,
860 final int numSlaves)
861 throws Exception {
862 return startMiniCluster(numMasters, numSlaves, null, false);
863 }
864
865 public MiniHBaseCluster startMiniCluster(final int numMasters,
866 final int numSlaves, final String[] dataNodeHosts, boolean create)
867 throws Exception {
868 return startMiniCluster(numMasters, numSlaves, numSlaves, dataNodeHosts,
869 null, null, create);
870 }
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896 public MiniHBaseCluster startMiniCluster(final int numMasters,
897 final int numSlaves, final String[] dataNodeHosts) throws Exception {
898 return startMiniCluster(numMasters, numSlaves, numSlaves, dataNodeHosts,
899 null, null);
900 }
901
902
903
904
905
906 public MiniHBaseCluster startMiniCluster(final int numMasters,
907 final int numSlaves, final int numDataNodes) throws Exception {
908 return startMiniCluster(numMasters, numSlaves, numDataNodes, null, null, null);
909 }
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938 public MiniHBaseCluster startMiniCluster(final int numMasters,
939 final int numSlaves, final String[] dataNodeHosts, Class<? extends HMaster> masterClass,
940 Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass)
941 throws Exception {
942 return startMiniCluster(
943 numMasters, numSlaves, numSlaves, dataNodeHosts, masterClass, regionserverClass);
944 }
945
946 public MiniHBaseCluster startMiniCluster(final int numMasters,
947 final int numSlaves, int numDataNodes, final String[] dataNodeHosts,
948 Class<? extends HMaster> masterClass,
949 Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass)
950 throws Exception {
951 return startMiniCluster(numMasters, numSlaves, numDataNodes, dataNodeHosts,
952 masterClass, regionserverClass, false);
953 }
954
955
956
957
958
959
960
961
962 public MiniHBaseCluster startMiniCluster(final int numMasters,
963 final int numSlaves, int numDataNodes, final String[] dataNodeHosts,
964 Class<? extends HMaster> masterClass,
965 Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass,
966 boolean create)
967 throws Exception {
968 if (dataNodeHosts != null && dataNodeHosts.length != 0) {
969 numDataNodes = dataNodeHosts.length;
970 }
971
972 LOG.info("Starting up minicluster with " + numMasters + " master(s) and " +
973 numSlaves + " regionserver(s) and " + numDataNodes + " datanode(s)");
974
975
976 if (miniClusterRunning) {
977 throw new IllegalStateException("A mini-cluster is already running");
978 }
979 miniClusterRunning = true;
980
981 setupClusterTestDir();
982 System.setProperty(TEST_DIRECTORY_KEY, this.clusterTestDir.getPath());
983
984
985
986 if(this.dfsCluster == null) {
987 dfsCluster = startMiniDFSCluster(numDataNodes, dataNodeHosts);
988 }
989
990
991 if (this.zkCluster == null) {
992 startMiniZKCluster(clusterTestDir);
993 }
994
995
996 return startMiniHBaseCluster(numMasters, numSlaves, masterClass,
997 regionserverClass, create);
998 }
999
1000 public MiniHBaseCluster startMiniHBaseCluster(final int numMasters, final int numSlaves)
1001 throws IOException, InterruptedException{
1002 return startMiniHBaseCluster(numMasters, numSlaves, null, null, false);
1003 }
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018 public MiniHBaseCluster startMiniHBaseCluster(final int numMasters,
1019 final int numSlaves, Class<? extends HMaster> masterClass,
1020 Class<? extends MiniHBaseCluster.MiniHBaseClusterRegionServer> regionserverClass,
1021 boolean create)
1022 throws IOException, InterruptedException {
1023
1024 createRootDir(create);
1025
1026
1027
1028 if (conf.getInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, -1) == -1) {
1029 conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, numSlaves);
1030 }
1031 if (conf.getInt(ServerManager.WAIT_ON_REGIONSERVERS_MAXTOSTART, -1) == -1) {
1032 conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MAXTOSTART, numSlaves);
1033 }
1034
1035 Configuration c = new Configuration(this.conf);
1036 this.hbaseCluster =
1037 new MiniHBaseCluster(c, numMasters, numSlaves, masterClass, regionserverClass);
1038
1039 Table t = new HTable(c, TableName.META_TABLE_NAME);
1040 ResultScanner s = t.getScanner(new Scan());
1041 while (s.next() != null) {
1042 continue;
1043 }
1044 s.close();
1045 t.close();
1046
1047 getHBaseAdmin();
1048 LOG.info("Minicluster is up");
1049
1050
1051
1052 setHBaseFsTmpDir();
1053
1054 return (MiniHBaseCluster)this.hbaseCluster;
1055 }
1056
1057
1058
1059
1060
1061
1062
1063 public void restartHBaseCluster(int servers) throws IOException, InterruptedException {
1064 this.hbaseCluster = new MiniHBaseCluster(this.conf, servers);
1065
1066 Table t = new HTable(new Configuration(this.conf), TableName.META_TABLE_NAME);
1067 ResultScanner s = t.getScanner(new Scan());
1068 while (s.next() != null) {
1069
1070 }
1071 LOG.info("HBase has been restarted");
1072 s.close();
1073 t.close();
1074 }
1075
1076
1077
1078
1079
1080
1081 public MiniHBaseCluster getMiniHBaseCluster() {
1082 if (this.hbaseCluster == null || this.hbaseCluster instanceof MiniHBaseCluster) {
1083 return (MiniHBaseCluster)this.hbaseCluster;
1084 }
1085 throw new RuntimeException(hbaseCluster + " not an instance of " +
1086 MiniHBaseCluster.class.getName());
1087 }
1088
1089
1090
1091
1092
1093
1094 public void shutdownMiniCluster() throws Exception {
1095 LOG.info("Shutting down minicluster");
1096 if (this.connection != null && !this.connection.isClosed()) {
1097 this.connection.close();
1098 this.connection = null;
1099 }
1100 shutdownMiniHBaseCluster();
1101 if (!this.passedZkCluster){
1102 shutdownMiniZKCluster();
1103 }
1104 shutdownMiniDFSCluster();
1105
1106 cleanupTestDir();
1107 miniClusterRunning = false;
1108 LOG.info("Minicluster is down");
1109 }
1110
1111
1112
1113
1114
1115 @Override
1116 public boolean cleanupTestDir() throws IOException {
1117 boolean ret = super.cleanupTestDir();
1118 if (deleteDir(this.clusterTestDir)) {
1119 this.clusterTestDir = null;
1120 return ret & true;
1121 }
1122 return false;
1123 }
1124
1125
1126
1127
1128
1129 public void shutdownMiniHBaseCluster() throws IOException {
1130 if (hbaseAdmin != null) {
1131 hbaseAdmin.close0();
1132 hbaseAdmin = null;
1133 }
1134
1135
1136 conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, -1);
1137 conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MAXTOSTART, -1);
1138 if (this.hbaseCluster != null) {
1139 this.hbaseCluster.shutdown();
1140
1141 this.hbaseCluster.waitUntilShutDown();
1142 this.hbaseCluster = null;
1143 }
1144
1145 if (zooKeeperWatcher != null) {
1146 zooKeeperWatcher.close();
1147 zooKeeperWatcher = null;
1148 }
1149 }
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159 public Path getDefaultRootDirPath(boolean create) throws IOException {
1160 if (!create) {
1161 return getDataTestDirOnTestFS();
1162 } else {
1163 return getNewDataTestDirOnTestFS();
1164 }
1165 }
1166
1167
1168
1169
1170
1171
1172
1173
1174 public Path getDefaultRootDirPath() throws IOException {
1175 return getDefaultRootDirPath(false);
1176 }
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190 public Path createRootDir(boolean create) throws IOException {
1191 FileSystem fs = FileSystem.get(this.conf);
1192 Path hbaseRootdir = getDefaultRootDirPath(create);
1193 FSUtils.setRootDir(this.conf, hbaseRootdir);
1194 fs.mkdirs(hbaseRootdir);
1195 FSUtils.setVersion(fs, hbaseRootdir);
1196 return hbaseRootdir;
1197 }
1198
1199
1200
1201
1202
1203
1204
1205 public Path createRootDir() throws IOException {
1206 return createRootDir(false);
1207 }
1208
1209
1210 private void setHBaseFsTmpDir() throws IOException {
1211 String hbaseFsTmpDirInString = this.conf.get("hbase.fs.tmp.dir");
1212 if (hbaseFsTmpDirInString == null) {
1213 this.conf.set("hbase.fs.tmp.dir", getDataTestDirOnTestFS("hbase-staging").toString());
1214 LOG.info("Setting hbase.fs.tmp.dir to " + this.conf.get("hbase.fs.tmp.dir"));
1215 } else {
1216 LOG.info("The hbase.fs.tmp.dir is set to " + hbaseFsTmpDirInString);
1217 }
1218 }
1219
1220
1221
1222
1223
1224 public void flush() throws IOException {
1225 getMiniHBaseCluster().flushcache();
1226 }
1227
1228
1229
1230
1231
1232 public void flush(TableName tableName) throws IOException {
1233 getMiniHBaseCluster().flushcache(tableName);
1234 }
1235
1236
1237
1238
1239
1240 public void compact(boolean major) throws IOException {
1241 getMiniHBaseCluster().compact(major);
1242 }
1243
1244
1245
1246
1247
1248 public void compact(TableName tableName, boolean major) throws IOException {
1249 getMiniHBaseCluster().compact(tableName, major);
1250 }
1251
1252
1253
1254
1255
1256
1257
1258
1259 public Table createTable(TableName tableName, String family)
1260 throws IOException{
1261 return createTable(tableName, new String[]{family});
1262 }
1263
1264
1265
1266
1267
1268
1269
1270
1271 public HTable createTable(byte[] tableName, byte[] family)
1272 throws IOException{
1273 return createTable(TableName.valueOf(tableName), new byte[][]{family});
1274 }
1275
1276
1277
1278
1279
1280
1281
1282
1283 public Table createTable(TableName tableName, String[] families)
1284 throws IOException {
1285 List<byte[]> fams = new ArrayList<byte[]>(families.length);
1286 for (String family : families) {
1287 fams.add(Bytes.toBytes(family));
1288 }
1289 return createTable(tableName, fams.toArray(new byte[0][]));
1290 }
1291
1292
1293
1294
1295
1296
1297
1298
1299 public HTable createTable(TableName tableName, byte[] family)
1300 throws IOException{
1301 return createTable(tableName, new byte[][]{family});
1302 }
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312 public HTable createMultiRegionTable(TableName tableName, byte[] family, int numRegions)
1313 throws IOException {
1314 if (numRegions < 3) throw new IOException("Must create at least 3 regions");
1315 byte[] startKey = Bytes.toBytes("aaaaa");
1316 byte[] endKey = Bytes.toBytes("zzzzz");
1317 byte[][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
1318
1319 return createTable(tableName, new byte[][] { family }, splitKeys);
1320 }
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330 public HTable createTable(byte[] tableName, byte[][] families)
1331 throws IOException {
1332 return createTable(tableName, families,
1333 new Configuration(getConfiguration()));
1334 }
1335
1336
1337
1338
1339
1340
1341
1342
1343 public HTable createTable(TableName tableName, byte[][] families)
1344 throws IOException {
1345 return createTable(tableName, families, (byte[][]) null);
1346 }
1347
1348
1349
1350
1351
1352
1353
1354
1355 public HTable createMultiRegionTable(TableName tableName, byte[][] families) throws IOException {
1356 return createTable(tableName, families, KEYS_FOR_HBA_CREATE_TABLE);
1357 }
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367 public HTable createTable(TableName tableName, byte[][] families, byte[][] splitKeys)
1368 throws IOException {
1369 return createTable(tableName, families, splitKeys, new Configuration(getConfiguration()));
1370 }
1371
1372 public HTable createTable(byte[] tableName, byte[][] families,
1373 int numVersions, byte[] startKey, byte[] endKey, int numRegions) throws IOException {
1374 return createTable(TableName.valueOf(tableName), families, numVersions,
1375 startKey, endKey, numRegions);
1376 }
1377
1378 public HTable createTable(String tableName, byte[][] families,
1379 int numVersions, byte[] startKey, byte[] endKey, int numRegions) throws IOException {
1380 return createTable(TableName.valueOf(tableName), families, numVersions,
1381 startKey, endKey, numRegions);
1382 }
1383
1384 public HTable createTable(TableName tableName, byte[][] families,
1385 int numVersions, byte[] startKey, byte[] endKey, int numRegions)
1386 throws IOException{
1387 HTableDescriptor desc = new HTableDescriptor(tableName);
1388 for (byte[] family : families) {
1389 HColumnDescriptor hcd = new HColumnDescriptor(family)
1390 .setMaxVersions(numVersions);
1391 desc.addFamily(hcd);
1392 }
1393 getHBaseAdmin().createTable(desc, startKey, endKey, numRegions);
1394
1395 waitUntilAllRegionsAssigned(tableName);
1396 return new HTable(getConfiguration(), tableName);
1397 }
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407 public HTable createTable(HTableDescriptor htd, byte[][] families, Configuration c)
1408 throws IOException {
1409 return createTable(htd, families, (byte[][]) null, c);
1410 }
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421 public HTable createTable(HTableDescriptor htd, byte[][] families, byte[][] splitKeys,
1422 Configuration c) throws IOException {
1423 for (byte[] family : families) {
1424 HColumnDescriptor hcd = new HColumnDescriptor(family);
1425
1426
1427
1428 hcd.setBloomFilterType(BloomType.NONE);
1429 htd.addFamily(hcd);
1430 }
1431 getHBaseAdmin().createTable(htd, splitKeys);
1432
1433
1434 waitUntilAllRegionsAssigned(htd.getTableName());
1435 return (HTable) getConnection().getTable(htd.getTableName());
1436 }
1437
1438
1439
1440
1441
1442
1443
1444
1445 public HTable createTable(HTableDescriptor htd, byte[][] splitRows)
1446 throws IOException {
1447 getHBaseAdmin().createTable(htd, splitRows);
1448
1449 waitUntilAllRegionsAssigned(htd.getTableName());
1450 return new HTable(getConfiguration(), htd.getTableName());
1451 }
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461 public HTable createTable(TableName tableName, byte[][] families,
1462 final Configuration c)
1463 throws IOException {
1464 return createTable(tableName, families, (byte[][]) null, c);
1465 }
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476 public HTable createTable(TableName tableName, byte[][] families, byte[][] splitKeys,
1477 final Configuration c) throws IOException {
1478 return createTable(new HTableDescriptor(tableName), families, splitKeys, c);
1479 }
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489 public HTable createTable(byte[] tableName, byte[][] families,
1490 final Configuration c)
1491 throws IOException {
1492 HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
1493 for(byte[] family : families) {
1494 HColumnDescriptor hcd = new HColumnDescriptor(family);
1495
1496
1497
1498 hcd.setBloomFilterType(BloomType.NONE);
1499 desc.addFamily(hcd);
1500 }
1501 getHBaseAdmin().createTable(desc);
1502 return new HTable(c, desc.getTableName());
1503 }
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514 public HTable createTable(TableName tableName, byte[][] families,
1515 final Configuration c, int numVersions)
1516 throws IOException {
1517 HTableDescriptor desc = new HTableDescriptor(tableName);
1518 for(byte[] family : families) {
1519 HColumnDescriptor hcd = new HColumnDescriptor(family)
1520 .setMaxVersions(numVersions);
1521 desc.addFamily(hcd);
1522 }
1523 getHBaseAdmin().createTable(desc);
1524
1525 waitUntilAllRegionsAssigned(tableName);
1526 return new HTable(c, tableName);
1527 }
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538 public HTable createTable(byte[] tableName, byte[][] families,
1539 final Configuration c, int numVersions)
1540 throws IOException {
1541 HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
1542 for(byte[] family : families) {
1543 HColumnDescriptor hcd = new HColumnDescriptor(family)
1544 .setMaxVersions(numVersions);
1545 desc.addFamily(hcd);
1546 }
1547 getHBaseAdmin().createTable(desc);
1548 return new HTable(c, desc.getTableName());
1549 }
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559 public HTable createTable(byte[] tableName, byte[] family, int numVersions)
1560 throws IOException {
1561 return createTable(tableName, new byte[][]{family}, numVersions);
1562 }
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572 public HTable createTable(TableName tableName, byte[] family, int numVersions)
1573 throws IOException {
1574 return createTable(tableName, new byte[][]{family}, numVersions);
1575 }
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585 public HTable createTable(byte[] tableName, byte[][] families,
1586 int numVersions)
1587 throws IOException {
1588 return createTable(TableName.valueOf(tableName), families, numVersions);
1589 }
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599 public HTable createTable(TableName tableName, byte[][] families,
1600 int numVersions)
1601 throws IOException {
1602 return createTable(tableName, families, numVersions, (byte[][]) null);
1603 }
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614 public HTable createTable(TableName tableName, byte[][] families, int numVersions,
1615 byte[][] splitKeys) throws IOException {
1616 HTableDescriptor desc = new HTableDescriptor(tableName);
1617 for (byte[] family : families) {
1618 HColumnDescriptor hcd = new HColumnDescriptor(family).setMaxVersions(numVersions);
1619 desc.addFamily(hcd);
1620 }
1621 getHBaseAdmin().createTable(desc, splitKeys);
1622
1623 waitUntilAllRegionsAssigned(tableName);
1624 return new HTable(new Configuration(getConfiguration()), tableName);
1625 }
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635 public HTable createMultiRegionTable(TableName tableName, byte[][] families, int numVersions)
1636 throws IOException {
1637 return createTable(tableName, families, numVersions, KEYS_FOR_HBA_CREATE_TABLE);
1638 }
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649 public HTable createTable(byte[] tableName, byte[][] families,
1650 int numVersions, int blockSize) throws IOException {
1651 return createTable(TableName.valueOf(tableName),
1652 families, numVersions, blockSize);
1653 }
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664 public HTable createTable(TableName tableName, byte[][] families,
1665 int numVersions, int blockSize) throws IOException {
1666 HTableDescriptor desc = new HTableDescriptor(tableName);
1667 for (byte[] family : families) {
1668 HColumnDescriptor hcd = new HColumnDescriptor(family)
1669 .setMaxVersions(numVersions)
1670 .setBlocksize(blockSize);
1671 desc.addFamily(hcd);
1672 }
1673 getHBaseAdmin().createTable(desc);
1674
1675 waitUntilAllRegionsAssigned(tableName);
1676 return new HTable(new Configuration(getConfiguration()), tableName);
1677 }
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687 public HTable createTable(byte[] tableName, byte[][] families,
1688 int[] numVersions)
1689 throws IOException {
1690 return createTable(TableName.valueOf(tableName), families, numVersions);
1691 }
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701 public HTable createTable(TableName tableName, byte[][] families,
1702 int[] numVersions)
1703 throws IOException {
1704 HTableDescriptor desc = new HTableDescriptor(tableName);
1705 int i = 0;
1706 for (byte[] family : families) {
1707 HColumnDescriptor hcd = new HColumnDescriptor(family)
1708 .setMaxVersions(numVersions[i]);
1709 desc.addFamily(hcd);
1710 i++;
1711 }
1712 getHBaseAdmin().createTable(desc);
1713
1714 waitUntilAllRegionsAssigned(tableName);
1715 return new HTable(new Configuration(getConfiguration()), tableName);
1716 }
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726 public HTable createTable(byte[] tableName, byte[] family, byte[][] splitRows)
1727 throws IOException{
1728 return createTable(TableName.valueOf(tableName), family, splitRows);
1729 }
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739 public HTable createTable(TableName tableName, byte[] family, byte[][] splitRows)
1740 throws IOException {
1741 HTableDescriptor desc = new HTableDescriptor(tableName);
1742 HColumnDescriptor hcd = new HColumnDescriptor(family);
1743 desc.addFamily(hcd);
1744 getHBaseAdmin().createTable(desc, splitRows);
1745
1746 waitUntilAllRegionsAssigned(tableName);
1747 return new HTable(getConfiguration(), tableName);
1748 }
1749
1750
1751
1752
1753
1754
1755
1756
1757 public HTable createMultiRegionTable(TableName tableName, byte[] family) throws IOException {
1758 return createTable(tableName, family, KEYS_FOR_HBA_CREATE_TABLE);
1759 }
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769 public HTable createTable(byte[] tableName, byte[][] families, byte[][] splitRows)
1770 throws IOException {
1771 HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
1772 for(byte[] family:families) {
1773 HColumnDescriptor hcd = new HColumnDescriptor(family);
1774 desc.addFamily(hcd);
1775 }
1776 getHBaseAdmin().createTable(desc, splitRows);
1777
1778 waitUntilAllRegionsAssigned(desc.getTableName());
1779 return new HTable(getConfiguration(), desc.getTableName());
1780 }
1781
1782
1783
1784
1785 public static WAL createWal(final Configuration conf, final Path rootDir, final HRegionInfo hri)
1786 throws IOException {
1787
1788
1789 Configuration confForWAL = new Configuration(conf);
1790 confForWAL.set(HConstants.HBASE_DIR, rootDir.toString());
1791 return (new WALFactory(confForWAL,
1792 Collections.<WALActionsListener>singletonList(new MetricsWAL()),
1793 "hregion-" + RandomStringUtils.randomNumeric(8))).
1794 getWAL(hri.getEncodedNameAsBytes());
1795 }
1796
1797
1798
1799
1800
1801 public static HRegion createRegionAndWAL(final HRegionInfo info, final Path rootDir,
1802 final Configuration conf, final HTableDescriptor htd) throws IOException {
1803 return createRegionAndWAL(info, rootDir, conf, htd, true);
1804 }
1805
1806
1807
1808
1809
1810 public static HRegion createRegionAndWAL(final HRegionInfo info, final Path rootDir,
1811 final Configuration conf, final HTableDescriptor htd, boolean initialize)
1812 throws IOException {
1813 WAL wal = createWal(conf, rootDir, info);
1814 return HRegion.createHRegion(info, rootDir, conf, htd, wal, initialize);
1815 }
1816
1817
1818
1819
1820 public static void closeRegionAndWAL(final Region r) throws IOException {
1821 closeRegionAndWAL((HRegion)r);
1822 }
1823
1824
1825
1826
1827 public static void closeRegionAndWAL(final HRegion r) throws IOException {
1828 if (r == null) return;
1829 r.close();
1830 if (r.getWAL() == null) return;
1831 r.getWAL().close();
1832 }
1833
1834
1835
1836
1837 @SuppressWarnings("serial")
1838 public static void modifyTableSync(Admin admin, HTableDescriptor desc)
1839 throws IOException, InterruptedException {
1840 admin.modifyTable(desc.getTableName(), desc);
1841 Pair<Integer, Integer> status = new Pair<Integer, Integer>() {{
1842 setFirst(0);
1843 setSecond(0);
1844 }};
1845 int i = 0;
1846 do {
1847 status = admin.getAlterStatus(desc.getTableName());
1848 if (status.getSecond() != 0) {
1849 LOG.debug(status.getSecond() - status.getFirst() + "/" + status.getSecond()
1850 + " regions updated.");
1851 Thread.sleep(1 * 1000l);
1852 } else {
1853 LOG.debug("All regions updated.");
1854 break;
1855 }
1856 } while (status.getFirst() != 0 && i++ < 500);
1857 if (status.getFirst() != 0) {
1858 throw new IOException("Failed to update all regions even after 500 seconds.");
1859 }
1860 }
1861
1862
1863
1864
1865 public static void setReplicas(Admin admin, TableName table, int replicaCount)
1866 throws IOException, InterruptedException {
1867 admin.disableTable(table);
1868 HTableDescriptor desc = admin.getTableDescriptor(table);
1869 desc.setRegionReplication(replicaCount);
1870 admin.modifyTable(desc.getTableName(), desc);
1871 admin.enableTable(table);
1872 }
1873
1874
1875
1876
1877
1878 public void deleteTable(String tableName) throws IOException {
1879 deleteTable(TableName.valueOf(tableName));
1880 }
1881
1882
1883
1884
1885
1886 public void deleteTable(byte[] tableName) throws IOException {
1887 deleteTable(TableName.valueOf(tableName));
1888 }
1889
1890
1891
1892
1893
1894 public void deleteTable(TableName tableName) throws IOException {
1895 try {
1896 getHBaseAdmin().disableTable(tableName);
1897 } catch (TableNotEnabledException e) {
1898 LOG.debug("Table: " + tableName + " already disabled, so just deleting it.");
1899 }
1900 getHBaseAdmin().deleteTable(tableName);
1901 }
1902
1903
1904
1905
1906
1907 public void deleteTableIfAny(TableName tableName) throws IOException {
1908 try {
1909 deleteTable(tableName);
1910 } catch (TableNotFoundException e) {
1911
1912 }
1913 }
1914
1915
1916
1917
1918
1919 public final static byte [] fam1 = Bytes.toBytes("colfamily11");
1920 public final static byte [] fam2 = Bytes.toBytes("colfamily21");
1921 public final static byte [] fam3 = Bytes.toBytes("colfamily31");
1922 public static final byte[][] COLUMNS = {fam1, fam2, fam3};
1923 private static final int MAXVERSIONS = 3;
1924
1925 public static final char FIRST_CHAR = 'a';
1926 public static final char LAST_CHAR = 'z';
1927 public static final byte [] START_KEY_BYTES = {FIRST_CHAR, FIRST_CHAR, FIRST_CHAR};
1928 public static final String START_KEY = new String(START_KEY_BYTES, HConstants.UTF8_CHARSET);
1929
1930
1931
1932
1933
1934
1935
1936
1937 public HTableDescriptor createTableDescriptor(final String name,
1938 final int minVersions, final int versions, final int ttl, KeepDeletedCells keepDeleted) {
1939 HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name));
1940 for (byte[] cfName : new byte[][]{ fam1, fam2, fam3 }) {
1941 htd.addFamily(new HColumnDescriptor(cfName)
1942 .setMinVersions(minVersions)
1943 .setMaxVersions(versions)
1944 .setKeepDeletedCells(keepDeleted)
1945 .setBlockCacheEnabled(false)
1946 .setTimeToLive(ttl)
1947 );
1948 }
1949 return htd;
1950 }
1951
1952
1953
1954
1955
1956
1957
1958 public HTableDescriptor createTableDescriptor(final String name) {
1959 return createTableDescriptor(name, HColumnDescriptor.DEFAULT_MIN_VERSIONS,
1960 MAXVERSIONS, HConstants.FOREVER, HColumnDescriptor.DEFAULT_KEEP_DELETED);
1961 }
1962
1963
1964
1965
1966
1967 public HRegion createHRegion(
1968 final HRegionInfo info,
1969 final Path rootDir,
1970 final Configuration conf,
1971 final HTableDescriptor htd) throws IOException {
1972 return HRegion.createHRegion(info, rootDir, conf, htd);
1973 }
1974
1975 public HTableDescriptor createTableDescriptor(final TableName tableName,
1976 byte[] family) {
1977 return createTableDescriptor(tableName, new byte[][] {family}, 1);
1978 }
1979
1980 public HTableDescriptor createTableDescriptor(final TableName tableName,
1981 byte[][] families, int maxVersions) {
1982 HTableDescriptor desc = new HTableDescriptor(tableName);
1983 for (byte[] family : families) {
1984 HColumnDescriptor hcd = new HColumnDescriptor(family)
1985 .setMaxVersions(maxVersions);
1986 desc.addFamily(hcd);
1987 }
1988 return desc;
1989 }
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999 public HRegion createLocalHRegion(HTableDescriptor desc, byte [] startKey,
2000 byte [] endKey)
2001 throws IOException {
2002 HRegionInfo hri = new HRegionInfo(desc.getTableName(), startKey, endKey);
2003 return createLocalHRegion(hri, desc);
2004 }
2005
2006
2007
2008
2009
2010
2011
2012
2013 public HRegion createLocalHRegion(HRegionInfo info, HTableDescriptor desc) throws IOException {
2014 return HRegion.createHRegion(info, getDataTestDir(), getConfiguration(), desc);
2015 }
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025 public HRegion createLocalHRegion(HRegionInfo info, HTableDescriptor desc, WAL wal)
2026 throws IOException {
2027 return HRegion.createHRegion(info, getDataTestDir(), getConfiguration(), desc, wal);
2028 }
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042 public HRegion createLocalHRegion(byte[] tableName, byte[] startKey, byte[] stopKey,
2043 String callingMethod, Configuration conf, boolean isReadOnly, Durability durability,
2044 WAL wal, byte[]... families) throws IOException {
2045 HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
2046 htd.setReadOnly(isReadOnly);
2047 for (byte[] family : families) {
2048 HColumnDescriptor hcd = new HColumnDescriptor(family);
2049
2050 hcd.setMaxVersions(Integer.MAX_VALUE);
2051 htd.addFamily(hcd);
2052 }
2053 htd.setDurability(durability);
2054 HRegionInfo info = new HRegionInfo(htd.getTableName(), startKey, stopKey, false);
2055 return createLocalHRegion(info, htd, wal);
2056 }
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067 public HTable deleteTableData(byte[] tableName) throws IOException {
2068 return deleteTableData(TableName.valueOf(tableName));
2069 }
2070
2071
2072
2073
2074
2075
2076
2077
2078 public HTable deleteTableData(TableName tableName) throws IOException {
2079 HTable table = new HTable(getConfiguration(), tableName);
2080 Scan scan = new Scan();
2081 ResultScanner resScan = table.getScanner(scan);
2082 for(Result res : resScan) {
2083 Delete del = new Delete(res.getRow());
2084 table.delete(del);
2085 }
2086 resScan = table.getScanner(scan);
2087 resScan.close();
2088 return table;
2089 }
2090
2091
2092
2093
2094
2095
2096
2097
2098 public HTable truncateTable(final TableName tableName, final boolean preserveRegions)
2099 throws IOException {
2100 Admin admin = getHBaseAdmin();
2101 if (!admin.isTableDisabled(tableName)) {
2102 admin.disableTable(tableName);
2103 }
2104 admin.truncateTable(tableName, preserveRegions);
2105 return new HTable(getConfiguration(), tableName);
2106 }
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117 public HTable truncateTable(final TableName tableName) throws IOException {
2118 return truncateTable(tableName, false);
2119 }
2120
2121
2122
2123
2124
2125
2126
2127
2128 public HTable truncateTable(final byte[] tableName, final boolean preserveRegions)
2129 throws IOException {
2130 return truncateTable(TableName.valueOf(tableName), preserveRegions);
2131 }
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142 public HTable truncateTable(final byte[] tableName) throws IOException {
2143 return truncateTable(tableName, false);
2144 }
2145
2146
2147
2148
2149
2150
2151
2152
2153 public int loadTable(final Table t, final byte[] f) throws IOException {
2154 return loadTable(t, new byte[][] {f});
2155 }
2156
2157
2158
2159
2160
2161
2162
2163
2164 public int loadTable(final Table t, final byte[] f, boolean writeToWAL) throws IOException {
2165 return loadTable(t, new byte[][] {f}, null, writeToWAL);
2166 }
2167
2168
2169
2170
2171
2172
2173
2174
2175 public int loadTable(final Table t, final byte[][] f) throws IOException {
2176 return loadTable(t, f, null);
2177 }
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187 public int loadTable(final Table t, final byte[][] f, byte[] value) throws IOException {
2188 return loadTable(t, f, value, true);
2189 }
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199 public int loadTable(final Table t, final byte[][] f, byte[] value, boolean writeToWAL) throws IOException {
2200 List<Put> puts = new ArrayList<>();
2201 for (byte[] row : HBaseTestingUtility.ROWS) {
2202 Put put = new Put(row);
2203 put.setDurability(writeToWAL ? Durability.USE_DEFAULT : Durability.SKIP_WAL);
2204 for (int i = 0; i < f.length; i++) {
2205 put.add(f[i], f[i], value != null ? value : row);
2206 }
2207 puts.add(put);
2208 }
2209 t.put(puts);
2210 return puts.size();
2211 }
2212
2213
2214
2215
2216 public static class SeenRowTracker {
2217 int dim = 'z' - 'a' + 1;
2218 int[][][] seenRows = new int[dim][dim][dim];
2219 byte[] startRow;
2220 byte[] stopRow;
2221
2222 public SeenRowTracker(byte[] startRow, byte[] stopRow) {
2223 this.startRow = startRow;
2224 this.stopRow = stopRow;
2225 }
2226
2227 void reset() {
2228 for (byte[] row : ROWS) {
2229 seenRows[i(row[0])][i(row[1])][i(row[2])] = 0;
2230 }
2231 }
2232
2233 int i(byte b) {
2234 return b - 'a';
2235 }
2236
2237 public void addRow(byte[] row) {
2238 seenRows[i(row[0])][i(row[1])][i(row[2])]++;
2239 }
2240
2241
2242
2243
2244 public void validate() {
2245 for (byte b1 = 'a'; b1 <= 'z'; b1++) {
2246 for (byte b2 = 'a'; b2 <= 'z'; b2++) {
2247 for (byte b3 = 'a'; b3 <= 'z'; b3++) {
2248 int count = seenRows[i(b1)][i(b2)][i(b3)];
2249 int expectedCount = 0;
2250 if (Bytes.compareTo(new byte[] {b1,b2,b3}, startRow) >= 0
2251 && Bytes.compareTo(new byte[] {b1,b2,b3}, stopRow) < 0) {
2252 expectedCount = 1;
2253 }
2254 if (count != expectedCount) {
2255 String row = new String(new byte[] {b1,b2,b3});
2256 throw new RuntimeException("Row:" + row + " has a seen count of " + count + " instead of " + expectedCount);
2257 }
2258 }
2259 }
2260 }
2261 }
2262 }
2263
2264 public int loadRegion(final HRegion r, final byte[] f) throws IOException {
2265 return loadRegion(r, f, false);
2266 }
2267
2268 public int loadRegion(final Region r, final byte[] f) throws IOException {
2269 return loadRegion((HRegion)r, f);
2270 }
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280 public int loadRegion(final HRegion r, final byte[] f, final boolean flush)
2281 throws IOException {
2282 byte[] k = new byte[3];
2283 int rowCount = 0;
2284 for (byte b1 = 'a'; b1 <= 'z'; b1++) {
2285 for (byte b2 = 'a'; b2 <= 'z'; b2++) {
2286 for (byte b3 = 'a'; b3 <= 'z'; b3++) {
2287 k[0] = b1;
2288 k[1] = b2;
2289 k[2] = b3;
2290 Put put = new Put(k);
2291 put.setDurability(Durability.SKIP_WAL);
2292 put.add(f, null, k);
2293 if (r.getWAL() == null) {
2294 put.setDurability(Durability.SKIP_WAL);
2295 }
2296 int preRowCount = rowCount;
2297 int pause = 10;
2298 int maxPause = 1000;
2299 while (rowCount == preRowCount) {
2300 try {
2301 r.put(put);
2302 rowCount++;
2303 } catch (RegionTooBusyException e) {
2304 pause = (pause * 2 >= maxPause) ? maxPause : pause * 2;
2305 Threads.sleep(pause);
2306 }
2307 }
2308 }
2309 }
2310 if (flush) {
2311 r.flush(true);
2312 }
2313 }
2314 return rowCount;
2315 }
2316
2317 public void loadNumericRows(final Table t, final byte[] f, int startRow, int endRow)
2318 throws IOException {
2319 for (int i = startRow; i < endRow; i++) {
2320 byte[] data = Bytes.toBytes(String.valueOf(i));
2321 Put put = new Put(data);
2322 put.add(f, null, data);
2323 t.put(put);
2324 }
2325 }
2326
2327 public void verifyNumericRows(Table table, final byte[] f, int startRow, int endRow,
2328 int replicaId)
2329 throws IOException {
2330 for (int i = startRow; i < endRow; i++) {
2331 String failMsg = "Failed verification of row :" + i;
2332 byte[] data = Bytes.toBytes(String.valueOf(i));
2333 Get get = new Get(data);
2334 get.setReplicaId(replicaId);
2335 get.setConsistency(Consistency.TIMELINE);
2336 Result result = table.get(get);
2337 assertTrue(failMsg, result.containsColumn(f, null));
2338 assertEquals(failMsg, result.getColumnCells(f, null).size(), 1);
2339 Cell cell = result.getColumnLatestCell(f, null);
2340 assertTrue(failMsg,
2341 Bytes.equals(data, 0, data.length, cell.getValueArray(), cell.getValueOffset(),
2342 cell.getValueLength()));
2343 }
2344 }
2345
2346 public void verifyNumericRows(Region region, final byte[] f, int startRow, int endRow)
2347 throws IOException {
2348 verifyNumericRows((HRegion)region, f, startRow, endRow);
2349 }
2350
2351 public void verifyNumericRows(HRegion region, final byte[] f, int startRow, int endRow)
2352 throws IOException {
2353 verifyNumericRows(region, f, startRow, endRow, true);
2354 }
2355
2356 public void verifyNumericRows(Region region, final byte[] f, int startRow, int endRow,
2357 final boolean present) throws IOException {
2358 verifyNumericRows((HRegion)region, f, startRow, endRow, present);
2359 }
2360
2361 public void verifyNumericRows(HRegion region, final byte[] f, int startRow, int endRow,
2362 final boolean present) throws IOException {
2363 for (int i = startRow; i < endRow; i++) {
2364 String failMsg = "Failed verification of row :" + i;
2365 byte[] data = Bytes.toBytes(String.valueOf(i));
2366 Result result = region.get(new Get(data));
2367
2368 boolean hasResult = result != null && !result.isEmpty();
2369 assertEquals(failMsg + result, present, hasResult);
2370 if (!present) continue;
2371
2372 assertTrue(failMsg, result.containsColumn(f, null));
2373 assertEquals(failMsg, result.getColumnCells(f, null).size(), 1);
2374 Cell cell = result.getColumnLatestCell(f, null);
2375 assertTrue(failMsg,
2376 Bytes.equals(data, 0, data.length, cell.getValueArray(), cell.getValueOffset(),
2377 cell.getValueLength()));
2378 }
2379 }
2380
2381 public void deleteNumericRows(final HTable t, final byte[] f, int startRow, int endRow)
2382 throws IOException {
2383 for (int i = startRow; i < endRow; i++) {
2384 byte[] data = Bytes.toBytes(String.valueOf(i));
2385 Delete delete = new Delete(data);
2386 delete.deleteFamily(f);
2387 t.delete(delete);
2388 }
2389 }
2390
2391
2392
2393
2394 public int countRows(final Table table) throws IOException {
2395 Scan scan = new Scan();
2396 ResultScanner results = table.getScanner(scan);
2397 int count = 0;
2398 for (@SuppressWarnings("unused") Result res : results) {
2399 count++;
2400 }
2401 results.close();
2402 return count;
2403 }
2404
2405 public int countRows(final Table table, final byte[]... families) throws IOException {
2406 Scan scan = new Scan();
2407 for (byte[] family: families) {
2408 scan.addFamily(family);
2409 }
2410 ResultScanner results = table.getScanner(scan);
2411 int count = 0;
2412 for (@SuppressWarnings("unused") Result res : results) {
2413 count++;
2414 }
2415 results.close();
2416 return count;
2417 }
2418
2419
2420
2421
2422 public int countRows(final TableName tableName) throws IOException {
2423 Table table = getConnection().getTable(tableName);
2424 try {
2425 return countRows(table);
2426 } finally {
2427 table.close();
2428 }
2429 }
2430
2431
2432
2433
2434 public String checksumRows(final Table table) throws Exception {
2435 Scan scan = new Scan();
2436 ResultScanner results = table.getScanner(scan);
2437 MessageDigest digest = MessageDigest.getInstance("MD5");
2438 for (Result res : results) {
2439 digest.update(res.getRow());
2440 }
2441 results.close();
2442 return digest.toString();
2443 }
2444
2445
2446 public static final byte[][] ROWS = new byte[(int) Math.pow('z' - 'a' + 1, 3)][3];
2447 static {
2448 int i = 0;
2449 for (byte b1 = 'a'; b1 <= 'z'; b1++) {
2450 for (byte b2 = 'a'; b2 <= 'z'; b2++) {
2451 for (byte b3 = 'a'; b3 <= 'z'; b3++) {
2452 ROWS[i][0] = b1;
2453 ROWS[i][1] = b2;
2454 ROWS[i][2] = b3;
2455 i++;
2456 }
2457 }
2458 }
2459 }
2460
2461 public static final byte[][] KEYS = {
2462 HConstants.EMPTY_BYTE_ARRAY, Bytes.toBytes("bbb"),
2463 Bytes.toBytes("ccc"), Bytes.toBytes("ddd"), Bytes.toBytes("eee"),
2464 Bytes.toBytes("fff"), Bytes.toBytes("ggg"), Bytes.toBytes("hhh"),
2465 Bytes.toBytes("iii"), Bytes.toBytes("jjj"), Bytes.toBytes("kkk"),
2466 Bytes.toBytes("lll"), Bytes.toBytes("mmm"), Bytes.toBytes("nnn"),
2467 Bytes.toBytes("ooo"), Bytes.toBytes("ppp"), Bytes.toBytes("qqq"),
2468 Bytes.toBytes("rrr"), Bytes.toBytes("sss"), Bytes.toBytes("ttt"),
2469 Bytes.toBytes("uuu"), Bytes.toBytes("vvv"), Bytes.toBytes("www"),
2470 Bytes.toBytes("xxx"), Bytes.toBytes("yyy")
2471 };
2472
2473 public static final byte[][] KEYS_FOR_HBA_CREATE_TABLE = {
2474 Bytes.toBytes("bbb"),
2475 Bytes.toBytes("ccc"), Bytes.toBytes("ddd"), Bytes.toBytes("eee"),
2476 Bytes.toBytes("fff"), Bytes.toBytes("ggg"), Bytes.toBytes("hhh"),
2477 Bytes.toBytes("iii"), Bytes.toBytes("jjj"), Bytes.toBytes("kkk"),
2478 Bytes.toBytes("lll"), Bytes.toBytes("mmm"), Bytes.toBytes("nnn"),
2479 Bytes.toBytes("ooo"), Bytes.toBytes("ppp"), Bytes.toBytes("qqq"),
2480 Bytes.toBytes("rrr"), Bytes.toBytes("sss"), Bytes.toBytes("ttt"),
2481 Bytes.toBytes("uuu"), Bytes.toBytes("vvv"), Bytes.toBytes("www"),
2482 Bytes.toBytes("xxx"), Bytes.toBytes("yyy"), Bytes.toBytes("zzz")
2483 };
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495 public List<HRegionInfo> createMultiRegionsInMeta(final Configuration conf,
2496 final HTableDescriptor htd, byte [][] startKeys)
2497 throws IOException {
2498 Table meta = new HTable(conf, TableName.META_TABLE_NAME);
2499 Arrays.sort(startKeys, Bytes.BYTES_COMPARATOR);
2500 List<HRegionInfo> newRegions = new ArrayList<HRegionInfo>(startKeys.length);
2501
2502 for (int i = 0; i < startKeys.length; i++) {
2503 int j = (i + 1) % startKeys.length;
2504 HRegionInfo hri = new HRegionInfo(htd.getTableName(), startKeys[i],
2505 startKeys[j]);
2506 MetaTableAccessor.addRegionToMeta(meta, hri);
2507 newRegions.add(hri);
2508 }
2509
2510 meta.close();
2511 return newRegions;
2512 }
2513
2514
2515
2516
2517
2518
2519 public List<byte[]> getMetaTableRows() throws IOException {
2520
2521 Table t = new HTable(new Configuration(this.conf), TableName.META_TABLE_NAME);
2522 List<byte[]> rows = new ArrayList<byte[]>();
2523 ResultScanner s = t.getScanner(new Scan());
2524 for (Result result : s) {
2525 LOG.info("getMetaTableRows: row -> " +
2526 Bytes.toStringBinary(result.getRow()));
2527 rows.add(result.getRow());
2528 }
2529 s.close();
2530 t.close();
2531 return rows;
2532 }
2533
2534
2535
2536
2537
2538
2539 public List<byte[]> getMetaTableRows(TableName tableName) throws IOException {
2540
2541 Table t = new HTable(new Configuration(this.conf), TableName.META_TABLE_NAME);
2542 List<byte[]> rows = new ArrayList<byte[]>();
2543 ResultScanner s = t.getScanner(new Scan());
2544 for (Result result : s) {
2545 HRegionInfo info = HRegionInfo.getHRegionInfo(result);
2546 if (info == null) {
2547 LOG.error("No region info for row " + Bytes.toString(result.getRow()));
2548
2549 continue;
2550 }
2551
2552 if (info.getTable().equals(tableName)) {
2553 LOG.info("getMetaTableRows: row -> " +
2554 Bytes.toStringBinary(result.getRow()) + info);
2555 rows.add(result.getRow());
2556 }
2557 }
2558 s.close();
2559 t.close();
2560 return rows;
2561 }
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574 public HRegionServer getRSForFirstRegionInTable(TableName tableName)
2575 throws IOException, InterruptedException {
2576 List<byte[]> metaRows = getMetaTableRows(tableName);
2577 if (metaRows == null || metaRows.isEmpty()) {
2578 return null;
2579 }
2580 LOG.debug("Found " + metaRows.size() + " rows for table " +
2581 tableName);
2582 byte [] firstrow = metaRows.get(0);
2583 LOG.debug("FirstRow=" + Bytes.toString(firstrow));
2584 long pause = getConfiguration().getLong(HConstants.HBASE_CLIENT_PAUSE,
2585 HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
2586 int numRetries = getConfiguration().getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
2587 HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
2588 RetryCounter retrier = new RetryCounter(numRetries+1, (int)pause, TimeUnit.MICROSECONDS);
2589 while(retrier.shouldRetry()) {
2590 int index = getMiniHBaseCluster().getServerWith(firstrow);
2591 if (index != -1) {
2592 return getMiniHBaseCluster().getRegionServerThreads().get(index).getRegionServer();
2593 }
2594
2595 retrier.sleepUntilNextRetry();
2596 }
2597 return null;
2598 }
2599
2600
2601
2602
2603
2604
2605
2606 public MiniMRCluster startMiniMapReduceCluster() throws IOException {
2607 startMiniMapReduceCluster(2);
2608 return mrCluster;
2609 }
2610
2611
2612
2613
2614
2615 private void forceChangeTaskLogDir() {
2616 Field logDirField;
2617 try {
2618 logDirField = TaskLog.class.getDeclaredField("LOG_DIR");
2619 logDirField.setAccessible(true);
2620
2621 Field modifiersField = Field.class.getDeclaredField("modifiers");
2622 modifiersField.setAccessible(true);
2623 modifiersField.setInt(logDirField, logDirField.getModifiers() & ~Modifier.FINAL);
2624
2625 logDirField.set(null, new File(hadoopLogDir, "userlogs"));
2626 } catch (SecurityException e) {
2627 throw new RuntimeException(e);
2628 } catch (NoSuchFieldException e) {
2629
2630 throw new RuntimeException(e);
2631 } catch (IllegalArgumentException e) {
2632 throw new RuntimeException(e);
2633 } catch (IllegalAccessException e) {
2634 throw new RuntimeException(e);
2635 }
2636 }
2637
2638
2639
2640
2641
2642
2643
2644 private void startMiniMapReduceCluster(final int servers) throws IOException {
2645 if (mrCluster != null) {
2646 throw new IllegalStateException("MiniMRCluster is already running");
2647 }
2648 LOG.info("Starting mini mapreduce cluster...");
2649 setupClusterTestDir();
2650 createDirsAndSetProperties();
2651
2652 forceChangeTaskLogDir();
2653
2654
2655
2656
2657 conf.setFloat("yarn.nodemanager.vmem-pmem-ratio", 8.0f);
2658
2659
2660
2661 conf.setBoolean("mapreduce.map.speculative", false);
2662 conf.setBoolean("mapreduce.reduce.speculative", false);
2663
2664
2665
2666 mrCluster = new MiniMRCluster(servers,
2667 FS_URI != null ? FS_URI : FileSystem.get(conf).getUri().toString(), 1,
2668 null, null, new JobConf(this.conf));
2669 JobConf jobConf = MapreduceTestingShim.getJobConf(mrCluster);
2670 if (jobConf == null) {
2671 jobConf = mrCluster.createJobConf();
2672 }
2673
2674 jobConf.set("mapreduce.cluster.local.dir",
2675 conf.get("mapreduce.cluster.local.dir"));
2676 LOG.info("Mini mapreduce cluster started");
2677
2678
2679
2680
2681 conf.set("mapreduce.jobtracker.address", jobConf.get("mapreduce.jobtracker.address"));
2682
2683 conf.set("mapreduce.framework.name", "yarn");
2684 conf.setBoolean("yarn.is.minicluster", true);
2685 String rmAddress = jobConf.get("yarn.resourcemanager.address");
2686 if (rmAddress != null) {
2687 conf.set("yarn.resourcemanager.address", rmAddress);
2688 }
2689 String historyAddress = jobConf.get("mapreduce.jobhistory.address");
2690 if (historyAddress != null) {
2691 conf.set("mapreduce.jobhistory.address", historyAddress);
2692 }
2693 String schedulerAddress =
2694 jobConf.get("yarn.resourcemanager.scheduler.address");
2695 if (schedulerAddress != null) {
2696 conf.set("yarn.resourcemanager.scheduler.address", schedulerAddress);
2697 }
2698 String mrJobHistoryWebappAddress =
2699 jobConf.get("mapreduce.jobhistory.webapp.address");
2700 if (mrJobHistoryWebappAddress != null) {
2701 conf.set("mapreduce.jobhistory.webapp.address", mrJobHistoryWebappAddress);
2702 }
2703 String yarnRMWebappAddress =
2704 jobConf.get("yarn.resourcemanager.webapp.address");
2705 if (yarnRMWebappAddress != null) {
2706 conf.set("yarn.resourcemanager.webapp.address", yarnRMWebappAddress);
2707 }
2708 }
2709
2710
2711
2712
2713 public void shutdownMiniMapReduceCluster() {
2714 if (mrCluster != null) {
2715 LOG.info("Stopping mini mapreduce cluster...");
2716 mrCluster.shutdown();
2717 mrCluster = null;
2718 LOG.info("Mini mapreduce cluster stopped");
2719 }
2720
2721 conf.set("mapreduce.jobtracker.address", "local");
2722 }
2723
2724
2725
2726
2727 public RegionServerServices createMockRegionServerService() throws IOException {
2728 return createMockRegionServerService((ServerName)null);
2729 }
2730
2731
2732
2733
2734
2735 public RegionServerServices createMockRegionServerService(RpcServerInterface rpc) throws IOException {
2736 final MockRegionServerServices rss = new MockRegionServerServices(getZooKeeperWatcher());
2737 rss.setFileSystem(getTestFileSystem());
2738 rss.setRpcServer(rpc);
2739 return rss;
2740 }
2741
2742
2743
2744
2745
2746 public RegionServerServices createMockRegionServerService(ServerName name) throws IOException {
2747 final MockRegionServerServices rss = new MockRegionServerServices(getZooKeeperWatcher(), name);
2748 rss.setFileSystem(getTestFileSystem());
2749 return rss;
2750 }
2751
2752
2753
2754
2755
2756
2757 public void enableDebug(Class<?> clazz) {
2758 Log l = LogFactory.getLog(clazz);
2759 if (l instanceof Log4JLogger) {
2760 ((Log4JLogger) l).getLogger().setLevel(org.apache.log4j.Level.DEBUG);
2761 } else if (l instanceof Jdk14Logger) {
2762 ((Jdk14Logger) l).getLogger().setLevel(java.util.logging.Level.ALL);
2763 }
2764 }
2765
2766
2767
2768
2769
2770 public void expireMasterSession() throws Exception {
2771 HMaster master = getMiniHBaseCluster().getMaster();
2772 expireSession(master.getZooKeeper(), false);
2773 }
2774
2775
2776
2777
2778
2779
2780 public void expireRegionServerSession(int index) throws Exception {
2781 HRegionServer rs = getMiniHBaseCluster().getRegionServer(index);
2782 expireSession(rs.getZooKeeper(), false);
2783 decrementMinRegionServerCount();
2784 }
2785
2786 private void decrementMinRegionServerCount() {
2787
2788
2789 decrementMinRegionServerCount(getConfiguration());
2790
2791
2792 for (MasterThread master : getHBaseCluster().getMasterThreads()) {
2793 decrementMinRegionServerCount(master.getMaster().getConfiguration());
2794 }
2795 }
2796
2797 private void decrementMinRegionServerCount(Configuration conf) {
2798 int currentCount = conf.getInt(
2799 ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, -1);
2800 if (currentCount != -1) {
2801 conf.setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART,
2802 Math.max(currentCount - 1, 1));
2803 }
2804 }
2805
2806 public void expireSession(ZooKeeperWatcher nodeZK) throws Exception {
2807 expireSession(nodeZK, false);
2808 }
2809
2810 @Deprecated
2811 public void expireSession(ZooKeeperWatcher nodeZK, Server server)
2812 throws Exception {
2813 expireSession(nodeZK, false);
2814 }
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827 public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus)
2828 throws Exception {
2829 Configuration c = new Configuration(this.conf);
2830 String quorumServers = ZKConfig.getZKQuorumServersString(c);
2831 ZooKeeper zk = nodeZK.getRecoverableZooKeeper().getZooKeeper();
2832 byte[] password = zk.getSessionPasswd();
2833 long sessionID = zk.getSessionId();
2834
2835
2836
2837
2838
2839
2840
2841
2842 ZooKeeper monitor = new ZooKeeper(quorumServers,
2843 1000, new org.apache.zookeeper.Watcher(){
2844 @Override
2845 public void process(WatchedEvent watchedEvent) {
2846 LOG.info("Monitor ZKW received event="+watchedEvent);
2847 }
2848 } , sessionID, password);
2849
2850
2851 ZooKeeper newZK = new ZooKeeper(quorumServers,
2852 1000, EmptyWatcher.instance, sessionID, password);
2853
2854
2855
2856 long start = System.currentTimeMillis();
2857 while (newZK.getState() != States.CONNECTED
2858 && System.currentTimeMillis() - start < 1000) {
2859 Thread.sleep(1);
2860 }
2861 newZK.close();
2862 LOG.info("ZK Closed Session 0x" + Long.toHexString(sessionID));
2863
2864
2865 monitor.close();
2866
2867 if (checkStatus) {
2868 new HTable(new Configuration(conf), TableName.META_TABLE_NAME).close();
2869 }
2870 }
2871
2872
2873
2874
2875
2876
2877
2878 public MiniHBaseCluster getHBaseCluster() {
2879 return getMiniHBaseCluster();
2880 }
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890 public HBaseCluster getHBaseClusterInterface() {
2891
2892
2893 return hbaseCluster;
2894 }
2895
2896
2897
2898
2899
2900
2901
2902 public Connection getConnection() throws IOException {
2903 if (this.connection == null) {
2904 this.connection = ConnectionFactory.createConnection(this.conf);
2905 }
2906 return this.connection;
2907 }
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918 public synchronized HBaseAdmin getHBaseAdmin()
2919 throws IOException {
2920 if (hbaseAdmin == null){
2921 this.hbaseAdmin = new HBaseAdminForTests(getConnection());
2922 }
2923 return hbaseAdmin;
2924 }
2925
2926 private HBaseAdminForTests hbaseAdmin = null;
2927 private static class HBaseAdminForTests extends HBaseAdmin {
2928 public HBaseAdminForTests(Connection connection) throws MasterNotRunningException,
2929 ZooKeeperConnectionException, IOException {
2930 super(connection);
2931 }
2932
2933 @Override
2934 public synchronized void close() throws IOException {
2935 LOG.warn("close() called on HBaseAdmin instance returned from " +
2936 "HBaseTestingUtility.getHBaseAdmin()");
2937 }
2938
2939 private synchronized void close0() throws IOException {
2940 super.close();
2941 }
2942 }
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953 public synchronized ZooKeeperWatcher getZooKeeperWatcher()
2954 throws IOException {
2955 if (zooKeeperWatcher == null) {
2956 zooKeeperWatcher = new ZooKeeperWatcher(conf, "testing utility",
2957 new Abortable() {
2958 @Override public void abort(String why, Throwable e) {
2959 throw new RuntimeException("Unexpected abort in HBaseTestingUtility:"+why, e);
2960 }
2961 @Override public boolean isAborted() {return false;}
2962 });
2963 }
2964 return zooKeeperWatcher;
2965 }
2966 private ZooKeeperWatcher zooKeeperWatcher;
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976 public void closeRegion(String regionName) throws IOException {
2977 closeRegion(Bytes.toBytes(regionName));
2978 }
2979
2980
2981
2982
2983
2984
2985
2986 public void closeRegion(byte[] regionName) throws IOException {
2987 getHBaseAdmin().closeRegion(regionName, null);
2988 }
2989
2990
2991
2992
2993
2994
2995
2996
2997 public void closeRegionByRow(String row, RegionLocator table) throws IOException {
2998 closeRegionByRow(Bytes.toBytes(row), table);
2999 }
3000
3001
3002
3003
3004
3005
3006
3007
3008 public void closeRegionByRow(byte[] row, RegionLocator table) throws IOException {
3009 HRegionLocation hrl = table.getRegionLocation(row);
3010 closeRegion(hrl.getRegionInfo().getRegionName());
3011 }
3012
3013
3014
3015
3016
3017
3018
3019
3020 public HRegion getSplittableRegion(TableName tableName, int maxAttempts) {
3021 List<HRegion> regions = getHBaseCluster().getRegions(tableName);
3022 int regCount = regions.size();
3023 Set<Integer> attempted = new HashSet<Integer>();
3024 int idx;
3025 int attempts = 0;
3026 do {
3027 regions = getHBaseCluster().getRegions(tableName);
3028 if (regCount != regions.size()) {
3029
3030 attempted.clear();
3031 }
3032 regCount = regions.size();
3033
3034
3035 if (regCount > 0) {
3036 idx = random.nextInt(regCount);
3037
3038 if (attempted.contains(idx))
3039 continue;
3040 try {
3041 regions.get(idx).checkSplit();
3042 return regions.get(idx);
3043 } catch (Exception ex) {
3044 LOG.warn("Caught exception", ex);
3045 attempted.add(idx);
3046 }
3047 }
3048 attempts++;
3049 } while (maxAttempts == -1 || attempts < maxAttempts);
3050 return null;
3051 }
3052
3053 public MiniZooKeeperCluster getZkCluster() {
3054 return zkCluster;
3055 }
3056
3057 public void setZkCluster(MiniZooKeeperCluster zkCluster) {
3058 this.passedZkCluster = true;
3059 this.zkCluster = zkCluster;
3060 conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkCluster.getClientPort());
3061 }
3062
3063 public MiniDFSCluster getDFSCluster() {
3064 return dfsCluster;
3065 }
3066
3067 public void setDFSCluster(MiniDFSCluster cluster) throws IllegalStateException, IOException {
3068 setDFSCluster(cluster, true);
3069 }
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079 public void setDFSCluster(MiniDFSCluster cluster, boolean requireDown)
3080 throws IllegalStateException, IOException {
3081 if (dfsCluster != null && requireDown && dfsCluster.isClusterUp()) {
3082 throw new IllegalStateException("DFSCluster is already running! Shut it down first.");
3083 }
3084 this.dfsCluster = cluster;
3085 this.setFs();
3086 }
3087
3088 public FileSystem getTestFileSystem() throws IOException {
3089 return HFileSystem.get(conf);
3090 }
3091
3092
3093
3094
3095
3096
3097
3098
3099 public void waitTableAvailable(TableName table)
3100 throws InterruptedException, IOException {
3101 waitTableAvailable(table.getName(), 30000);
3102 }
3103
3104 public void waitTableAvailable(TableName table, long timeoutMillis)
3105 throws InterruptedException, IOException {
3106 waitFor(timeoutMillis, predicateTableAvailable(table));
3107 }
3108
3109 public String explainTableAvailability(TableName tableName) throws IOException {
3110 String msg = explainTableState(tableName) + ",";
3111 if (getHBaseCluster().getMaster().isAlive()) {
3112 Map<HRegionInfo, ServerName> assignments =
3113 getHBaseCluster().getMaster().getAssignmentManager().getRegionStates()
3114 .getRegionAssignments();
3115 final List<Pair<HRegionInfo, ServerName>> metaLocations =
3116 MetaTableAccessor
3117 .getTableRegionsAndLocations(getZooKeeperWatcher(), connection, tableName);
3118 for (Pair<HRegionInfo, ServerName> metaLocation : metaLocations) {
3119 HRegionInfo hri = metaLocation.getFirst();
3120 ServerName sn = metaLocation.getSecond();
3121 if (!assignments.containsKey(hri)) {
3122 msg += ", region " + hri
3123 + " not assigned, but found in meta, it expected to be on " + sn;
3124
3125 } else if (sn == null) {
3126 msg += ", region " + hri
3127 + " assigned, but has no server in meta";
3128 } else if (!sn.equals(assignments.get(hri))) {
3129 msg += ", region " + hri
3130 + " assigned, but has different servers in meta and AM ( " +
3131 sn + " <> " + assignments.get(hri);
3132 }
3133 }
3134 }
3135 return msg;
3136 }
3137
3138 public String explainTableState(TableName tableName) throws IOException {
3139 try {
3140 if (getHBaseAdmin().isTableEnabled(tableName))
3141 return "table enabled in zk";
3142 else if (getHBaseAdmin().isTableDisabled(tableName))
3143 return "table disabled in zk";
3144 else
3145 return "table in uknown state";
3146 } catch (TableNotFoundException e) {
3147 return "table not exists";
3148 }
3149 }
3150
3151
3152
3153
3154
3155
3156
3157
3158 public void waitTableAvailable(byte[] table, long timeoutMillis)
3159 throws InterruptedException, IOException {
3160 waitTableAvailable(getHBaseAdmin(), table, timeoutMillis);
3161 }
3162
3163 public void waitTableAvailable(Admin admin, byte[] table, long timeoutMillis)
3164 throws InterruptedException, IOException {
3165 long startWait = System.currentTimeMillis();
3166 while (!admin.isTableAvailable(TableName.valueOf(table))) {
3167 assertTrue("Timed out waiting for table to become available " +
3168 Bytes.toStringBinary(table),
3169 System.currentTimeMillis() - startWait < timeoutMillis);
3170 Thread.sleep(200);
3171 }
3172 }
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183 public void waitTableEnabled(TableName table)
3184 throws InterruptedException, IOException {
3185 waitTableEnabled(table, 30000);
3186 }
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197 public void waitTableEnabled(byte[] table, long timeoutMillis)
3198 throws InterruptedException, IOException {
3199 waitTableEnabled(TableName.valueOf(table), timeoutMillis);
3200 }
3201
3202 public void waitTableEnabled(TableName table, long timeoutMillis)
3203 throws IOException {
3204 waitFor(timeoutMillis, predicateTableEnabled(table));
3205 }
3206
3207
3208
3209
3210
3211
3212
3213
3214 public void waitTableDisabled(byte[] table)
3215 throws InterruptedException, IOException {
3216 waitTableDisabled(getHBaseAdmin(), table, 30000);
3217 }
3218
3219 public void waitTableDisabled(Admin admin, byte[] table)
3220 throws InterruptedException, IOException {
3221 waitTableDisabled(admin, table, 30000);
3222 }
3223
3224
3225
3226
3227
3228
3229
3230
3231 public void waitTableDisabled(byte[] table, long timeoutMillis)
3232 throws InterruptedException, IOException {
3233 waitTableDisabled(getHBaseAdmin(), table, timeoutMillis);
3234 }
3235
3236 public void waitTableDisabled(Admin admin, byte[] table, long timeoutMillis)
3237 throws InterruptedException, IOException {
3238 TableName tableName = TableName.valueOf(table);
3239 long startWait = System.currentTimeMillis();
3240 while (!admin.isTableDisabled(tableName)) {
3241 assertTrue("Timed out waiting for table to become disabled " +
3242 Bytes.toStringBinary(table),
3243 System.currentTimeMillis() - startWait < timeoutMillis);
3244 Thread.sleep(200);
3245 }
3246 }
3247
3248
3249
3250
3251
3252
3253
3254
3255 public boolean ensureSomeRegionServersAvailable(final int num)
3256 throws IOException {
3257 boolean startedServer = false;
3258 MiniHBaseCluster hbaseCluster = getMiniHBaseCluster();
3259 for (int i=hbaseCluster.getLiveRegionServerThreads().size(); i<num; ++i) {
3260 LOG.info("Started new server=" + hbaseCluster.startRegionServer());
3261 startedServer = true;
3262 }
3263
3264 return startedServer;
3265 }
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276 public boolean ensureSomeNonStoppedRegionServersAvailable(final int num)
3277 throws IOException {
3278 boolean startedServer = ensureSomeRegionServersAvailable(num);
3279
3280 int nonStoppedServers = 0;
3281 for (JVMClusterUtil.RegionServerThread rst :
3282 getMiniHBaseCluster().getRegionServerThreads()) {
3283
3284 HRegionServer hrs = rst.getRegionServer();
3285 if (hrs.isStopping() || hrs.isStopped()) {
3286 LOG.info("A region server is stopped or stopping:"+hrs);
3287 } else {
3288 nonStoppedServers++;
3289 }
3290 }
3291 for (int i=nonStoppedServers; i<num; ++i) {
3292 LOG.info("Started new server=" + getMiniHBaseCluster().startRegionServer());
3293 startedServer = true;
3294 }
3295 return startedServer;
3296 }
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308 public static User getDifferentUser(final Configuration c,
3309 final String differentiatingSuffix)
3310 throws IOException {
3311 FileSystem currentfs = FileSystem.get(c);
3312 if (!(currentfs instanceof DistributedFileSystem) || User.isHBaseSecurityEnabled(c)) {
3313 return User.getCurrent();
3314 }
3315
3316
3317 String username = User.getCurrent().getName() +
3318 differentiatingSuffix;
3319 User user = User.createUserForTesting(c, username,
3320 new String[]{"supergroup"});
3321 return user;
3322 }
3323
3324 public static NavigableSet<String> getAllOnlineRegions(MiniHBaseCluster cluster)
3325 throws IOException {
3326 NavigableSet<String> online = new TreeSet<String>();
3327 for (RegionServerThread rst : cluster.getLiveRegionServerThreads()) {
3328 try {
3329 for (HRegionInfo region :
3330 ProtobufUtil.getOnlineRegions(rst.getRegionServer().getRSRpcServices())) {
3331 online.add(region.getRegionNameAsString());
3332 }
3333 } catch (RegionServerStoppedException e) {
3334
3335 }
3336 }
3337 for (MasterThread mt : cluster.getLiveMasterThreads()) {
3338 try {
3339 for (HRegionInfo region :
3340 ProtobufUtil.getOnlineRegions(mt.getMaster().getRSRpcServices())) {
3341 online.add(region.getRegionNameAsString());
3342 }
3343 } catch (RegionServerStoppedException e) {
3344
3345 } catch (ServerNotRunningYetException e) {
3346
3347 }
3348 }
3349 return online;
3350 }
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365 public static void setMaxRecoveryErrorCount(final OutputStream stream,
3366 final int max) {
3367 try {
3368 Class<?> [] clazzes = DFSClient.class.getDeclaredClasses();
3369 for (Class<?> clazz: clazzes) {
3370 String className = clazz.getSimpleName();
3371 if (className.equals("DFSOutputStream")) {
3372 if (clazz.isInstance(stream)) {
3373 Field maxRecoveryErrorCountField =
3374 stream.getClass().getDeclaredField("maxRecoveryErrorCount");
3375 maxRecoveryErrorCountField.setAccessible(true);
3376 maxRecoveryErrorCountField.setInt(stream, max);
3377 break;
3378 }
3379 }
3380 }
3381 } catch (Exception e) {
3382 LOG.info("Could not set max recovery field", e);
3383 }
3384 }
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395 public void waitUntilAllRegionsAssigned(final TableName tableName) throws IOException {
3396 waitUntilAllRegionsAssigned(
3397 tableName,
3398 this.conf.getLong("hbase.client.sync.wait.timeout.msec", 60000));
3399 }
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410 public void waitUntilAllRegionsAssigned(final TableName tableName, final long timeout)
3411 throws IOException {
3412 final Table meta = new HTable(getConfiguration(), TableName.META_TABLE_NAME);
3413 try {
3414 waitFor(timeout, 200, true, new Predicate<IOException>() {
3415 @Override
3416 public boolean evaluate() throws IOException {
3417 boolean allRegionsAssigned = true;
3418 Scan scan = new Scan();
3419 scan.addFamily(HConstants.CATALOG_FAMILY);
3420 ResultScanner s = meta.getScanner(scan);
3421 try {
3422 Result r;
3423 while ((r = s.next()) != null) {
3424 byte[] b = r.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
3425 HRegionInfo info = HRegionInfo.parseFromOrNull(b);
3426 if (info != null && info.getTable().equals(tableName)) {
3427 b = r.getValue(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER);
3428 allRegionsAssigned &= (b != null);
3429 }
3430 }
3431 } finally {
3432 s.close();
3433 }
3434 return allRegionsAssigned;
3435 }
3436 });
3437 } finally {
3438 meta.close();
3439 }
3440
3441
3442 if (!getHBaseClusterInterface().isDistributedCluster()) {
3443
3444
3445 HMaster master = getHBaseCluster().getMaster();
3446 final RegionStates states = master.getAssignmentManager().getRegionStates();
3447 waitFor(timeout, 200, new ExplainingPredicate<IOException>() {
3448 @Override
3449 public String explainFailure() throws IOException {
3450 return explainTableAvailability(tableName);
3451 }
3452
3453 @Override
3454 public boolean evaluate() throws IOException {
3455 List<HRegionInfo> hris = states.getRegionsOfTable(tableName);
3456 return hris != null && !hris.isEmpty();
3457 }
3458 });
3459 }
3460 }
3461
3462
3463
3464
3465
3466 public static List<Cell> getFromStoreFile(HStore store,
3467 Get get) throws IOException {
3468 Scan scan = new Scan(get);
3469 InternalScanner scanner = (InternalScanner) store.getScanner(scan,
3470 scan.getFamilyMap().get(store.getFamily().getName()),
3471
3472
3473 0);
3474
3475 List<Cell> result = new ArrayList<Cell>();
3476 scanner.next(result);
3477 if (!result.isEmpty()) {
3478
3479 Cell kv = result.get(0);
3480 if (!CellUtil.matchingRow(kv, get.getRow())) {
3481 result.clear();
3482 }
3483 }
3484 scanner.close();
3485 return result;
3486 }
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496 public byte[][] getRegionSplitStartKeys(byte[] startKey, byte[] endKey, int numRegions){
3497 assertTrue(numRegions>3);
3498 byte [][] tmpSplitKeys = Bytes.split(startKey, endKey, numRegions - 3);
3499 byte [][] result = new byte[tmpSplitKeys.length+1][];
3500 System.arraycopy(tmpSplitKeys, 0, result, 1, tmpSplitKeys.length);
3501 result[0] = HConstants.EMPTY_BYTE_ARRAY;
3502 return result;
3503 }
3504
3505
3506
3507
3508
3509 public static List<Cell> getFromStoreFile(HStore store,
3510 byte [] row,
3511 NavigableSet<byte[]> columns
3512 ) throws IOException {
3513 Get get = new Get(row);
3514 Map<byte[], NavigableSet<byte[]>> s = get.getFamilyMap();
3515 s.put(store.getFamily().getName(), columns);
3516
3517 return getFromStoreFile(store,get);
3518 }
3519
3520
3521
3522
3523
3524 public static ZooKeeperWatcher getZooKeeperWatcher(
3525 HBaseTestingUtility TEST_UTIL) throws ZooKeeperConnectionException,
3526 IOException {
3527 ZooKeeperWatcher zkw = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(),
3528 "unittest", new Abortable() {
3529 boolean aborted = false;
3530
3531 @Override
3532 public void abort(String why, Throwable e) {
3533 aborted = true;
3534 throw new RuntimeException("Fatal ZK error, why=" + why, e);
3535 }
3536
3537 @Override
3538 public boolean isAborted() {
3539 return aborted;
3540 }
3541 });
3542 return zkw;
3543 }
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556 public static ZooKeeperWatcher createAndForceNodeToOpenedState(
3557 HBaseTestingUtility TEST_UTIL, Region region,
3558 ServerName serverName) throws ZooKeeperConnectionException,
3559 IOException, KeeperException, NodeExistsException {
3560 return createAndForceNodeToOpenedState(TEST_UTIL, (HRegion)region, serverName);
3561 }
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574 public static ZooKeeperWatcher createAndForceNodeToOpenedState(
3575 HBaseTestingUtility TEST_UTIL, HRegion region,
3576 ServerName serverName) throws ZooKeeperConnectionException,
3577 IOException, KeeperException, NodeExistsException {
3578 ZooKeeperWatcher zkw = getZooKeeperWatcher(TEST_UTIL);
3579 ZKAssign.createNodeOffline(zkw, region.getRegionInfo(), serverName);
3580 int version = ZKAssign.transitionNodeOpening(zkw, region
3581 .getRegionInfo(), serverName);
3582 ZKAssign.transitionNodeOpened(zkw, region.getRegionInfo(), serverName,
3583 version);
3584 return zkw;
3585 }
3586
3587 public static void assertKVListsEqual(String additionalMsg,
3588 final List<? extends Cell> expected,
3589 final List<? extends Cell> actual) {
3590 final int eLen = expected.size();
3591 final int aLen = actual.size();
3592 final int minLen = Math.min(eLen, aLen);
3593
3594 int i;
3595 for (i = 0; i < minLen
3596 && KeyValue.COMPARATOR.compare(expected.get(i), actual.get(i)) == 0;
3597 ++i) {}
3598
3599 if (additionalMsg == null) {
3600 additionalMsg = "";
3601 }
3602 if (!additionalMsg.isEmpty()) {
3603 additionalMsg = ". " + additionalMsg;
3604 }
3605
3606 if (eLen != aLen || i != minLen) {
3607 throw new AssertionError(
3608 "Expected and actual KV arrays differ at position " + i + ": " +
3609 safeGetAsStr(expected, i) + " (length " + eLen +") vs. " +
3610 safeGetAsStr(actual, i) + " (length " + aLen + ")" + additionalMsg);
3611 }
3612 }
3613
3614 public static <T> String safeGetAsStr(List<T> lst, int i) {
3615 if (0 <= i && i < lst.size()) {
3616 return lst.get(i).toString();
3617 } else {
3618 return "<out_of_range>";
3619 }
3620 }
3621
3622 public String getClusterKey() {
3623 return conf.get(HConstants.ZOOKEEPER_QUORUM) + ":"
3624 + conf.get(HConstants.ZOOKEEPER_CLIENT_PORT) + ":"
3625 + conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
3626 HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
3627 }
3628
3629
3630 public HTable createRandomTable(String tableName,
3631 final Collection<String> families,
3632 final int maxVersions,
3633 final int numColsPerRow,
3634 final int numFlushes,
3635 final int numRegions,
3636 final int numRowsPerFlush)
3637 throws IOException, InterruptedException {
3638
3639 LOG.info("\n\nCreating random table " + tableName + " with " + numRegions +
3640 " regions, " + numFlushes + " storefiles per region, " +
3641 numRowsPerFlush + " rows per flush, maxVersions=" + maxVersions +
3642 "\n");
3643
3644 final Random rand = new Random(tableName.hashCode() * 17L + 12938197137L);
3645 final int numCF = families.size();
3646 final byte[][] cfBytes = new byte[numCF][];
3647 {
3648 int cfIndex = 0;
3649 for (String cf : families) {
3650 cfBytes[cfIndex++] = Bytes.toBytes(cf);
3651 }
3652 }
3653
3654 final int actualStartKey = 0;
3655 final int actualEndKey = Integer.MAX_VALUE;
3656 final int keysPerRegion = (actualEndKey - actualStartKey) / numRegions;
3657 final int splitStartKey = actualStartKey + keysPerRegion;
3658 final int splitEndKey = actualEndKey - keysPerRegion;
3659 final String keyFormat = "%08x";
3660 final HTable table = createTable(tableName, cfBytes,
3661 maxVersions,
3662 Bytes.toBytes(String.format(keyFormat, splitStartKey)),
3663 Bytes.toBytes(String.format(keyFormat, splitEndKey)),
3664 numRegions);
3665
3666 if (hbaseCluster != null) {
3667 getMiniHBaseCluster().flushcache(TableName.META_TABLE_NAME);
3668 }
3669
3670 for (int iFlush = 0; iFlush < numFlushes; ++iFlush) {
3671 for (int iRow = 0; iRow < numRowsPerFlush; ++iRow) {
3672 final byte[] row = Bytes.toBytes(String.format(keyFormat,
3673 actualStartKey + rand.nextInt(actualEndKey - actualStartKey)));
3674
3675 Put put = new Put(row);
3676 Delete del = new Delete(row);
3677 for (int iCol = 0; iCol < numColsPerRow; ++iCol) {
3678 final byte[] cf = cfBytes[rand.nextInt(numCF)];
3679 final long ts = rand.nextInt();
3680 final byte[] qual = Bytes.toBytes("col" + iCol);
3681 if (rand.nextBoolean()) {
3682 final byte[] value = Bytes.toBytes("value_for_row_" + iRow +
3683 "_cf_" + Bytes.toStringBinary(cf) + "_col_" + iCol + "_ts_" +
3684 ts + "_random_" + rand.nextLong());
3685 put.add(cf, qual, ts, value);
3686 } else if (rand.nextDouble() < 0.8) {
3687 del.deleteColumn(cf, qual, ts);
3688 } else {
3689 del.deleteColumns(cf, qual, ts);
3690 }
3691 }
3692
3693 if (!put.isEmpty()) {
3694 table.put(put);
3695 }
3696
3697 if (!del.isEmpty()) {
3698 table.delete(del);
3699 }
3700 }
3701 LOG.info("Initiating flush #" + iFlush + " for table " + tableName);
3702 table.flushCommits();
3703 if (hbaseCluster != null) {
3704 getMiniHBaseCluster().flushcache(table.getName());
3705 }
3706 }
3707
3708 return table;
3709 }
3710
3711 private static final int MIN_RANDOM_PORT = 0xc000;
3712 private static final int MAX_RANDOM_PORT = 0xfffe;
3713 private static Random random = new Random();
3714
3715
3716
3717
3718
3719 public static int randomPort() {
3720 return MIN_RANDOM_PORT
3721 + random.nextInt(MAX_RANDOM_PORT - MIN_RANDOM_PORT);
3722 }
3723
3724
3725
3726
3727
3728 public static int randomFreePort() {
3729 int port = 0;
3730 do {
3731 port = randomPort();
3732 if (takenRandomPorts.contains(port)) {
3733 port = 0;
3734 continue;
3735 }
3736 takenRandomPorts.add(port);
3737
3738 try {
3739 ServerSocket sock = new ServerSocket(port);
3740 sock.close();
3741 } catch (IOException ex) {
3742 port = 0;
3743 }
3744 } while (port == 0);
3745 return port;
3746 }
3747
3748
3749 public static String randomMultiCastAddress() {
3750 return "226.1.1." + random.nextInt(254);
3751 }
3752
3753
3754
3755 public static void waitForHostPort(String host, int port)
3756 throws IOException {
3757 final int maxTimeMs = 10000;
3758 final int maxNumAttempts = maxTimeMs / HConstants.SOCKET_RETRY_WAIT_MS;
3759 IOException savedException = null;
3760 LOG.info("Waiting for server at " + host + ":" + port);
3761 for (int attempt = 0; attempt < maxNumAttempts; ++attempt) {
3762 try {
3763 Socket sock = new Socket(InetAddress.getByName(host), port);
3764 sock.close();
3765 savedException = null;
3766 LOG.info("Server at " + host + ":" + port + " is available");
3767 break;
3768 } catch (UnknownHostException e) {
3769 throw new IOException("Failed to look up " + host, e);
3770 } catch (IOException e) {
3771 savedException = e;
3772 }
3773 Threads.sleepWithoutInterrupt(HConstants.SOCKET_RETRY_WAIT_MS);
3774 }
3775
3776 if (savedException != null) {
3777 throw savedException;
3778 }
3779 }
3780
3781
3782
3783
3784
3785
3786 public static int createPreSplitLoadTestTable(Configuration conf,
3787 TableName tableName, byte[] columnFamily, Algorithm compression,
3788 DataBlockEncoding dataBlockEncoding) throws IOException {
3789 return createPreSplitLoadTestTable(conf, tableName,
3790 columnFamily, compression, dataBlockEncoding, DEFAULT_REGIONS_PER_SERVER, 1,
3791 Durability.USE_DEFAULT);
3792 }
3793
3794
3795
3796
3797
3798 public static int createPreSplitLoadTestTable(Configuration conf,
3799 TableName tableName, byte[] columnFamily, Algorithm compression,
3800 DataBlockEncoding dataBlockEncoding, int numRegionsPerServer, int regionReplication,
3801 Durability durability)
3802 throws IOException {
3803 HTableDescriptor desc = new HTableDescriptor(tableName);
3804 desc.setDurability(durability);
3805 desc.setRegionReplication(regionReplication);
3806 HColumnDescriptor hcd = new HColumnDescriptor(columnFamily);
3807 hcd.setDataBlockEncoding(dataBlockEncoding);
3808 hcd.setCompressionType(compression);
3809 return createPreSplitLoadTestTable(conf, desc, hcd, numRegionsPerServer);
3810 }
3811
3812
3813
3814
3815
3816
3817 public static int createPreSplitLoadTestTable(Configuration conf,
3818 TableName tableName, byte[][] columnFamilies, Algorithm compression,
3819 DataBlockEncoding dataBlockEncoding, int numRegionsPerServer, int regionReplication,
3820 Durability durability)
3821 throws IOException {
3822 HTableDescriptor desc = new HTableDescriptor(tableName);
3823 desc.setDurability(durability);
3824 desc.setRegionReplication(regionReplication);
3825 HColumnDescriptor[] hcds = new HColumnDescriptor[columnFamilies.length];
3826 for (int i = 0; i < columnFamilies.length; i++) {
3827 HColumnDescriptor hcd = new HColumnDescriptor(columnFamilies[i]);
3828 hcd.setDataBlockEncoding(dataBlockEncoding);
3829 hcd.setCompressionType(compression);
3830 hcds[i] = hcd;
3831 }
3832 return createPreSplitLoadTestTable(conf, desc, hcds, numRegionsPerServer);
3833 }
3834
3835
3836
3837
3838
3839
3840 public static int createPreSplitLoadTestTable(Configuration conf,
3841 HTableDescriptor desc, HColumnDescriptor hcd) throws IOException {
3842 return createPreSplitLoadTestTable(conf, desc, hcd, DEFAULT_REGIONS_PER_SERVER);
3843 }
3844
3845
3846
3847
3848
3849
3850 public static int createPreSplitLoadTestTable(Configuration conf,
3851 HTableDescriptor desc, HColumnDescriptor hcd, int numRegionsPerServer) throws IOException {
3852 return createPreSplitLoadTestTable(conf, desc, new HColumnDescriptor[] {hcd},
3853 numRegionsPerServer);
3854 }
3855
3856
3857
3858
3859
3860
3861 public static int createPreSplitLoadTestTable(Configuration conf,
3862 HTableDescriptor desc, HColumnDescriptor[] hcds, int numRegionsPerServer) throws IOException {
3863 for (HColumnDescriptor hcd : hcds) {
3864 if (!desc.hasFamily(hcd.getName())) {
3865 desc.addFamily(hcd);
3866 }
3867 }
3868
3869 int totalNumberOfRegions = 0;
3870 Connection unmanagedConnection = ConnectionFactory.createConnection(conf);
3871 Admin admin = unmanagedConnection.getAdmin();
3872
3873 try {
3874
3875
3876
3877 int numberOfServers = admin.getClusterStatus().getServers().size();
3878 if (numberOfServers == 0) {
3879 throw new IllegalStateException("No live regionservers");
3880 }
3881
3882 totalNumberOfRegions = numberOfServers * numRegionsPerServer;
3883 LOG.info("Number of live regionservers: " + numberOfServers + ", " +
3884 "pre-splitting table into " + totalNumberOfRegions + " regions " +
3885 "(regions per server: " + numRegionsPerServer + ")");
3886
3887 byte[][] splits = new RegionSplitter.HexStringSplit().split(
3888 totalNumberOfRegions);
3889
3890 admin.createTable(desc, splits);
3891 } catch (MasterNotRunningException e) {
3892 LOG.error("Master not running", e);
3893 throw new IOException(e);
3894 } catch (TableExistsException e) {
3895 LOG.warn("Table " + desc.getTableName() +
3896 " already exists, continuing");
3897 } finally {
3898 admin.close();
3899 unmanagedConnection.close();
3900 }
3901 return totalNumberOfRegions;
3902 }
3903
3904 public static int getMetaRSPort(Configuration conf) throws IOException {
3905 try (Connection c = ConnectionFactory.createConnection();
3906 RegionLocator locator = c.getRegionLocator(TableName.META_TABLE_NAME)) {
3907 return locator.getRegionLocation(Bytes.toBytes("")).getPort();
3908 }
3909 }
3910
3911
3912
3913
3914
3915
3916
3917 public void assertRegionOnServer(
3918 final HRegionInfo hri, final ServerName server,
3919 final long timeout) throws IOException, InterruptedException {
3920 long timeoutTime = System.currentTimeMillis() + timeout;
3921 while (true) {
3922 List<HRegionInfo> regions = getHBaseAdmin().getOnlineRegions(server);
3923 if (regions.contains(hri)) return;
3924 long now = System.currentTimeMillis();
3925 if (now > timeoutTime) break;
3926 Thread.sleep(10);
3927 }
3928 fail("Could not find region " + hri.getRegionNameAsString()
3929 + " on server " + server);
3930 }
3931
3932
3933
3934
3935
3936 public void assertRegionOnlyOnServer(
3937 final HRegionInfo hri, final ServerName server,
3938 final long timeout) throws IOException, InterruptedException {
3939 long timeoutTime = System.currentTimeMillis() + timeout;
3940 while (true) {
3941 List<HRegionInfo> regions = getHBaseAdmin().getOnlineRegions(server);
3942 if (regions.contains(hri)) {
3943 List<JVMClusterUtil.RegionServerThread> rsThreads =
3944 getHBaseCluster().getLiveRegionServerThreads();
3945 for (JVMClusterUtil.RegionServerThread rsThread: rsThreads) {
3946 HRegionServer rs = rsThread.getRegionServer();
3947 if (server.equals(rs.getServerName())) {
3948 continue;
3949 }
3950 Collection<Region> hrs = rs.getOnlineRegionsLocalContext();
3951 for (Region r: hrs) {
3952 assertTrue("Region should not be double assigned",
3953 r.getRegionInfo().getRegionId() != hri.getRegionId());
3954 }
3955 }
3956 return;
3957 }
3958 long now = System.currentTimeMillis();
3959 if (now > timeoutTime) break;
3960 Thread.sleep(10);
3961 }
3962 fail("Could not find region " + hri.getRegionNameAsString()
3963 + " on server " + server);
3964 }
3965
3966 public HRegion createTestRegion(String tableName, HColumnDescriptor hcd)
3967 throws IOException {
3968 HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
3969 htd.addFamily(hcd);
3970 HRegionInfo info =
3971 new HRegionInfo(TableName.valueOf(tableName), null, null, false);
3972 HRegion region =
3973 HRegion.createHRegion(info, getDataTestDir(), getConfiguration(), htd);
3974 return region;
3975 }
3976
3977 public void setFileSystemURI(String fsURI) {
3978 FS_URI = fsURI;
3979 }
3980
3981
3982
3983
3984 public <E extends Exception> long waitFor(long timeout, Predicate<E> predicate)
3985 throws E {
3986 return Waiter.waitFor(this.conf, timeout, predicate);
3987 }
3988
3989
3990
3991
3992 public <E extends Exception> long waitFor(long timeout, long interval, Predicate<E> predicate)
3993 throws E {
3994 return Waiter.waitFor(this.conf, timeout, interval, predicate);
3995 }
3996
3997
3998
3999
4000 public <E extends Exception> long waitFor(long timeout, long interval,
4001 boolean failIfTimeout, Predicate<E> predicate) throws E {
4002 return Waiter.waitFor(this.conf, timeout, interval, failIfTimeout, predicate);
4003 }
4004
4005
4006
4007
4008 public ExplainingPredicate<IOException> predicateNoRegionsInTransition() {
4009 return new ExplainingPredicate<IOException>() {
4010 @Override
4011 public String explainFailure() throws IOException {
4012 final RegionStates regionStates = getMiniHBaseCluster().getMaster()
4013 .getAssignmentManager().getRegionStates();
4014 return "found in transition: " + regionStates.getRegionsInTransition().toString();
4015 }
4016
4017 @Override
4018 public boolean evaluate() throws IOException {
4019 HMaster master = getMiniHBaseCluster().getMaster();
4020 if (master == null) return false;
4021 AssignmentManager am = master.getAssignmentManager();
4022 if (am == null) return false;
4023 final RegionStates regionStates = am.getRegionStates();
4024 return !regionStates.isRegionsInTransition();
4025 }
4026 };
4027 }
4028
4029
4030
4031
4032 public Waiter.Predicate<IOException> predicateTableEnabled(final TableName tableName) {
4033 return new ExplainingPredicate<IOException>() {
4034 @Override
4035 public String explainFailure() throws IOException {
4036 return explainTableState(tableName);
4037 }
4038
4039 @Override
4040 public boolean evaluate() throws IOException {
4041 return getHBaseAdmin().tableExists(tableName) && getHBaseAdmin().isTableEnabled(tableName);
4042 }
4043 };
4044 }
4045
4046
4047
4048
4049 public Waiter.Predicate<IOException> predicateTableDisabled(final TableName tableName) {
4050 return new ExplainingPredicate<IOException>() {
4051 @Override
4052 public String explainFailure() throws IOException {
4053 return explainTableState(tableName);
4054 }
4055
4056 @Override
4057 public boolean evaluate() throws IOException {
4058 return getHBaseAdmin().isTableDisabled(tableName);
4059 }
4060 };
4061 }
4062
4063
4064
4065
4066 public Waiter.Predicate<IOException> predicateTableAvailable(final TableName tableName) {
4067 return new ExplainingPredicate<IOException>() {
4068 @Override
4069 public String explainFailure() throws IOException {
4070 return explainTableAvailability(tableName);
4071 }
4072
4073 @Override
4074 public boolean evaluate() throws IOException {
4075 boolean tableAvailable = getHBaseAdmin().isTableAvailable(tableName);
4076 if (tableAvailable) {
4077 try {
4078 Canary.sniff(getHBaseAdmin(), tableName);
4079 } catch (Exception e) {
4080 throw new IOException("Canary sniff failed for table " + tableName, e);
4081 }
4082 }
4083 return tableAvailable;
4084 }
4085 };
4086 }
4087
4088
4089
4090
4091
4092
4093 public void waitUntilNoRegionsInTransition(
4094 final long timeout) throws Exception {
4095 waitFor(timeout, predicateNoRegionsInTransition());
4096 }
4097
4098
4099
4100
4101
4102
4103 public void waitLabelAvailable(long timeoutMillis, final String... labels) {
4104 final VisibilityLabelsCache labelsCache = VisibilityLabelsCache.get();
4105 waitFor(timeoutMillis, new Waiter.ExplainingPredicate<RuntimeException>() {
4106
4107 @Override
4108 public boolean evaluate() {
4109 for (String label : labels) {
4110 if (labelsCache.getLabelOrdinal(label) == 0) {
4111 return false;
4112 }
4113 }
4114 return true;
4115 }
4116
4117 @Override
4118 public String explainFailure() {
4119 for (String label : labels) {
4120 if (labelsCache.getLabelOrdinal(label) == 0) {
4121 return label + " is not available yet";
4122 }
4123 }
4124 return "";
4125 }
4126 });
4127 }
4128
4129
4130
4131
4132
4133
4134 public static List<HColumnDescriptor> generateColumnDescriptors() {
4135 return generateColumnDescriptors("");
4136 }
4137
4138
4139
4140
4141
4142
4143
4144 public static List<HColumnDescriptor> generateColumnDescriptors(final String prefix) {
4145 List<HColumnDescriptor> htds = new ArrayList<HColumnDescriptor>();
4146 long familyId = 0;
4147 for (Compression.Algorithm compressionType: getSupportedCompressionAlgorithms()) {
4148 for (DataBlockEncoding encodingType: DataBlockEncoding.values()) {
4149 for (BloomType bloomType: BloomType.values()) {
4150 String name = String.format("%s-cf-!@#&-%d!@#", prefix, familyId);
4151 HColumnDescriptor htd = new HColumnDescriptor(name);
4152 htd.setCompressionType(compressionType);
4153 htd.setDataBlockEncoding(encodingType);
4154 htd.setBloomFilterType(bloomType);
4155 htds.add(htd);
4156 familyId++;
4157 }
4158 }
4159 }
4160 return htds;
4161 }
4162
4163
4164
4165
4166
4167 public static Compression.Algorithm[] getSupportedCompressionAlgorithms() {
4168 String[] allAlgos = HFile.getSupportedCompressionAlgorithms();
4169 List<Compression.Algorithm> supportedAlgos = new ArrayList<Compression.Algorithm>();
4170 for (String algoName : allAlgos) {
4171 try {
4172 Compression.Algorithm algo = Compression.getCompressionAlgorithmByName(algoName);
4173 algo.getCompressor();
4174 supportedAlgos.add(algo);
4175 } catch (Throwable t) {
4176
4177 }
4178 }
4179 return supportedAlgos.toArray(new Algorithm[supportedAlgos.size()]);
4180 }
4181
4182
4183
4184
4185
4186
4187
4188 public MiniKdc setupMiniKdc(File keytabFile) throws Exception {
4189 Properties conf = MiniKdc.createConf();
4190 conf.put(MiniKdc.DEBUG, true);
4191 MiniKdc kdc = null;
4192 File dir = null;
4193
4194
4195 boolean bindException;
4196 int numTries = 0;
4197 do {
4198 try {
4199 bindException = false;
4200 dir = new File(getDataTestDir("kdc").toUri().getPath());
4201 kdc = new MiniKdc(conf, dir);
4202 kdc.start();
4203 } catch (BindException e) {
4204 FileUtils.deleteDirectory(dir);
4205 numTries++;
4206 if (numTries == 3) {
4207 LOG.error("Failed setting up MiniKDC. Tried " + numTries + " times.");
4208 throw e;
4209 }
4210 LOG.error("BindException encountered when setting up MiniKdc. Trying again.");
4211 bindException = true;
4212 }
4213 } while (bindException);
4214 HBaseKerberosUtils.setKeytabFileForTesting(keytabFile.getAbsolutePath());
4215 return kdc;
4216 }
4217 }