Browse files

Omid project

  • Loading branch information...
0 parents commit 2e435f54c714e3b610110f24a73de857ba0f30e0 @dgomezferro committed Nov 2, 2011
Showing with 10,326 additions and 0 deletions.
  1. +202 −0 LICENSE.txt
  2. +9 −0 NOTICE.txt
  3. +78 −0 README
  4. +96 −0 README.md
  5. +97 −0 bin/omid.sh
  6. +25 −0 conf/hbase-site.xml
  7. +132 −0 pom.xml
  8. +21 −0 src/main/java/com/yahoo/omid/client/AbortCompleteCallback.java
  9. +21 −0 src/main/java/com/yahoo/omid/client/Callback.java
  10. +24 −0 src/main/java/com/yahoo/omid/client/CommitCallback.java
  11. +21 −0 src/main/java/com/yahoo/omid/client/CommitQueryCallback.java
  12. +21 −0 src/main/java/com/yahoo/omid/client/CommitUnsuccessfulException.java
  13. +22 −0 src/main/java/com/yahoo/omid/client/CreateCallback.java
  14. +18 −0 src/main/java/com/yahoo/omid/client/CreateCallbackImpl.java
  15. +57 −0 src/main/java/com/yahoo/omid/client/RowKeyFamily.java
  16. +26 −0 src/main/java/com/yahoo/omid/client/SyncAbortCompleteCallback.java
  17. +43 −0 src/main/java/com/yahoo/omid/client/SyncCallbackBase.java
  18. +40 −0 src/main/java/com/yahoo/omid/client/SyncCommitCallback.java
  19. +32 −0 src/main/java/com/yahoo/omid/client/SyncCommitQueryCallback.java
  20. +34 −0 src/main/java/com/yahoo/omid/client/SyncCreateCallback.java
  21. +569 −0 src/main/java/com/yahoo/omid/client/TSOClient.java
  22. +30 −0 src/main/java/com/yahoo/omid/client/TransactionException.java
  23. +149 −0 src/main/java/com/yahoo/omid/client/TransactionManager.java
  24. +65 −0 src/main/java/com/yahoo/omid/client/TransactionState.java
  25. +469 −0 src/main/java/com/yahoo/omid/client/TransactionalTable.java
  26. +120 −0 src/main/java/com/yahoo/omid/tso/BandwidthMeterHandler.java
  27. +88 −0 src/main/java/com/yahoo/omid/tso/Bucket.java
  28. +41 −0 src/main/java/com/yahoo/omid/tso/BufferPool.java
  29. +420 −0 src/main/java/com/yahoo/omid/tso/ClientHandler.java
  30. +243 −0 src/main/java/com/yahoo/omid/tso/CommitHashMap.java
  31. +91 −0 src/main/java/com/yahoo/omid/tso/Committed.java
  32. +67 −0 src/main/java/com/yahoo/omid/tso/RowId.java
  33. +112 −0 src/main/java/com/yahoo/omid/tso/RowKey.java
  34. +61 −0 src/main/java/com/yahoo/omid/tso/TSOBuffer.java
  35. +456 −0 src/main/java/com/yahoo/omid/tso/TSOHandler.java
  36. +69 −0 src/main/java/com/yahoo/omid/tso/TSOMessage.java
  37. +180 −0 src/main/java/com/yahoo/omid/tso/TSOMessageBuffer.java
  38. +89 −0 src/main/java/com/yahoo/omid/tso/TSOPipelineFactory.java
  39. +212 −0 src/main/java/com/yahoo/omid/tso/TSOServer.java
  40. +453 −0 src/main/java/com/yahoo/omid/tso/TSOSharedMessageBuffer.java
  41. +114 −0 src/main/java/com/yahoo/omid/tso/TSOState.java
  42. +227 −0 src/main/java/com/yahoo/omid/tso/ThroughputMonitor.java
  43. +91 −0 src/main/java/com/yahoo/omid/tso/Timestamp.java
  44. +159 −0 src/main/java/com/yahoo/omid/tso/TimestampOracle.java
  45. +139 −0 src/main/java/com/yahoo/omid/tso/TransactionClient.java
  46. +94 −0 src/main/java/com/yahoo/omid/tso/Uncommited.java
  47. +69 −0 src/main/java/com/yahoo/omid/tso/messages/AbortedTransactionReport.java
  48. +66 −0 src/main/java/com/yahoo/omid/tso/messages/CommitQueryRequest.java
  49. +84 −0 src/main/java/com/yahoo/omid/tso/messages/CommitQueryResponse.java
  50. +103 −0 src/main/java/com/yahoo/omid/tso/messages/CommitRequest.java
  51. +94 −0 src/main/java/com/yahoo/omid/tso/messages/CommitResponse.java
  52. +138 −0 src/main/java/com/yahoo/omid/tso/messages/CommittedTransactionReport.java
  53. +77 −0 src/main/java/com/yahoo/omid/tso/messages/FullAbortReport.java
  54. +69 −0 src/main/java/com/yahoo/omid/tso/messages/LargestDeletedTimestampReport.java
  55. +47 −0 src/main/java/com/yahoo/omid/tso/messages/TimestampRequest.java
  56. +75 −0 src/main/java/com/yahoo/omid/tso/messages/TimestampResponse.java
  57. +234 −0 src/main/java/com/yahoo/omid/tso/serialization/TSODecoder.java
  58. +80 −0 src/main/java/com/yahoo/omid/tso/serialization/TSOEncoder.java
  59. +55 −0 src/main/native/Makefile
  60. +339 −0 src/main/native/nativelib.cc
  61. +75 −0 src/main/resources/log4j.properties
  62. +213 −0 src/test/java/com/yahoo/omid/OmidTestBase.java
  63. +414 −0 src/test/java/com/yahoo/omid/TestBasicTransaction.java
  64. +128 −0 src/test/java/com/yahoo/omid/TestMultiplePut.java
  65. +107 −0 src/test/java/com/yahoo/omid/TestNonexistentRow.java
  66. +142 −0 src/test/java/com/yahoo/omid/TestSingleColumnFamily.java
  67. +50 −0 src/test/java/com/yahoo/omid/TestTable.java
  68. +249 −0 src/test/java/com/yahoo/omid/TestTransactionConflict.java
  69. +245 −0 src/test/java/com/yahoo/omid/TestUpdateScan.java
  70. +257 −0 src/test/java/com/yahoo/omid/tso/TSOTestBase.java
  71. +100 −0 src/test/java/com/yahoo/omid/tso/TestBasicTransaction.java
  72. +281 −0 src/test/java/com/yahoo/omid/tso/TestClientHandler.java
  73. +44 −0 src/test/java/com/yahoo/omid/tso/TestCommit.java
  74. +108 −0 src/test/java/com/yahoo/omid/tso/TestCommitAbortedReport.java
  75. +113 −0 src/test/java/com/yahoo/omid/tso/TestCommitQuery.java
  76. +78 −0 src/test/java/com/yahoo/omid/tso/TestCommitReport.java
  77. +54 −0 src/test/java/com/yahoo/omid/tso/TestConflict.java
  78. +72 −0 src/test/java/com/yahoo/omid/tso/TestMultipleCommitsWithoutConflict.java
  79. +70 −0 src/test/java/com/yahoo/omid/tso/TestReadAlgorithm.java
  80. +40 −0 src/test/java/com/yahoo/omid/tso/TestTimestamps.java
  81. +72 −0 src/test/java/com/yahoo/omid/tso/TestTimestampsOrdering.java
  82. +57 −0 src/test/resources/log4j.properties
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.
9 NOTICE.txt
@@ -0,0 +1,9 @@
+=======================================================================
+NOTICE file for use with, and corresponding to Section 4 of,
+the Apache License, Version 2.0,
+in this case for the CrTSO project. ==
+=========================================================================
+
+ This product includes software developed by
+ Yahoo! Inc. (www.yahoo.com)
+ Copyright (c) 2010 Yahoo! Inc. All rights reserved.
78 README
@@ -0,0 +1,78 @@
+* Dependencies
+ - Netty
+ - log4j
+ - ZooKeeper
+ - HBase
+
+* Compilation
+
+Omid uses Maven for its build system. The versions
+of zookeeper and bookkeeper are missing from mvn, so you have to
+manually install these dependencies.
+
+To install zookeeper:
+ $ mvn install:install-file -DgroupId=org.apache.zookeeper -DartifactId=zookeeper -Dversion=3.4.0 -Dpackaging=jar -Dfile=zookeeper-3.4.0.jar
+
+To install bookkeeper:
+ $ mvn install:install-file -DgroupId=org.apache.zookeeper -DartifactId=bookkeeper -Dversion=3.4.0 -Dpackaging=jar -Dfile=bookkeeper-3.4.0.jar
+
+Then to compile omid:
+ $ tar jxvf omid-1.0-SNAPSHOT.tar.bz2
+ $ cd omid-1.0-SNAPSHOT
+ $ mvn install
+
+Tests should run cleanly.
+
+* Running
+
+You need to run four components before running the transactional
+client. They are bookkeeper, zookeeper, omid tso and
+hbase. Bookkeeper is needed by the TSO. Zookeeper is needed by
+bookkeeper and hbase. The TSO is needed by hbase. Hence, the order of
+starting should be:
+ 1. Zookeeper
+ 2. Bookkeeper
+ 3. TSO
+ 4. Hbase
+
+** Zookeeper & Bookkeeper
+For simplicity we've included a utility script which starts zookeeper
+and bookkeeper. Run:
+
+ $ bin/omid.sh bktest
+
+Omid doesn't use anything special in zookeeper or bookkeeper, so you
+can use any install for these. However, if you are running this
+anywhere but localhost, you need to update the setting for hbase and
+TSO. See the hbase docs for changing the zookeeper quorum. For TSO,
+you need to modify bin/omid.sh.
+
+** TSO
+To start the TSO, run:
+
+ $ bin/omid.sh tso
+
+** Benchmark
+To benchmark the TSO alone, run:
+
+ $ bin/omid.sh tsobench
+
+** HBase
+We've included a utility script to start a HBase cluster on your local
+machine. Run:
+
+ $ bin/omid.sh tran-hbase
+
+For running in a cluster
+
+* API
+The public api is in
+ src/main/java/com/yahoo/omid/client/TransactionalTable.java
+ src/main/java/com/yahoo/omid/client/TransactionState.java
+ src/main/java/com/yahoo/omid/client/TransactionManager.java
+
+For an example of usage, look in
+ src/test/java/com/yahoo/omid/TestBasicTransaction.java
+
+* Logging
+Logging can be adjusted in src/main/resource/log4j.properties.
96 README.md
@@ -0,0 +1,96 @@
+Omid
+=====
+
+This project provides transactional support for HBase (or any other key-value store) using Snapshot Isolation.
+
+Architecture
+------------
+
+Omid is composed by a server (the Status Oracle) and several clients. The server contains all the information
+needed to manage transactions and replicates it to the clients which just contact the server when they want
+to start a transaction or commit it.
+
+The server uses BookKeeper as a Writer Ahead Log where it dumps all its state. In case of crash it is possible
+to restart the server without losing any commit information.
+
+Compilation
+-----------
+
+Omid uses Maven for its build system. The versions of zookeeper and bookkeeper are missing from mvn, so you have to
+manually install these dependencies.
+
+To install zookeeper:
+
+ $ mvn install:install-file -DgroupId=org.apache.zookeeper -DartifactId=zookeeper -Dversion=3.4.0 -Dpackaging=jar -Dfile=zookeeper-3.4.0.jar
+
+To install bookkeeper:
+
+ $ mvn install:install-file -DgroupId=org.apache.zookeeper -DartifactId=bookkeeper -Dversion=3.4.0 -Dpackaging=jar -Dfile=bookkeeper-3.4.0.jar
+
+Then to compile omid:
+
+ $ tar jxvf omid-1.0-SNAPSHOT.tar.bz2
+ $ cd omid-1.0-SNAPSHOT
+ $ mvn install
+
+Tests should run cleanly.
+
+Running
+-------
+
+You need to run four components before running the transactional
+client. They are bookkeeper, zookeeper, omid tso and
+hbase. Bookkeeper is needed by the TSO. Zookeeper is needed by
+bookkeeper and hbase. The TSO is needed by hbase. Hence, the order of
+starting should be:
+ 1. Zookeeper
+ 2. Bookkeeper
+ 3. TSO
+ 4. Hbase
+
+### Zookeeper & Bookkeeper
+For simplicity we've included a utility script which starts zookeeper
+and bookkeeper. Run:
+
+ $ bin/omid.sh bktest
+
+Omid doesn't use anything special in zookeeper or bookkeeper, so you
+can use any install for these. However, if you are running this
+anywhere but localhost, you need to update the setting for hbase and
+TSO. See the hbase docs for changing the zookeeper quorum. For TSO,
+you need to modify bin/omid.sh.
+
+### TSO
+To start the TSO, run:
+
+ $ bin/omid.sh tso
+
+### Benchmark
+To benchmark the TSO alone, run:
+
+ $ bin/omid.sh tsobench
+
+### HBase
+We've included a utility script to start a HBase cluster on your local
+machine. Run:
+
+ $ bin/omid.sh tran-hbase
+
+For running in a cluster
+
+API
+---
+
+The public api is in
+
+ src/main/java/com/yahoo/omid/client/TransactionalTable.java
+ src/main/java/com/yahoo/omid/client/TransactionState.java
+ src/main/java/com/yahoo/omid/client/TransactionManager.java
+
+For an example of usage, look in
+
+ src/test/java/com/yahoo/omid/TestBasicTransaction.java
+
+Logging
+-------
+Logging can be adjusted in src/main/resource/log4j.properties.
97 bin/omid.sh
@@ -0,0 +1,97 @@
+#!/bin/bash
+
+########################################################################
+#
+# Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+#
+# 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. See accompanying LICENSE file.
+#
+########################################################################
+
+
+BUFFERSIZE=1000;
+BATCHSIZE=0;
+
+SCRIPTDIR=`dirname $0`
+cd $SCRIPTDIR;
+CLASSPATH=../conf
+for j in ../target/omid*.jar; do
+ CLASSPATH=$CLASSPATH:$j
+done
+
+for j in ../lib/*.jar; do
+ CLASSPATH=$CLASSPATH:$j
+done
+
+if which greadlink; then
+ READLINK=greadlink
+else
+ READLINK=readlink
+fi
+
+tso() {
+ export LD_LIBRARY_PATH=`$READLINK -f ../src/main/native`
+ exec java -Xmx1024m -cp $CLASSPATH -Djava.library.path=$LD_LIBRARY_PATH -Dlog4j.configuration=log4j.properties com.yahoo.omid.tso.TSOServer 1234 $BATCHSIZE 4 2 localhost:2181
+}
+
+tsobench() {
+ exec java -Xmx1024m -cp $CLASSPATH -Dlog4j.configuration=log4j.properties com.yahoo.omid.tso.TransactionClient localhost 1234 100000 10 5
+}
+
+bktest() {
+ exec java -cp $CLASSPATH -Dlog4j.configuration=log4j.properties org.apache.bookkeeper.util.LocalBookKeeper 5
+}
+
+tranhbase() {
+ pwd
+ echo $CLASSPATH
+ exec java -cp $CLASSPATH org.apache.hadoop.hbase.LocalHBaseCluster
+}
+
+testtable() {
+ exec java -cp $CLASSPATH:../target/test-classes com.yahoo.omid.TestTable
+}
+
+usage() {
+ echo "Usage: omid.sh <command>"
+ echo "where <command> is one of:"
+ echo " tso Start the timestamp oracle server."
+ echo " tsobench Run a simple benchmark of the TsO."
+ echo " bktest Start test bookkeeper ensemble. Starts zookeeper also."
+ echo " tran-hbase Start hbase with transaction support."
+ echo " test-table Create test table"
+}
+
+# if no args specified, show usage
+if [ $# = 0 ]; then
+ usage;
+ exit 1
+fi
+
+COMMAND=$1
+
+if [ "$COMMAND" = "tso" ]; then
+ tso;
+elif [ "$COMMAND" = "tsobench" ]; then
+ tsobench;
+elif [ "$COMMAND" = "bktest" ]; then
+ bktest;
+elif [ "$COMMAND" = "tran-hbase" ]; then
+ tranhbase;
+elif [ "$COMMAND" = "test-table" ]; then
+ testtable;
+else
+ usage;
+fi
+
+
25 conf/hbase-site.xml
@@ -0,0 +1,25 @@
+<!--
+ Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+
+ 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. See accompanying LICENSE file.
+ -->
+<configuration>
+ <property>
+ <name>tso.host</name>
+ <value>localhost</value>
+ </property>
+ <property>
+ <name>tso.port</name>
+ <value>1234</value>
+ </property>
+</configuration>
132 pom.xml
@@ -0,0 +1,132 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+
+<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.yahoo</groupId>
+ <artifactId>omid</artifactId>
+ <packaging>jar</packaging>
+ <version>1.0-SNAPSHOT</version>
+ <name>omid</name>
+ <url>http://maven.apache.org</url>
+
+ <repositories>
+ <repository>
+ <id>repository.jboss.org</id>
+ <url>http://repository.jboss.org/nexus/content/groups/public/</url>
+ </repository>
+ </repositories>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>copy-dependencies</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${basedir}/lib</outputDirectory>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>build-native</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <tasks>
+ <property name="native.classpath" refid="maven.compile.classpath" />
+ <echo file="${project.build.directory}/compile-classpath" message="${native.classpath}" />
+ <exec dir="src/main/native" executable="make" failonerror="true"/>
+ </tasks>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.7.1</version>
+ <configuration>
+ <!-- forkMode>pertest</forkMode -->
+ <argLine>-Djava.library.path=${basedir}/src/main/native</argLine>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.8.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.14</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.netty</groupId>
+ <artifactId>netty</artifactId>
+ <version>3.1.2.GA</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.zookeeper</groupId>
+ <artifactId>bookkeeper</artifactId>
+ <version>3.4.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.zookeeper</groupId>
+ <artifactId>zookeeper</artifactId>
+ <version>3.4.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ <version>1.2.1</version>
+ <type>jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase</artifactId>
+ <version>0.90.2</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+ </dependencies>
+</project>
21 src/main/java/com/yahoo/omid/client/AbortCompleteCallback.java
@@ -0,0 +1,21 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public interface AbortCompleteCallback extends Callback {
+ public void complete();
+}
21 src/main/java/com/yahoo/omid/client/Callback.java
@@ -0,0 +1,21 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public interface Callback {
+ public void error(Exception e);
+}
24 src/main/java/com/yahoo/omid/client/CommitCallback.java
@@ -0,0 +1,24 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+import com.yahoo.omid.client.TSOClient.Result;
+
+public interface CommitCallback extends Callback {
+ public void complete(Result res, long commitTimestamp);
+}
+
21 src/main/java/com/yahoo/omid/client/CommitQueryCallback.java
@@ -0,0 +1,21 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public interface CommitQueryCallback extends Callback {
+ public void complete(boolean committed);
+}
21 src/main/java/com/yahoo/omid/client/CommitUnsuccessfulException.java
@@ -0,0 +1,21 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public class CommitUnsuccessfulException extends Exception {
+ private static final long serialVersionUID = -9163407697376986830L;
+}
22 src/main/java/com/yahoo/omid/client/CreateCallback.java
@@ -0,0 +1,22 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public interface CreateCallback extends Callback {
+ public void complete(long startTimestamp);
+}
+
18 src/main/java/com/yahoo/omid/client/CreateCallbackImpl.java
@@ -0,0 +1,18 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
57 src/main/java/com/yahoo/omid/client/RowKeyFamily.java
@@ -0,0 +1,57 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.hadoop.hbase.KeyValue;
+
+import com.yahoo.omid.tso.RowKey;
+
+public class RowKeyFamily extends RowKey {
+
+ private Map<byte[], List<KeyValue>> families;
+
+ public RowKeyFamily() {
+ super();
+ }
+
+ public RowKeyFamily(byte [] r, byte [] t, Map<byte[], List<KeyValue>> families) {
+ super(r, t);
+ this.families = families;
+ }
+
+ public Map<byte[], List<KeyValue>> getFamilies() {
+ return families;
+ }
+
+ public void setFamilies(Map<byte[], List<KeyValue>> families) {
+ this.families = families;
+ }
+
+ public void addFamily(byte [] row, KeyValue kv) {
+ List<KeyValue> kvs = families.get(row);
+ if (kvs == null) {
+ kvs = new ArrayList<KeyValue>();
+ families.put(row, kvs);
+ }
+ kvs.add(kv);
+ }
+
+}
26 src/main/java/com/yahoo/omid/client/SyncAbortCompleteCallback.java
@@ -0,0 +1,26 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public class SyncAbortCompleteCallback extends SyncCallbackBase
+ implements AbortCompleteCallback {
+
+ synchronized
+ public void complete() {
+ countDown();
+ }
+}
43 src/main/java/com/yahoo/omid/client/SyncCallbackBase.java
@@ -0,0 +1,43 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+
+import java.util.concurrent.CountDownLatch;
+
+class SyncCallbackBase implements Callback {
+ private Exception e = null;
+ private CountDownLatch latch = new CountDownLatch(1);;
+
+ public Exception getException() {
+ return e;
+ }
+
+ synchronized
+ public void error(Exception e) {
+ this.e = e;
+ countDown();
+ }
+
+ protected void countDown() {
+ latch.countDown();
+ }
+
+ public void await() throws InterruptedException {
+ latch.await();
+ }
+}
40 src/main/java/com/yahoo/omid/client/SyncCommitCallback.java
@@ -0,0 +1,40 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+import com.yahoo.omid.client.TSOClient.Result;
+
+public class SyncCommitCallback extends SyncCallbackBase implements CommitCallback {
+ private Result result;
+ private long commitTimestamp;
+
+ public Result getResult() {
+ return result;
+ }
+
+ public long getCommitTimestamp() {
+ return commitTimestamp;
+ }
+
+ synchronized
+ public void complete(Result res, long commitTimestamp) {
+ this.result = res;
+ this.commitTimestamp = commitTimestamp;
+ countDown();
+ }
+}
+
32 src/main/java/com/yahoo/omid/client/SyncCommitQueryCallback.java
@@ -0,0 +1,32 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public class SyncCommitQueryCallback extends SyncCallbackBase
+ implements CommitQueryCallback {
+ private boolean committed = false;
+
+ public boolean isCommitted() {
+ return committed;
+ }
+
+ synchronized
+ public void complete(boolean committed) {
+ this.committed = committed;
+ countDown();
+ }
+}
34 src/main/java/com/yahoo/omid/client/SyncCreateCallback.java
@@ -0,0 +1,34 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+
+public class SyncCreateCallback extends SyncCallbackBase implements CreateCallback {
+ private long startTimestamp = 0;
+
+ public long getStartTimestamp() {
+ return startTimestamp;
+ }
+
+ synchronized
+ public void complete(long startTimestamp) {
+ this.startTimestamp = startTimestamp;
+ countDown();
+ }
+}
+
+
569 src/main/java/com/yahoo/omid/client/TSOClient.java
@@ -0,0 +1,569 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.Executors;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.jboss.netty.bootstrap.ClientBootstrap;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelFactory;
+import org.jboss.netty.channel.ChannelFuture;
+import org.jboss.netty.channel.ChannelFutureListener;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.channel.ChannelPipelineCoverage;
+import org.jboss.netty.channel.ChannelStateEvent;
+import org.jboss.netty.channel.ExceptionEvent;
+import org.jboss.netty.channel.MessageEvent;
+import org.jboss.netty.channel.SimpleChannelHandler;
+import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
+
+import com.yahoo.omid.tso.Committed;
+import com.yahoo.omid.tso.RowKey;
+import com.yahoo.omid.tso.messages.AbortedTransactionReport;
+import com.yahoo.omid.tso.messages.CommitQueryRequest;
+import com.yahoo.omid.tso.messages.CommitQueryResponse;
+import com.yahoo.omid.tso.messages.CommitRequest;
+import com.yahoo.omid.tso.messages.CommitResponse;
+import com.yahoo.omid.tso.messages.CommittedTransactionReport;
+import com.yahoo.omid.tso.messages.FullAbortReport;
+import com.yahoo.omid.tso.messages.LargestDeletedTimestampReport;
+import com.yahoo.omid.tso.messages.TimestampRequest;
+import com.yahoo.omid.tso.messages.TimestampResponse;
+import com.yahoo.omid.tso.serialization.TSODecoder;
+import com.yahoo.omid.tso.serialization.TSOEncoder;
+
+@ChannelPipelineCoverage("one")
+public class TSOClient extends SimpleChannelHandler {
+ private static final Log LOG = LogFactory.getLog(TSOClient.class);
+
+ public static long askedTSO = 0;
+
+ public enum Result {
+ OK, ABORTED
+ };
+
+ private Queue<CreateCallback> createCallbacks;
+ private Map<Long, CommitCallback> commitCallbacks;
+ private Map<Long, List<CommitQueryCallback>> isCommittedCallbacks;
+
+ private Committed committed = new Committed();
+ private Set<Long> aborted = Collections.synchronizedSet(new HashSet<Long>(1000));
+ private long largestDeletedTimestamp;
+ private long connectionTimestamp = 0;
+ private boolean hasConnectionTimestamp = false;
+
+ private ChannelFactory factory;
+ private ClientBootstrap bootstrap;
+ private Channel channel;
+ private InetSocketAddress addr;
+ private int max_retries;
+ private int retries;
+ private int retry_delay_ms;
+ private Timer retryTimer;
+
+ private enum State {
+ DISCONNECTED, CONNECTING, CONNECTED, RETRY_CONNECT_WAIT
+ };
+
+ private interface Op {
+ public void execute(Channel channel);
+ public void error(Exception e);
+ }
+
+ private class NewTimestampOp implements Op {
+ private CreateCallback cb;
+
+ NewTimestampOp(CreateCallback cb) {
+ this.cb = cb;
+ }
+
+ public void execute(Channel channel) {
+ try {
+ synchronized(createCallbacks) {
+ createCallbacks.add(cb);
+ }
+
+ TimestampRequest tr = new TimestampRequest();
+ ChannelFuture f = channel.write(tr);
+ f.addListener(new ChannelFutureListener() {
+ public void operationComplete(ChannelFuture future) {
+ if (!future.isSuccess()) {
+ error(new IOException("Error writing to socket"));
+ }
+ }
+ });
+ } catch (Exception e) {
+ error(e);
+ }
+ }
+
+ public void error(Exception e) {
+ synchronized(createCallbacks) {
+ createCallbacks.remove();
+ }
+
+ cb.error(e);
+ }
+ }
+
+ private class CommitQueryOp implements Op {
+ long startTimestamp;
+ long pendingWriteTimestamp;
+ CommitQueryCallback cb;
+
+ CommitQueryOp(long startTimestamp, long pendingWriteTimestamp, CommitQueryCallback cb) {
+ this.startTimestamp = startTimestamp;
+ this.pendingWriteTimestamp = pendingWriteTimestamp;
+ this.cb = cb;
+ }
+
+ public void execute(Channel channel) {
+ try {
+ synchronized(isCommittedCallbacks) {
+ List<CommitQueryCallback> callbacks = isCommittedCallbacks.get(startTimestamp);
+ if (callbacks == null) {
+ callbacks = new ArrayList<CommitQueryCallback>(1);
+ }
+ callbacks.add(cb);
+ isCommittedCallbacks.put(startTimestamp, callbacks);
+ }
+
+ CommitQueryRequest qr = new CommitQueryRequest(startTimestamp,
+ pendingWriteTimestamp);
+ ChannelFuture f = channel.write(qr);
+ f.addListener(new ChannelFutureListener() {
+ public void operationComplete(ChannelFuture future) {
+ if (!future.isSuccess()) {
+ error(new IOException("Error writing to socket"));
+ }
+ }
+ });
+ } catch (Exception e) {
+ error(e);
+ }
+ }
+
+ public void error(Exception e) {
+ synchronized(isCommittedCallbacks) {
+ isCommittedCallbacks.remove(startTimestamp);
+ }
+
+ cb.error(e);
+ }
+ }
+
+ private class CommitOp implements Op {
+ long transactionId;
+ RowKey[] rows;
+ CommitCallback cb;
+
+ CommitOp(long transactionid, RowKey[] rows, CommitCallback cb) throws IOException {
+ this.transactionId = transactionid;
+ this.rows = rows;
+ this.cb = cb;
+ }
+
+ public void execute(Channel channel) {
+ try {
+ synchronized(commitCallbacks) {
+ if (commitCallbacks.containsKey(transactionId)) {
+ throw new IOException("Already committing transaction " + transactionId);
+ }
+ commitCallbacks.put(transactionId, cb);
+ }
+
+ CommitRequest cr = new CommitRequest();
+ cr.startTimestamp = transactionId;
+ cr.rows = rows;
+ ChannelFuture f = channel.write(cr);
+ f.addListener(new ChannelFutureListener() {
+ public void operationComplete(ChannelFuture future) {
+ if (!future.isSuccess()) {
+ error(new IOException("Error writing to socket"));
+ }
+ }
+ });
+ } catch (Exception e) {
+ error(e);
+ }
+ }
+
+ public void error(Exception e) {
+ synchronized(commitCallbacks) {
+ commitCallbacks.remove(transactionId);
+ }
+ cb.error(e);
+ }
+ }
+
+ private class AbortCompleteOp implements Op {
+ long transactionId;
+ AbortCompleteCallback cb;
+
+ AbortCompleteOp(long transactionId, AbortCompleteCallback cb) throws IOException {
+ this.transactionId = transactionId;
+ this.cb = cb;
+ }
+
+ public void execute(Channel channel) {
+ try {
+ FullAbortReport far = new FullAbortReport();
+ far.startTimestamp = transactionId;
+
+ ChannelFuture f = channel.write(far);
+ f.addListener(new ChannelFutureListener() {
+ public void operationComplete(ChannelFuture future) {
+ if (!future.isSuccess()) {
+ error(new IOException("Error writing to socket"));
+ } else {
+ cb.complete();
+ }
+ }
+ });
+ } catch (Exception e) {
+ error(e);
+ }
+
+ }
+
+ public void error(Exception e) {
+ cb.error(e);
+ }
+ }
+
+ private ArrayBlockingQueue<Op> queuedOps;
+
+ private State state;
+
+ public TSOClient(Configuration conf) throws IOException {
+ state = State.DISCONNECTED;
+ queuedOps = new ArrayBlockingQueue<Op>(200);
+ retryTimer = new Timer(true);
+
+ commitCallbacks = Collections.synchronizedMap(new HashMap<Long, CommitCallback>());
+ isCommittedCallbacks = Collections.synchronizedMap(new HashMap<Long, List<CommitQueryCallback>>());
+ createCallbacks = new ConcurrentLinkedQueue<CreateCallback>();
+ channel = null;
+
+ System.out.println("Starting TSOClient");
+
+ // Start client with Nb of active threads = 3 as maximum.
+ factory = new NioClientSocketChannelFactory(Executors
+ .newCachedThreadPool(), Executors.newCachedThreadPool(), 3);
+ // Create the bootstrap
+ bootstrap = new ClientBootstrap(factory);
+
+ bootstrap.getPipeline().addLast("handler", this);
+ bootstrap.setOption("tcpNoDelay", false);
+ bootstrap.setOption("keepAlive", true);
+ bootstrap.setOption("reuseAddress", true);
+ bootstrap.setOption("connectTimeoutMillis", 100);
+
+ String host = conf.get("tso.host");
+ int port = conf.getInt("tso.port", 1234);
+ max_retries = conf.getInt("tso.max_retries", 10);
+ retry_delay_ms = conf.getInt("tso.retry_delay_ms", 3000);
+
+ if (host == null) {
+ throw new IOException("tso.host missing from configuration");
+ }
+
+ addr = new InetSocketAddress(host, port);
+ connectIfNeeded();
+ }
+
+ private State connectIfNeeded() throws IOException {
+ synchronized (state) {
+ if (state == State.CONNECTED || state == State.CONNECTING) {
+ return state;
+ }
+ if (state == State.RETRY_CONNECT_WAIT) {
+ return State.CONNECTING;
+ }
+
+ if (retries > max_retries) {
+ IOException e = new IOException("Max connection retries exceeded");
+ bailout(e);
+ throw e;
+ }
+ retries++;
+ bootstrap.connect(addr);
+ state = State.CONNECTING;
+ return state;
+ }
+ }
+
+ private void withConnection(Op op) throws IOException {
+ State state = connectIfNeeded();
+
+ if (state == State.CONNECTING) {
+ try {
+ queuedOps.put(op);
+ } catch (InterruptedException e) {
+ throw new IOException("Couldn't add new operation", e);
+ }
+ } else if (state == State.CONNECTED) {
+ op.execute(channel);
+ } else {
+ throw new IOException("Invalid connection state " + state);
+ }
+ }
+
+ public void getNewTimestamp(CreateCallback cb) throws IOException {
+ withConnection(new NewTimestampOp(cb));
+ }
+
+ public void isCommitted(long startTimestamp, long pendingWriteTimestamp, CommitQueryCallback cb)
+ throws IOException {
+ withConnection(new CommitQueryOp(startTimestamp, pendingWriteTimestamp, cb));
+ }
+
+ public void commit(long transactionId, RowKey[] rows, CommitCallback cb) throws IOException {
+ withConnection(new CommitOp(transactionId, rows, cb));
+ }
+
+ public void completeAbort(long transactionId, AbortCompleteCallback cb) throws IOException {
+ withConnection(new AbortCompleteOp(transactionId, cb));
+ }
+
+ @Override
+ synchronized
+ public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
+ e.getChannel().getPipeline().addFirst("decoder", new TSODecoder());
+ e.getChannel().getPipeline().addAfter("decoder", "encoder",
+ new TSOEncoder());
+ }
+
+ /**
+ * Starts the traffic
+ */
+ @Override
+ synchronized
+ public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
+ synchronized (state) {
+ channel = e.getChannel();
+ state = State.CONNECTED;
+ retries = 0;
+ }
+ clearState();
+ Op o = queuedOps.poll();;
+ while (o != null && state == State.CONNECTED) {
+ o.execute(channel);
+ o = queuedOps.poll();
+ }
+ }
+
+ private void clearState() {
+ committed = new Committed();
+ aborted.clear();
+ largestDeletedTimestamp = 0;
+ connectionTimestamp = 0;
+ hasConnectionTimestamp = false;
+ }
+
+ @Override
+ synchronized
+ public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)
+ throws Exception {
+ synchronized(state) {
+ channel = null;
+ state = State.DISCONNECTED;
+ }
+ }
+
+ public boolean validRead(long transaction, long startTimestamp) throws IOException {
+ if (transaction == startTimestamp)
+ return true;
+ if (aborted.contains(transaction))
+ return false;
+ long commitTimestamp = committed.getCommit(transaction);
+ if (commitTimestamp != -1)
+ return commitTimestamp <= startTimestamp;
+ if (hasConnectionTimestamp && transaction > connectionTimestamp)
+ return transaction <= largestDeletedTimestamp;
+ if (transaction <= largestDeletedTimestamp)
+ return true;
+// System.out.format("Asking TSO... hasConnectionTimestamp: %s connectionTimestamp: %d transaction: %d startTimestamp: %d\n",
+// Boolean.valueOf(hasConnectionTimestamp).toString(), connectionTimestamp, transaction, startTimestamp);
+ askedTSO++;
+ SyncCommitQueryCallback cb = new SyncCommitQueryCallback();
+ isCommitted(startTimestamp, transaction, cb);
+ try {
+ cb.await();
+ } catch (InterruptedException e) {
+ throw new IOException("Commit query didn't complete", e);
+ }
+ return cb.isCommitted();
+ }
+
+ /**
+ * When a message is received, handle it based on its type
+ */
+ @Override
+ public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("messageReceived " + e.getMessage());
+ }
+ Object msg = e.getMessage();
+ if (msg instanceof CommitResponse) {
+ CommitResponse r = (CommitResponse)msg;
+ CommitCallback cb = null;
+ synchronized (commitCallbacks) {
+ cb = commitCallbacks.remove(r.startTimestamp);
+ }
+ if (cb == null) {
+ LOG.error("Received a commit response for a nonexisting commit");
+ return;
+ }
+ cb.complete(r.committed ? Result.OK : Result.ABORTED, r.commitTimestamp);
+ } else if (msg instanceof TimestampResponse) {
+ CreateCallback cb = createCallbacks.poll();
+ long timestamp = ((TimestampResponse)msg).timestamp;
+ if (!hasConnectionTimestamp || timestamp < connectionTimestamp) {
+ hasConnectionTimestamp = true;
+ connectionTimestamp = timestamp;
+ }
+ if (cb == null) {
+ LOG.error("Receiving a timestamp response, but none requested: " + timestamp);
+ return;
+ }
+ cb.complete(timestamp);
+ } else if (msg instanceof CommitQueryResponse) {
+ CommitQueryResponse r = (CommitQueryResponse)msg;
+ if (r.commitTimestamp != 0) {
+ committed.commit(r.queryTimestamp, r.commitTimestamp);
+ } else if (r.committed) {
+ committed.commit(r.queryTimestamp, largestDeletedTimestamp);
+ }
+ List<CommitQueryCallback> cbs = null;
+ synchronized (isCommittedCallbacks) {
+ cbs = isCommittedCallbacks.remove(r.startTimestamp);
+ }
+ if (cbs == null) {
+ LOG.error("Received a commit query response for a nonexisting request");
+ return;
+ }
+ for (CommitQueryCallback cb : cbs) {
+ cb.complete(r.committed);
+ }
+ } else if (msg instanceof CommittedTransactionReport) {
+ CommittedTransactionReport ctr = (CommittedTransactionReport) msg;
+ committed.commit(ctr.startTimestamp, ctr.commitTimestamp);
+ } else if (msg instanceof FullAbortReport) {
+ FullAbortReport r = (FullAbortReport) msg;
+ aborted.remove(r.startTimestamp);
+ } else if (msg instanceof AbortedTransactionReport) {
+ AbortedTransactionReport r = (AbortedTransactionReport) msg;
+ aborted.add(r.startTimestamp);
+ } else if (msg instanceof LargestDeletedTimestampReport) {
+ LargestDeletedTimestampReport r = (LargestDeletedTimestampReport) msg;
+ largestDeletedTimestamp = r.largestDeletedTimestamp;
+ committed.raiseLargestDeletedTransaction(r.largestDeletedTimestamp);
+ } else {
+ LOG.error("Unknown message received " + msg);
+ }
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx,
+ ExceptionEvent e)
+ throws Exception {
+ System.out.println("Unexpected exception " + e.getCause());
+ e.getCause().printStackTrace();
+
+ synchronized(state) {
+
+ if (state == State.CONNECTING) {
+ state = State.RETRY_CONNECT_WAIT;
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Retrying connect in " + retry_delay_ms + "ms " + retries);
+ }
+ try {
+ retryTimer.schedule(new TimerTask() {
+ public void run() {
+ synchronized (state) {
+ state = State.DISCONNECTED;
+ try {
+ connectIfNeeded();
+ } catch (IOException e) {
+ bailout(e);
+ }
+ }
+ }
+ }, retry_delay_ms);
+ } catch (Exception cause) {
+ bailout(cause);
+ }
+ } else {
+ LOG.error("Exception on channel", e.getCause());
+ }
+ }
+ }
+
+ public void bailout(Exception cause) {
+ synchronized (state) {
+ state = State.DISCONNECTED;
+ }
+ LOG.error("Unrecoverable error in client, bailing out", cause);
+ Exception e = new IOException("Unrecoverable error", cause);
+ Op o = queuedOps.poll();;
+ while (o != null) {
+ o.error(e);
+ o = queuedOps.poll();
+ }
+ synchronized (createCallbacks) {
+ for (CreateCallback cb : createCallbacks) {
+ cb.error(e);
+ }
+ createCallbacks.clear();
+ }
+
+ synchronized(commitCallbacks) {
+ for (CommitCallback cb : commitCallbacks.values()) {
+ cb.error(e);
+ }
+ commitCallbacks.clear();
+ }
+
+ synchronized(isCommittedCallbacks) {
+ for (List<CommitQueryCallback> cbs : isCommittedCallbacks.values()) {
+ for (CommitQueryCallback cb : cbs) {
+ cb.error(e);
+ }
+ }
+ isCommittedCallbacks.clear();
+ }
+ }
+
+}
30 src/main/java/com/yahoo/omid/client/TransactionException.java
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+public class TransactionException extends Exception {
+
+ private static final long serialVersionUID = 7273525983622126275L;
+
+ public TransactionException(String reason) {
+ super(reason);
+ }
+
+ public TransactionException(String reason, Exception e) {
+ super(reason, e);
+ }
+}
149 src/main/java/com/yahoo/omid/client/TransactionManager.java
@@ -0,0 +1,149 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.HTable;
+
+/**
+ * Provides the methods necessary to create and commit transactions.
+ *
+ * @see TransactionalTable
+ *
+ */
+public class TransactionManager {
+ private static final Log LOG = LogFactory.getLog(TSOClient.class);
+
+ static TSOClient tsoclient = null;
+ private static Object lock = new Object();
+ private Configuration conf;
+ private HashMap<byte[], HTable> tableCache;
+
+ public TransactionManager(Configuration conf) throws TransactionException, IOException {
+ this.conf = conf;
+ synchronized (lock) {
+ if (tsoclient == null) {
+ tsoclient = new TSOClient(conf);
+ }
+ }
+ tableCache = new HashMap<byte[], HTable>();
+ }
+
+ /**
+ * Starts a new transaction.
+ *
+ * This method returns an opaque {@link TransactionState} object, used by {@link TransactionalTable}'s methods
+ * for performing operations on a given transaction.
+ *
+ * @return Opaque object which identifies one transaction.
+ * @throws TransactionException
+ */
+ public TransactionState beginTransaction() throws TransactionException {
+ SyncCreateCallback cb = new SyncCreateCallback();
+ try {
+ tsoclient.getNewTimestamp(cb);
+ cb.await();
+ } catch (Exception e) {
+ throw new TransactionException("Could not get new timestamp", e);
+ }
+ if (cb.getException() != null) {
+ throw new TransactionException("Error retrieving timestamp", cb.getException());
+ }
+
+ return new TransactionState(cb.getStartTimestamp(), tsoclient);
+ }
+
+ /**
+ * Commits a transaction. If the transaction is aborted it automatically rollbacks the changes and
+ * throws a {@link CommitUnsuccessfulException}.
+ *
+ * @param transactionState Object identifying the transaction to be committed.
+ * @throws CommitUnsuccessfulException
+ * @throws TransactionException
+ */
+ public void tryCommit(TransactionState transactionState)
+ throws CommitUnsuccessfulException, TransactionException {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("tryCommit " + transactionState.getStartTimestamp());
+ }
+ SyncCommitCallback cb = new SyncCommitCallback();
+ try {
+ tsoclient.commit(transactionState.getStartTimestamp(),
+ transactionState.getRows(), cb);
+ cb.await();
+ } catch (Exception e) {
+ throw new TransactionException("Could not commit", e);
+ }
+ if (cb.getException() != null) {
+ throw new TransactionException("Error committing", cb.getException());
+ }
+
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("doneCommit " + transactionState.getStartTimestamp() +
+ " TS_c: " + cb.getCommitTimestamp() +
+ " Success: " + (cb.getResult() == TSOClient.Result.OK));
+ }
+
+ if (cb.getResult() == TSOClient.Result.ABORTED) {
+ cleanup(transactionState);
+ throw new CommitUnsuccessfulException();
+ }
+ transactionState.setCommitTimestamp(cb.getCommitTimestamp());
+ }
+
+ private void cleanup(final TransactionState transactionState)
+ throws TransactionException {
+ Map<byte[], List<Delete>> deleteBatches = new HashMap<byte[], List<Delete>>();
+ for (final RowKeyFamily rowkey : transactionState.getRows()) {
+ List<Delete> batch = deleteBatches.get(rowkey.getTable());
+ if (batch == null) {
+ batch = new ArrayList<Delete>();
+ deleteBatches.put(rowkey.getTable(), batch);
+ }
+ Delete delete = new Delete(rowkey.getRow());
+ for (Entry<byte[], List<KeyValue>> entry : rowkey.getFamilies().entrySet()) {
+ for (KeyValue kv : entry.getValue()) {
+ delete.deleteColumn(entry.getKey(), kv.getQualifier(), transactionState.getStartTimestamp());
+ }
+ }
+ batch.add(delete);
+ }
+ for (final Entry<byte[], List<Delete>> entry : deleteBatches.entrySet()) {
+ try {
+ HTable table = tableCache.get(entry.getKey());
+ if (table == null) {
+ table = new HTable(conf, entry.getKey());
+ tableCache.put(entry.getKey(), table);
+ }
+ table.delete(entry.getValue());
+ } catch (IOException ioe) {
+ throw new TransactionException("Could not clean up for table " + entry.getKey(), ioe);
+ }
+ }
+ }
+}
65 src/main/java/com/yahoo/omid/client/TransactionState.java
@@ -0,0 +1,65 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class TransactionState {
+ private long startTimestamp;
+ private long commitTimestamp;
+ private Set<RowKeyFamily> rows;
+
+ public TSOClient tsoclient;
+
+ TransactionState() {
+ startTimestamp = 0;
+ commitTimestamp = 0;
+ this.rows = new HashSet<RowKeyFamily>();
+ }
+
+ TransactionState(long startTimestamp, TSOClient client) {
+ this();
+ this.startTimestamp = startTimestamp;;
+ this.commitTimestamp = 0;
+ this.tsoclient = client;
+ }
+
+ long getStartTimestamp() {
+ return startTimestamp;
+ }
+
+ long getCommitTimestamp() {
+ return commitTimestamp;
+ }
+
+ void setCommitTimestamp(long commitTimestamp) {
+ this.commitTimestamp = commitTimestamp;
+ }
+
+ RowKeyFamily[] getRows() {
+ return rows.toArray(new RowKeyFamily[0]);
+ }
+
+ void addRow(RowKeyFamily row) {
+ rows.add(row);
+ }
+
+ public String toString() {
+ return "Transaction-" + Long.toHexString(startTimestamp);
+ }
+}
469 src/main/java/com/yahoo/omid/client/TransactionalTable.java
@@ -0,0 +1,469 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * 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. See accompanying LICENSE file.
+ */
+
+package com.yahoo.omid.client;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.NavigableMap;
+import java.util.NavigableSet;
+import java.util.Set;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.Get;
+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.TimeRange;
+import org.apache.hadoop.hbase.util.Bytes;
+
+/**
+ * Provides transactional methods for accessing and modifying a given snapshot of data identified by an opaque
+ * {@link TransactionState} object.
+ *
+ */
+public class TransactionalTable extends HTable {
+
+ public static long getsPerformed = 0;
+ public static long elementsGotten = 0;
+ public static long elementsRead = 0;
+ public static long extraGetsPerformed = 0;
+ public static double extraVersionsAvg = 3;
+
+ private static int CACHE_VERSIONS_OVERHEAD = 3;
+// private int cacheVersions = 3;
+ public double versionsAvg = 3;
+ private static final double alpha = 0.975;
+// private static final double betha = 1.25;
+
+// private static Thread monitor = new ThroughputMonitor();
+// private static boolean started = false;
+// {
+// synchronized(monitor) {
+// if (!started) {
+// started = true;
+// monitor.start();
+// }
+// }
+// }
+
+ public TransactionalTable(Configuration conf, byte[] tableName) throws IOException {
+ super(conf, tableName);
+ }
+
+ public TransactionalTable(Configuration conf, String tableName) throws IOException {
+ this(conf, Bytes.toBytes(tableName));
+ }
+
+ /**
+ * Transactional version of {@link HTable#get(Get)}
+ *
+ * @param transactionState Identifier of the transaction
+ * @see HTable#get(Get)
+ * @throws IOException
+ */
+ public Result get(TransactionState transactionState, final Get get) throws IOException {
+ final long readTimestamp = transactionState.getStartTimestamp();
+ final Get tsget = new Get(get.getRow());
+ TimeRange timeRange = get.getTimeRange();
+ long startTime = timeRange.getMin();
+ long endTime = Math.min(timeRange.getMax(), readTimestamp + 1);
+// int maxVersions = get.getMaxVersions();
+ tsget.setTimeRange(startTime, endTime).setMaxVersions((int) (versionsAvg + CACHE_VERSIONS_OVERHEAD));
+ Map<byte[], NavigableSet<byte[]>> kvs = get.getFamilyMap();
+ for (Map.Entry<byte[], NavigableSet<byte[]>> entry : kvs.entrySet()) {
+ byte[] family = entry.getKey();
+ NavigableSet<byte[]> qualifiers = entry.getValue();
+ if (qualifiers == null || qualifiers.isEmpty()) {
+ tsget.addFamily(family);
+ } else {
+ for (byte[] qualifier : qualifiers) {
+ tsget.addColumn(family, qualifier);
+ }
+ }
+ }
+// Result result;
+// Result filteredResult;
+// do {
+// result = super.get(tsget);
+// filteredResult = filter(super.get(tsget), readTimestamp, maxVersions);
+// } while (!result.isEmpty() && filteredResult == null);
+ getsPerformed++;
+ Result result = filter(transactionState, super.get(tsget), readTimestamp, (int) (versionsAvg + CACHE_VERSIONS_OVERHEAD));
+ return result == null ? new Result() : result;
+// Scan scan = new Scan(get);
+// scan.setRetainDeletesInOutput(true);
+// ResultScanner rs = this.getScanner(transactionState, scan);
+// Result r = rs.next();
+// if (r == null) {
+// r = new Result();
+// }
+// return r;
+ }
+
+ /**
+ * Transactional version of {@link HTable#delete(Delete)}
+ *
+ * @param transactionState Identifier of the transaction
+ * @see HTable#delete(Delete)
+ * @throws IOException
+ */
+ public void delete(TransactionState transactionState, Delete delete) throws IOException {
+ final long startTimestamp = transactionState.getStartTimestamp();
+ boolean issueGet = false;
+
+ final Put deleteP = new Put(delete.getRow(), startTimestamp);
+ final Get deleteG = new Get(delete.getRow());
+ Map<byte[], List<KeyValue>> fmap = delete.getFamilyMap();
+ if (fmap.isEmpty()) {
+ issueGet = true;
+ }
+ for (List<KeyValue> kvl : fmap.values()) {
+ for (KeyValue kv : kvl) {
+ switch(KeyValue.Type.codeToType(kv.getType())) {
+ case DeleteColumn:
+ deleteP.add(kv.getFamily(), kv.getQualifier(), startTimestamp, null);
+ break;
+ case DeleteFamily:
+ deleteG.addFamily(kv.getFamily());
+ issueGet = true;
+ break;
+ case Delete:
+ if (kv.getTimestamp() == HConstants.LATEST_TIMESTAMP) {
+ deleteP.add(kv.getFamily(), kv.getQualifier(), startTimestamp, null);
+ break;
+ } else {
+ throw new UnsupportedOperationException("Cannot delete specific versions on Snapshot Isolation.");
+ }
+ }
+ }
+ }
+ if (issueGet) {
+ Result result = this.get(deleteG);
+ for (Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> entryF : result.getMap().entrySet()) {
+ byte[] family = entryF.getKey();
+ for (Entry<byte[], NavigableMap<Long, byte[]>> entryQ : entryF.getValue().entrySet()) {
+ byte[] qualifier = entryQ.getKey();
+ deleteP.add(family, qualifier, null);
+ }
+ }
+ }
+
+ transactionState.addRow(new RowKeyFamily(delete.getRow(), getTableName(), deleteP.getFamilyMap()));
+
+ put(deleteP);
+ }
+
+ /**
+ * Transactional version of {@link HTable#put(Put)}
+ *
+ * @param transactionState Identifier of the transaction
+ * @see HTable#put(Put)
+ * @throws IOException
+ */
+ public void put(TransactionState transactionState, Put put) throws IOException, IllegalArgumentException {
+ final long startTimestamp = transactionState.getStartTimestamp();
+// byte[] startTSBytes = Bytes.toBytes(startTimestamp);
+ // create put with correct ts
+ final Put tsput = new Put(put.getRow(), startTimestamp);
+ Map<byte[], List<KeyValue>> kvs = put.getFamilyMap();
+ for (List<KeyValue> kvl : kvs.values()) {
+ for (KeyValue kv : kvl) {
+// int tsOffset = kv.getTimestampOffset();
+// System.arraycopy(startTSBytes, 0, kv.getBuffer(), tsOffset, Bytes.SIZEOF_LONG);
+ tsput.add(new KeyValue(kv.getRow(), kv.getFamily(), kv.getQualifier(), startTimestamp, kv.getValue()));
+ }
+ }
+
+ // should add the table as well
+ transactionState.addRow(new RowKeyFamily(put.getRow(), getTableName(), put.getFamilyMap()));
+
+ put(tsput);
+// super.getConnection().getRegionServerWithRetries(
+// new ServerCallable<Boolean>(super.getConnection(), super.getTableName(), put.getRow()) {
+// public Boolean call() throws IOException {
+// server.put(location.getRegionInfo().getRegionName(), tsput);
+// return true;
+// }
+// });
+ }
+ /**
+ * Transactional version of {@link HTable#getScanner(Scan)}
+ *
+ * @param transactionState Identifier of the transaction
+ * @see HTable#getScanner(Scan)
+ * @throws IOException
+ */
+ public ResultScanner getScanner(TransactionState transactionState, Scan scan) throws IOException {
+ Scan tsscan = new Scan(scan);
+// tsscan.setRetainDeletesInOutput(true);
+// int maxVersions = scan.getMaxVersions();
+ tsscan.setMaxVersions((int) (versionsAvg + CACHE_VERSIONS_OVERHEAD));
+ tsscan.setTimeRange(0, transactionState.getStartTimestamp() + 1);
+ ClientScanner scanner = new ClientScanner(transactionState, tsscan, (int) (versionsAvg + CACHE_VERSIONS_OVERHEAD));
+ scanner.initialize();
+ return scanner;
+ }
+
+ private Result filter(TransactionState state, Result result, long startTimestamp, int localVersions) throws IOException {
+ if (result == null) {
+ return null;
+ }
+ List<KeyValue> kvs = result.list();
+ if (kvs == null) {
+ return result;
+ }
+ Map<ByteArray, Map<ByteArray, Integer>> occurrences = new HashMap<TransactionalTable.ByteArray, Map<ByteArray,Integer>>();
+ Map<ByteArray, Map<ByteArray, Long>> minTimestamp = new HashMap<TransactionalTable.ByteArray, Map<ByteArray,Long>>();
+ List<KeyValue> nonDeletes = new ArrayList<KeyValue>();
+ List<KeyValue> filtered = new ArrayList<KeyValue>();
+ Map<ByteArray, Set<ByteArray>> read = new HashMap<ByteArray, Set<ByteArray>>();
+ DeleteTracker tracker = new DeleteTracker();
+ for (KeyValue kv : kvs) {
+ ByteArray family = new ByteArray(kv.getFamily());
+ ByteArray qualifier = new ByteArray(kv.getQualifier());
+ Set<ByteArray> readQualifiers = read.get(family);
+ if (readQualifiers == null) {
+ readQualifiers = new HashSet<TransactionalTable.ByteArray>();
+ read.put(family, readQualifiers);
+ } else if (readQualifiers.contains(qualifier)) continue;
+// RowKey rk = new RowKey(kv.getRow(), getTableName());
+ if (state.tsoclient.validRead(kv.getTimestamp(), startTimestamp)) {
+ if (!tracker.addDeleted(kv))
+ nonDeletes.add(kv);
+ {
+ // Read valid value
+ readQualifiers.add(qualifier);
+
+// statistics
+// elementsGotten++;
+ Map<ByteArray, Integer> occurrencesCols = occurrences.get(family);
+ Integer times = null;
+ if (occurrencesCols != null) {
+ times = occurrencesCols.get(qualifier);
+ }
+ if (times != null) {
+// elementsRead += times;
+ versionsAvg = times > versionsAvg ? times : alpha * versionsAvg + (1 - alpha) * times;
+// extraVersionsAvg = times > extraVersionsAvg ? times : alpha * extraVersionsAvg + (1 - alpha) * times;
+ } else {
+// elementsRead++;
+ versionsAvg = alpha * versionsAvg + (1 - alpha);
+// extraVersionsAvg = alpha * extraVersionsAvg + (1 - alpha);
+ }
+ }
+ } else {
+ Map<ByteArray, Integer> occurrencesCols = occurrences.get(family);
+ Map<ByteArray, Long> minTimestampCols = minTimestamp.get(family);
+ if (occurrencesCols == null) {
+ occurrencesCols = new HashMap<TransactionalTable.ByteArray, Integer>();
+ minTimestampCols = new HashMap<TransactionalTable.ByteArray, Long>();
+ occurrences.put(family, occurrencesCols);
+ minTimestamp.put(family, minTimestampCols);
+ }
+ Integer times = occurrencesCols.get(qualifier);
+ Long timestamp = minTimestampCols.get(qualifier);
+ if (times == null) {
+ times = 0;
+ timestamp = kv.getTimestamp();
+ }
+ times++;
+ timestamp = Math.min(timestamp, kv.getTimestamp());
+ if (times == localVersions) {
+ // We need to fetch more versions
+ Get get = new Get(kv.getRow());
+ get.addColumn(kv.getFamily(), kv.getQualifier());
+ get.setMaxVersions(localVersions);
+ Result r;
+ GOTRESULT: do {
+ extraGetsPerformed++;
+ get.setTimeRange(0, timestamp);
+ r = this.get(get);
+ List<KeyValue> list = r.list();
+ if (list == null) break;
+ for (KeyValue t : list) {
+ times++;
+ timestamp = Math.min(timestamp, t.getTimestamp());
+// rk = new RowKey(kv.getRow(), getTableName());
+ if (state.tsoclient.validRead(t.getTimestamp(), startTimestamp)) {
+ if (!tracker.addDeleted(t))
+ nonDeletes.add(t);
+ readQualifiers.add(qualifier);
+ elementsGotten++;
+ elementsRead += times;
+ versionsAvg = times > versionsAvg ? times : alpha * versionsAvg + (1 - alpha) * times;
+ extraVersionsAvg = times > extraVersionsAvg ? times : alpha * extraVersionsAvg + (1 - alpha) * times;
+ break GOTRESULT;
+ }
+ }
+ } while (r.size() == localVersions);
+ } else {
+ occurrencesCols.put(qualifier, times);
+ minTimestampCols.put(qualifier, timestamp);
+ }
+ }
+ }
+ for (KeyValue kv : nonDeletes) {
+ if (!tracker.isDeleted(kv)) {
+ filtered.add(kv);
+ }
+ }
+// cacheVersions = (int) versionsAvg;
+ if (filtered.isEmpty()) {
+ return null;
+ }
+ return new Result(filtered);
+ }
+
+ private class DeleteTracker {
+ Map<ByteArray, Long> deletedRows = new HashMap<ByteArray, Long>();
+ Map<ByteArray, Long> deletedFamilies = new HashMap<ByteArray, Long>();
+ Map<ByteArray, Long> deletedColumns = new HashMap<ByteArray, Long>();
+
+ public boolean addDeleted(KeyValue kv) {
+ if (kv.getValue().length == 0) {
+ deletedColumns.put(new ByteArray(Bytes.add(kv.getFamily(), kv.getQualifier())), kv.getTimestamp());
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isDeleted(KeyValue kv) {
+ Long timestamp;
+ timestamp = deletedRows.get(new ByteArray(kv.getRow()));
+ if (timestamp != null && kv.getTimestamp() < timestamp) return true;
+ timestamp = deletedFamilies.get(new ByteArray(kv.getFamily()));
+ if (timestamp != null && kv.getTimestamp() < timestamp) return true;
+ timestamp = deletedColumns.get(new ByteArray(Bytes.add(kv.getFamily(), kv.getQualifier())));
+ if (timestamp != null && kv.getTimestamp() < timestamp) return true;
+ return false;
+ }
+ }
+
+ private class ByteArray {
+ public byte [] array;
+
+ public ByteArray(byte [] array) {
+ this.array = array;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof ByteArray) {
+ ByteArray ba = (ByteArray) obj;
+ return Arrays.equals(array, ba.array);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(array);
+ }
+ }
+
+ protected class ClientScanner extends HTable.ClientScanner {
+ private TransactionState state;
+ private int maxVersions;
+
+ ClientScanner(TransactionState state, Scan scan, int maxVersions) {
+ super(scan);
+ this.state = state;
+ this.maxVersions = maxVersions;
+ }