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