Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial commit

  • Loading branch information...
commit d56063b6c65b6b4807ee64fa05651cee629c3490 0 parents
Alex Baranau authored
202 LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
109 README
@@ -0,0 +1,109 @@
+HBaseWD:
+---------
+http://github.com/sematext/HBaseWD
+
+April 2011
+
+Released under Apache License 2.0.
+
+Author:
+-------
+Alex Baranau
+
+Description:
+------------
+HBaseWD stands for Distributing (sequential) Writes. It was inspired by
+discussions on HBase mailing lists around the problem of choosing between:
+* writing records with sequential row keys (e.g. time-series data with row key
+ built based on ts)
+* using random unique IDs for records
+
+First approach makes possible to perform fast range scans with help of setting
+start/stop keys on Scanner, but creates single region server hot-spotting
+problem upon writing data (as row keys go in sequence all records end up
+written into a single region at a time).
+
+Second approach aims for fastest writing performance by distributing new
+records over random regions but makes not possible doing fast range scans
+against written data.
+
+The suggested approach stays in the middle of the two above and proved to
+perform well by distributing records over the cluster during writing data
+while allowing range scans over it. HBaseWD provides very simple API to
+work with which makes it perfect to use with existing code.
+
+Please refer to unit-tests for lib usage info as they aimed to act as example.
+
+Brief Usage Info (Examples):
+----------------------------
+
+Distributing records with sequential keys which are being written in up to
+Byte.MAX_VALUE buckets:
+
+ byte bucketsCount = (byte) 32; // distributing into 32 buckets
+ RowKeyDistributor keyDistributor =
+ new RowKeyDistributorByOneBytePrefix(bucketsCount);
+ for (int i = 0; i < 100; i++) {
+ Put put = new Put(keyDistributor.getDistributedKey(originalKey));
+ ... // add values
+ hTable.put(put);
+ }
+
+
+Performing a range scan over written data (internally <bucketsCount> scanners
+executed):
+
+ Scan scan = new Scan(startKey, stopKey);
+ ResultScanner rs = DistributedScanner.create(hTable, scan, keyDistributor);
+ for (Result current : rs) {
+ ...
+ }
+
+Performing mapreduce job over written data chunk specified by Scan:
+
+ Configuration conf = HBaseConfiguration.create();
+ Job job = new Job(conf, "testMapreduceJob");
+
+ Scan scan = new Scan(startKey, stopKey);
+
+ TableMapReduceUtil.initTableMapperJob("table", scan,
+ RowCounterMapper.class, ImmutableBytesWritable.class, Result.class, job);
+
+ // Substituting standard TableInputFormat which was set in
+ // TableMapReduceUtil.initTableMapperJob(...)
+ job.setInputFormatClass(WdTableInputFormat.class);
+ keyDistributor.addInfo(job.getConfiguration());
+
+
+Extending Row Keys Distributing Patterns:
+-----------------------------------------
+
+HBaseWD is designed to be flexible and to support custom row key distribution
+approaches. To define custom row key distributing logic just implement
+AbstractRowKeyDistributor abstract class which is really very simple:
+
+ public abstract class AbstractRowKeyDistributor implements Parametrizable {
+ public abstract byte[] getDistributedKey(byte[] originalKey);
+ public abstract byte[] getOriginalKey(byte[] adjustedKey);
+ public abstract byte[][] getAllDistributedKeys(byte[] originalKey);
+ ... // some utility methods
+ }
+
+
+Mailing List:
+-------------
+To participate more in the discussion, join the group at
+https://groups.google.com/group/hbasewd/
+
+Build Notes:
+------------
+Current pom configured to build against HBase 0.89.20100924.
+HBase jars are provided with sources, as only HBase trunk sources
+were mavenized and available in public repos.
+Tests take some time to execute (can be up to several minutes), to skip
+their execution use -Dmaven.skip.tests=true.
+
+HBase Version Compatibility:
+----------------------------
+Compatible with HBase 0.20.5 and higher.
+May be compatible with previous: tests needed (TODO)
BIN  hbasewd-0.1.0-SNAPSHOT-2011.04.19.jar
Binary file not shown
BIN  lib/hbase-0.89.20100924-tests.jar
Binary file not shown
BIN  lib/hbase-0.89.20100924.jar
Binary file not shown
176 pom.xml
@@ -0,0 +1,176 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>com.sematext</groupId>
+ <artifactId>hbasewd</artifactId>
+ <version>0.1.0-SNAPSHOT</version>
+
+ <packaging>jar</packaging>
+ <name>HBaseWD</name>
+ <description>TODO</description>
+
+ <properties>
+ <maven.compile.source>1.6</maven.compile.source>
+ <maven.compile.target>1.6</maven.compile.target>
+ <commons-logging.version>1.1.1</commons-logging.version>
+ <log4j.version>1.2.15</log4j.version>
+ <hadoop.version>0.20.3-append-r964955-1240</hadoop.version>
+ <junit.version>4.5</junit.version>
+ <easymock.version>2.4</easymock.version>
+ <zookeeper.version>3.3.1</zookeeper.version>
+ <hbase.version>0.89.20100924</hbase.version>
+ <hbase.basedir>${basedir}/lib</hbase.basedir>
+ <slf4j.version>1.5.8</slf4j.version>
+ <guava.version>r05</guava.version>
+ </properties>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>${maven.compile.source}</source>
+ <target>${maven.compile.target}</target>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <repositories>
+ <repository>
+ <id>jboss.com</id>
+ <name>JBoss.com Repository</name>
+ <url>http://repository.jboss.com/maven2</url>
+ </repository>
+ <repository>
+ <id>java.net</id>
+ <name>java.net Repository</name>
+ <url>http://download.java.net/maven/2</url>
+ </repository>
+ <repository>
+ <id>ibiblio</id>
+ <name>ibiblio</name>
+ <url>http://people.apache.org/repo/m2-ibiblio-rsync-repository</url>
+ </repository>
+ <repository>
+ <id>apache-releases</id>
+ <name>Apache Releases repository</name>
+ <url>https://repository.apache.org/content/repositories/releases</url>
+ </repository>
+ <repository>
+ <id>apache-snapshot</id>
+ <name>Apache Snapshot repository</name>
+ <url>https://repository.apache.org/content/repositories/snapshots</url>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ <repository>
+ <id>ryan-repo</id>
+ <name>Ryan's repository for hadoop dependencies</name>
+ <url>http://people.apache.org/~rawson/repo</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ <releases>
+ <enabled>true</enabled>
+ </releases>
+ </repository>
+ </repositories>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase-core</artifactId>
+ <version>${hbase.version}</version>
+ <scope>system</scope>
+ <systemPath>${hbase.basedir}/hbase-${hbase.version}.jar</systemPath>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase-core-test</artifactId>
+ <version>${hbase.version}</version>
+ <scope>system</scope>
+ <systemPath>${hbase.basedir}/hbase-${hbase.version}-tests.jar</systemPath>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.zookeeper</groupId>
+ <artifactId>zookeeper</artifactId>
+ <version>${zookeeper.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-core</artifactId>
+ <version>${hadoop.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.15</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.sun.jdmk</groupId>
+ <artifactId>jmxtools</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.sun.jmx</groupId>
+ <artifactId>jmxri</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <!-- Tests dependencies -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>${junit.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.easymock</groupId>
+ <artifactId>easymock</artifactId>
+ <version>${easymock.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-test</artifactId>
+ <version>${hadoop.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>${slf4j.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-jdk14</artifactId>
+ <version>${slf4j.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <version>${slf4j.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>${guava.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+</project>
36 src/main/java/com/sematext/hbase/wd/AbstractRowKeyDistributor.java
@@ -0,0 +1,36 @@
+/**
+ * Copyright 2010 Sematext International
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sematext.hbase.wd;
+
+import org.apache.hadoop.conf.Configuration;
+
+/**
+ * Defines the way row keys are distributed
+ *
+ * @author Alex Baranau
+ */
+public abstract class AbstractRowKeyDistributor implements Parametrizable {
+ public abstract byte[] getDistributedKey(byte[] originalKey);
+
+ public abstract byte[] getOriginalKey(byte[] adjustedKey);
+
+ public abstract byte[][] getAllDistributedKeys(byte[] originalKey);
+
+ public void addInfo(Configuration conf) {
+ conf.set(WdTableInputFormat.ROW_KEY_DISTRIBUTOR_CLASS, this.getClass().getCanonicalName());
+ conf.set(WdTableInputFormat.ROW_KEY_DISTRIBUTOR_PARAMS, getParamsToStore());
+ }
+}
187 src/main/java/com/sematext/hbase/wd/DistributedScanner.java
@@ -0,0 +1,187 @@
+/**
+ * Copyright 2010 Sematext International
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sematext.hbase.wd;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
+
+/**
+ * Interface for client-side scanning the data written with keys distribution
+ *
+ * @author Alex Baranau
+ */
+public class DistributedScanner implements ResultScanner {
+ private final ResultScanner[] scanners;
+ private final List<Result>[] nextOfScanners;
+ private Result next = null;
+
+ @SuppressWarnings("unchecked")
+ public DistributedScanner(ResultScanner[] scanners) throws IOException {
+ this.scanners = scanners;
+ this.nextOfScanners = new List[scanners.length];
+ Arrays.fill(this.nextOfScanners, new ArrayList<Result>());
+ }
+
+ private boolean hasNext(int nbRows) throws IOException {
+ if (next != null) {
+ return true;
+ }
+
+ next = nextInternal(nbRows);
+
+ return next != null;
+ }
+
+ @Override
+ public Result next() throws IOException {
+ if (hasNext(1)) {
+ Result toReturn = next;
+ next = null;
+ return toReturn;
+ }
+
+ return null;
+ }
+
+ @Override
+ public Result[] next(int nbRows) throws IOException {
+ // Identical to HTable.ClientScanner implementation
+ // Collect values to be returned here
+ ArrayList<Result> resultSets = new ArrayList<Result>(nbRows);
+ for(int i = 0; i < nbRows; i++) {
+ Result next = next();
+ if (next != null) {
+ resultSets.add(next);
+ } else {
+ break;
+ }
+ }
+ return resultSets.toArray(new Result[resultSets.size()]);
+ }
+
+ @Override
+ public void close() {
+ for (int i = 0; i < scanners.length; i++) {
+ scanners[i].close();
+ }
+ }
+
+ public static DistributedScanner create(HTable hTable, Scan original, AbstractRowKeyDistributor keyDistributor) throws IOException {
+ byte[][] startKeys = keyDistributor.getAllDistributedKeys(original.getStartRow());
+ byte[][] stopKeys = keyDistributor.getAllDistributedKeys(original.getStopRow());
+ Scan[] scans = new Scan[startKeys.length];
+ for (byte i = 0; i < startKeys.length; i++) {
+ scans[i] = new Scan(original);
+ scans[i].setStartRow(startKeys[i]);
+ scans[i].setStopRow(stopKeys[i]);
+ }
+
+ ResultScanner[] rss = new ResultScanner[startKeys.length];
+ for (byte i = 0; i < scans.length; i++) {
+ rss[i] = hTable.getScanner(scans[i]);
+ }
+
+ return new DistributedScanner(rss);
+ }
+
+ private Result nextInternal(int nbRows) throws IOException {
+ Result result = null;
+ byte indexOfScannerToUse = -1;
+ for (byte i = 0; i < nextOfScanners.length; i++) {
+ if (nextOfScanners[i] == null) {
+ // result scanner is exhausted, don't advance it any more
+ continue;
+ }
+
+ if (nextOfScanners[i].size() == 0) {
+ // advancing result scanner
+ Result[] results = scanners[i].next(nbRows);
+ if (results.length == 0) {
+ // marking result scanner as exhausted
+ nextOfScanners[i] = null;
+ continue;
+ }
+ nextOfScanners[i].addAll(Arrays.asList(results));
+ }
+
+ if (result == null || Bytes.compareTo(nextOfScanners[i].get(0).getRow(), result.getRow()) < 0) {
+ result = nextOfScanners[i].get(0);
+ indexOfScannerToUse = i;
+ }
+ }
+
+ if (indexOfScannerToUse >= 0) {
+ nextOfScanners[indexOfScannerToUse].remove(0);
+ }
+
+ return result;
+ }
+
+ @Override
+ public Iterator<Result> iterator() {
+ // Identical to HTable.ClientScanner implementation
+ return new Iterator<Result>() {
+ // The next RowResult, possibly pre-read
+ Result next = null;
+
+ // return true if there is another item pending, false if there isn't.
+ // this method is where the actual advancing takes place, but you need
+ // to call next() to consume it. hasNext() will only advance if there
+ // isn't a pending next().
+ public boolean hasNext() {
+ if (next == null) {
+ try {
+ next = DistributedScanner.this.next();
+ return next != null;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return true;
+ }
+
+ // get the pending next item and advance the iterator. returns null if
+ // there is no next item.
+ public Result next() {
+ // since hasNext() does the real advancing, we call this to determine
+ // if there is a next before proceeding.
+ if (!hasNext()) {
+ return null;
+ }
+
+ // if we get to here, then hasNext() has given us an item to return.
+ // we want to return the item and then null out the next pointer, so
+ // we use a temporary variable.
+ Result temp = next;
+ next = null;
+ return temp;
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+}
27 src/main/java/com/sematext/hbase/wd/Parametrizable.java
@@ -0,0 +1,27 @@
+/**
+ * Copyright 2010 Sematext International
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sematext.hbase.wd;
+
+/**
+ * Defines interface for storing object parameters in a String object to later restore the object by applying them to
+ * new object instance
+ *
+ * @author Alex Baranau
+ */
+public interface Parametrizable {
+ String getParamsToStore();
+ void init(String storedParams);
+}
83 src/main/java/com/sematext/hbase/wd/RowKeyDistributorByOneBytePrefix.java
@@ -0,0 +1,83 @@
+/**
+ * Copyright 2010 Sematext International
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sematext.hbase.wd;
+
+import org.apache.hadoop.hbase.util.Bytes;
+
+/**
+ * Provides handy methods to distribute
+ *
+ * @author Alex Baranau
+ */
+public class RowKeyDistributorByOneBytePrefix extends AbstractRowKeyDistributor {
+ private static final byte[][] PREFIXES;
+
+ static {
+ PREFIXES = new byte[Byte.MAX_VALUE][];
+ for (byte i = 0; i < Byte.MAX_VALUE; i++) {
+ PREFIXES[i] = new byte[] {i};
+ }
+ }
+
+ private byte maxPrefix;
+ private byte nextPrefix;
+
+ /** Constructor reflection. DO NOT USE */
+ public RowKeyDistributorByOneBytePrefix() {
+ }
+
+ public RowKeyDistributorByOneBytePrefix(byte bucketsCount) {
+ this.maxPrefix = bucketsCount;
+ this.nextPrefix = 0;
+ }
+
+ @Override
+ public byte[] getDistributedKey(byte[] originalKey) {
+ byte[] key = Bytes.add(PREFIXES[nextPrefix++], originalKey);
+ nextPrefix = (byte) (nextPrefix % maxPrefix);
+
+ return key;
+ }
+
+ @Override
+ public byte[] getOriginalKey(byte[] adjustedKey) {
+ return Bytes.tail(adjustedKey, adjustedKey.length - 1);
+ }
+
+ @Override
+ public byte[][] getAllDistributedKeys(byte[] originalKey) {
+ return getAllDistributedKeys(originalKey, maxPrefix);
+ }
+
+ private static byte[][] getAllDistributedKeys(byte[] originalKey, byte maxPrefix) {
+ byte[][] keys = new byte[maxPrefix][];
+ for (byte i = 0; i < maxPrefix; i++) {
+ keys[i] = Bytes.add(PREFIXES[i], originalKey);
+ }
+
+ return keys;
+ }
+
+ @Override
+ public String getParamsToStore() {
+ return String.valueOf(maxPrefix);
+ }
+
+ @Override
+ public void init(String params) {
+ maxPrefix = Byte.parseByte(params);
+ }
+}
82 src/main/java/com/sematext/hbase/wd/WdTableInputFormat.java
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2010 Sematext International
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sematext.hbase.wd;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapreduce.JobContext;
+
+/**
+ * Convert HBase tabular data into a format that is consumable by Map/Reduce with respect to
+ * row key distribution strategy
+ *
+ * @author Alex Baranau
+ */
+public class WdTableInputFormat extends TableInputFormat {
+
+ public static final String ROW_KEY_DISTRIBUTOR_CLASS = "hbase.mapreduce.scan.wd.distributor.class";
+ public static final String ROW_KEY_DISTRIBUTOR_PARAMS = "hbase.mapreduce.scan.wd.distributor.params";
+
+ private AbstractRowKeyDistributor rowKeyDistributor;
+
+ @Override
+ public void setConf(Configuration conf) {
+ super.setConf(conf);
+
+ if (conf.get(ROW_KEY_DISTRIBUTOR_CLASS) != null) {
+ String clazz = conf.get(ROW_KEY_DISTRIBUTOR_CLASS);
+ try {
+ rowKeyDistributor = (AbstractRowKeyDistributor) Class.forName(clazz).newInstance();
+ if (conf.get(ROW_KEY_DISTRIBUTOR_PARAMS) != null) {
+ rowKeyDistributor.init(conf.get(ROW_KEY_DISTRIBUTOR_PARAMS));
+ }
+ } catch (Exception e) {
+ throw new RuntimeException("Cannot create row key distributor, " + ROW_KEY_DISTRIBUTOR_CLASS + ": " + clazz);
+ }
+ }
+ }
+
+ @Override
+ public List<InputSplit> getSplits(JobContext context) throws IOException {
+ List<InputSplit> allSplits = new ArrayList<InputSplit>();
+ Scan originalScan = getScan();
+
+ byte[][] startRows = rowKeyDistributor.getAllDistributedKeys(originalScan.getStartRow());
+ byte[][] stopRows = rowKeyDistributor.getAllDistributedKeys(originalScan.getStopRow());
+
+ for (byte i = 0; i < startRows.length; i++) {
+ // Internally super.getSplits(...) uses scan object stored in private variable,
+ // to re-use the code of super class we switch scan object with scans we
+ Scan scan = new Scan(originalScan);
+ scan.setStartRow(startRows[i]);
+ scan.setStopRow(stopRows[i]);
+ setScan(scan);
+ List<InputSplit> splits = super.getSplits(context);
+ allSplits.addAll(splits);
+ }
+
+ // Setting original scan back
+ setScan(originalScan);
+
+ return allSplits;
+ }
+}
81 src/test/java/com/sematext/hbase/wd/DebugUtil.java
@@ -0,0 +1,81 @@
+/**
+ * Copyright 2010 Sematext International
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sematext.hbase.wd;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.NavigableMap;
+
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
+
+/**
+ * @author Alex Baranau
+ */
+public final class DebugUtil {
+ private static final String C_DEL = "\t\t";
+ private static final String CF_DEL = ":";
+ private static final String VAL_DEL = "=";
+
+ public DebugUtil() {}
+
+ public static String getContent(HTable t) throws IOException {
+ ResultScanner rs = t.getScanner(new Scan());
+ Result next = rs.next();
+ int readCount = 0;
+ StringBuilder contentText = new StringBuilder();
+ while (next != null && readCount < 1000) {
+ contentText.append(getRowKeyAsText(next.getRow()));
+ for (Map.Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> cf : next.getMap().entrySet()) {
+ for (Map.Entry<byte[], NavigableMap<Long, byte[]>> c : cf.getValue().entrySet()) {
+ byte[] value = c.getValue().values().iterator().next();
+ contentText.append(C_DEL);
+ contentText.append(Bytes.toString(cf.getKey())).append(CF_DEL)
+ .append(Bytes.toString(c.getKey())).append(VAL_DEL)
+ .append(getText(value));
+ }
+ }
+ contentText.append("\n");
+ next = rs.next();
+ readCount++;
+ }
+
+ return contentText.toString();
+ }
+
+ private static String getRowKeyAsText(byte[] row) {
+ return Bytes.toString(new RowKeyDistributorByOneBytePrefix((byte) 0).getOriginalKey(row)) + "-" +
+ Bytes.toLong(Bytes.head(Bytes.tail(row, 2 * Bytes.SIZEOF_LONG), Bytes.SIZEOF_LONG)) + "-" +
+ Bytes.toLong(Bytes.tail(row, Bytes.SIZEOF_LONG));
+ }
+
+ private static String getText(byte[] data) {
+ try {
+ if (data.length == Bytes.SIZEOF_INT) {
+ return String.valueOf(Bytes.toInt(data));
+ } else if (data.length == Bytes.SIZEOF_LONG) {
+ return String.valueOf(Bytes.toLong(data));
+ } else {
+ return Bytes.toString(data);
+ }
+ } catch (IllegalArgumentException ex) {
+ return Bytes.toString(data);
+ }
+ }
+}
168 src/test/java/com/sematext/hbase/wd/TestHBaseWd.java
@@ -0,0 +1,168 @@
+/**
+ * Copyright 2010 Sematext International
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.sematext.hbase.wd;
+
+import java.io.IOException;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HBaseTestingUtility;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.hbase.mapreduce.TableMapper;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * General unit-test for the whole concept
+ *
+ * @author Alex Baranau
+ */
+public class TestHBaseWd {
+ private HBaseTestingUtility testingUtility;
+ public static final byte[] CF = Bytes.toBytes("colfam");
+ public static final byte[] QUAL = Bytes.toBytes("qual");
+
+ @Before
+ public void before() throws Exception {
+ testingUtility = new HBaseTestingUtility();
+ testingUtility.startMiniCluster(1);
+ }
+
+ @After
+ public void after() throws IOException {
+ testingUtility.shutdownMiniCluster();
+ testingUtility = null;
+ }
+
+ @Test
+ public void testSimpleScan() throws IOException, InterruptedException {
+ byte bucketsCount = (byte) 12;
+
+ HTable hTable = testingUtility.createTable(Bytes.toBytes("table"), CF);
+ long millis = System.currentTimeMillis();
+ int valuesCountInSeekInterval = 0;
+
+ AbstractRowKeyDistributor keyDistributor = new RowKeyDistributorByOneBytePrefix(bucketsCount);
+ for (int i = 0; i < 500; i++) {
+ int val = 500 + i - i * (i % 2) * 2; // i.e. 500, 499, 502, 497, 504, ...
+ valuesCountInSeekInterval += (val >= 100 && val < 900) ? 1 : 0;
+ byte[] key = Bytes.toBytes(millis + val);
+ Put put = new Put(keyDistributor.getDistributedKey(key));
+ put.add(CF, QUAL, Bytes.toBytes(val));
+ hTable.put(put);
+ }
+
+ byte[] startKey = Bytes.toBytes(millis + 100);
+ byte[] stopKey = Bytes.toBytes(millis + 900);
+
+ // TODO: add some filters for better testing
+ Scan scan = new Scan(startKey, stopKey);
+ ResultScanner distributedScanner = DistributedScanner.create(hTable, scan, keyDistributor);
+
+ Result previous = null;
+ int countMatched = 0;
+ for (Result current : distributedScanner) {
+ countMatched++;
+ if (previous != null) {
+ Assert.assertTrue(Bytes.compareTo(current.getRow(), previous.getRow()) >= 0);
+ Assert.assertTrue(Bytes.toInt(current.getValue(CF, QUAL)) >= 100);
+ Assert.assertTrue(Bytes.toInt(current.getValue(CF, QUAL)) < 900);
+ }
+ previous = current;
+ }
+
+ Assert.assertEquals(valuesCountInSeekInterval, countMatched);
+ }
+
+ @Test
+ public void testMapreduceJob() throws IOException, ClassNotFoundException, InterruptedException {
+ byte spread = (byte) 12;
+
+ // Writing data
+ AbstractRowKeyDistributor keyDistributor = new RowKeyDistributorByOneBytePrefix(spread);
+ HTable hTable = testingUtility.createTable(Bytes.toBytes("table"), CF);
+ long millis = System.currentTimeMillis();
+ int valuesCountInSeekInterval = 0;
+ for (int i = 0; i < 500; i++) {
+ int val = 500 + i - i * (i % 2) * 2; // i.e. 500, 499, 502, 497, 504, ...
+ valuesCountInSeekInterval += (val >= 100 && val < 900) ? 1 : 0;
+ byte[] key = Bytes.toBytes(millis + val);
+ Put put = new Put(keyDistributor.getDistributedKey(key));
+ put.add(CF, QUAL, Bytes.toBytes(val));
+ hTable.put(put);
+ }
+
+ // Reading data
+ byte[] startKey = Bytes.toBytes(millis + 100);
+ byte[] stopKey = Bytes.toBytes(millis + 900);
+ Scan scan = new Scan(startKey, stopKey);
+
+ Configuration conf = HBaseConfiguration.create();
+
+ Job job = new Job(conf, "testMapreduceJob");
+ TableMapReduceUtil.initTableMapperJob("table", scan,
+ RowCounterMapper.class, ImmutableBytesWritable.class, Result.class, job);
+
+ // Substituting standard TableInputFormat which was set in TableMapReduceUtil.initTableMapperJob(...)
+ job.setInputFormatClass(WdTableInputFormat.class);
+ keyDistributor.addInfo(job.getConfiguration());
+
+ job.setJarByClass(TestHBaseWd.class);
+
+ job.setNumReduceTasks(0);
+ job.setOutputFormatClass(NullOutputFormat.class);
+
+ boolean succeeded = job.waitForCompletion(true);
+ Assert.assertTrue(succeeded);
+
+ long mapInputRecords = job.getCounters().findCounter(RowCounterMapper.Counters.ROWS).getValue();
+ Assert.assertEquals(valuesCountInSeekInterval, mapInputRecords);
+ }
+
+ /**
+ * Mapper that runs the count.
+ * NOTE: it was copied from RowCounter class
+ */
+ static class RowCounterMapper
+ extends TableMapper<ImmutableBytesWritable, Result> {
+ /** Counter enumeration to count the actual rows. */
+ public static enum Counters {ROWS}
+
+ @Override
+ public void map(ImmutableBytesWritable row, Result values,
+ Context context)
+ throws IOException {
+ for (KeyValue value: values.list()) {
+ if (value.getValue().length > 0) {
+ context.getCounter(Counters.ROWS).increment(1);
+ break;
+ }
+ }
+ }
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.