basic-examples.html (331 lines of code) (raw):
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 1.7 at 2016-04-15
| Rendered using Apache Maven Fluido Skin 1.5
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20160415" />
<meta http-equiv="Content-Language" content="en" />
<title>Apache Omid – Code Examples</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.5.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.5.min.js"></script>
</head>
<body class="topBarEnabled">
<div id="topbar" class="navbar navbar-fixed-top ">
<div class="navbar-inner">
<div class="container" style="width: 100%;"><div class="nav-collapse">
<ul class="nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Home <b class="caret"></b></a>
<ul class="dropdown-menu">
<li> <a href="index.html" title="Overview">Overview</a>
</li>
<li> <a href="license.html" title="License">License</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Download <b class="caret"></b></a>
<ul class="dropdown-menu">
<li> <a href="https://bintray.com/yahoo/maven/omid" title="Download Omid">Download Omid</a>
</li>
<li> <a href="https://bintray.com/yahoo/maven/omid" title="Bintray Repository">Bintray Repository</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">User Guide & API <b class="caret"></b></a>
<ul class="dropdown-menu">
<li> <a href="quickstart.html" title="Quickstart">Quickstart</a>
</li>
<li> <a href="basic-examples.html" title="API and Code Examples">API and Code Examples</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Technical Docs <b class="caret"></b></a>
<ul class="dropdown-menu">
<li> <a href="basic-concepts.html" title="Basic Concepts">Basic Concepts</a>
</li>
<li> <a href="omid-components.html" title="Omid Components">Omid Components</a>
</li>
<li> <a href="basic-algorithm.html" title="Basic Algorithm">Basic Algorithm</a>
</li>
<li> <a href="client-failure-management.html" title="Management of Client Failures">Management of Client Failures</a>
</li>
<li> <a href="http://yahoohadoop.tumblr.com/tagged/HBase" title="Blog Entries">Blog Entries</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contribute <b class="caret"></b></a>
<ul class="dropdown-menu">
<li> <a href="https://git-wip-us.apache.org/repos/asf/incubator-omid.git" title="Source Code">Source Code</a>
</li>
<li> <a href="https://issues.apache.org/jira/browse/Omid" title="JIRA">JIRA</a>
</li>
<li> <a href="mailing-lists.html" title="Mailing Lists">Mailing Lists</a>
</li>
<li> <a href="coding-guide-and-style.html" title="Coding Guide and Style">Coding Guide and Style</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Project Reports <b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="dropdown-submenu">
<a href="project-info.html" title="Project Information">Project Information</a>
<ul class="dropdown-menu">
<li> <a href="dependency-convergence.html" title="Dependency Convergence">Dependency Convergence</a>
</li>
<li> <a href="dependency-info.html" title="Dependency Information">Dependency Information</a>
</li>
<li> <a href="dependency-management.html" title="Dependency Management">Dependency Management</a>
</li>
<li> <a href="distribution-management.html" title="Distribution Management">Distribution Management</a>
</li>
<li> <a href="index.html" title="About">About</a>
</li>
<li> <a href="license.html" title="Licenses">Licenses</a>
</li>
<li> <a href="modules.html" title="Project Modules">Project Modules</a>
</li>
<li> <a href="plugin-management.html" title="Plugin Management">Plugin Management</a>
</li>
<li> <a href="plugins.html" title="Plugins">Plugins</a>
</li>
<li> <a href="team-list.html" title="Team">Team</a>
</li>
<li> <a href="source-repository.html" title="Source Code Management">Source Code Management</a>
</li>
<li> <a href="project-summary.html" title="Summary">Summary</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<form id="search-form" action="https://www.google.com/search" method="get" class="navbar-search pull-right" >
<input value="omid.incubator.apache.org" name="sitesearch" type="hidden"/>
<input class="search-query" name="q" id="query" type="text" />
</form>
<script type="text/javascript" src="https://cse.google.com/brand?form=search-form"></script>
<ul class="nav pull-right"><li>
<a href="https://twitter.com/apacheomid" class="twitter-follow-button" data-show-count="true" data-align="right" data-size="large" data-show-screen-name="true" data-lang="en">Follow apacheomid</a>
<script type="text/javascript">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</li></ul>
</div>
</div>
</div>
</div>
<div class="container">
<div id="banner">
<div class="pull-left">
<a href="./" id="bannerLeft">
<img src="images/omid-logo.png" alt="Omid" width="200"/>
</a>
</div>
<div class="pull-right"> <a href="http://incubator.apache.org/" id="bannerRight">
<img src="http://incubator.apache.org/images/egg-logo2.png" alt="Apache Incubator" width="200"/>
</a>
</div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="projectVersion">Version: 0.8.1.37-SNAPSHOT
</li>
<li id="publishDate" class="pull-right">Last Published: 2016-04-15</li>
</ul>
</div>
<div id="bodyColumn" >
<h1>Code Examples</h1>
<p>This section guides the developer of Omid-based transactional applications over the different steps required to execute multi-row transactions on HBase and the different APIs involved in the process.</p>
<div class="section">
<h2><a name="Transactional_Contexts_and_Operations_with_Omid"></a>Transactional Contexts and Operations with Omid</h2>
<p>Applications requiring transactions will use the interfaces provided by the Omid <i>Transactional Client</i>. These interfaces are provided by the <i>TransactionManager</i> and <i>TTable</i> classes described below.</p>
<p>When starting a transaction, the Omid <i>Transactional Client</i> requests a <i>start timestamp</i> from the <i>TSO</i>. This timestamp marks the beginning of a transactional context, that is, a transaction. From that point on, the client application can perform transactional read and write operations on the data source:</p>
<ul>
<li><b>Read Ops</b>. The client first checks if the cell has a <i>Shadow Cell (SC)</i>. If the cell has a <i>SC</i> and the <i>commit timestamp</i> is lower than the <i>start timestamp</i> of the reading transaction, then the client can “see” the cell, that is, it’s in its snapshot. If there is no <i>SC</i>, the <i>Commit Table (CT)</i> is consulted to find the <i>commit timestamp</i> of the cell. If the <i>commit timestamp</i> does not exist in the <i>CT</i>, then the cell is assumed to below to an aborted transaction.</li>
<li><b>Write Ops</b>. The client directly writes optimistically in the data source any data cells it wishes adding the <i>start timestamp</i> as the version of each data cell. The metadata of each cell written is added also to the so-called <i>write-set</i> of the transaction.</li>
</ul>
<p>To commit a transaction, the client sends the <i>write-set</i> of the transaction to the <i>TSO</i>, which will check for conflicts in the transaction <i>write-set</i> with other transactions executing concurrently:</p>
<ul>
<li><b>Conflicts</b>. The transaction is aborted and the <i>roll-back</i> outcome is returned to the client.</li>
<li><b>No conflicts</b>. The TSO assigns a <i>commit timestamp</i> to the transaction, writes the mapping <i>start timestamp -> commit timestamp</i> to the <i>CT</i> and returns <i>commit</i> as an outcome for the transaction to the client.</li>
</ul>
<p>On receiving the outcome for the transaction, the client:</p>
<ul>
<li><b>For roll-backs</b>, it clears the written cells.</li>
<li><b>For commits</b>, it updates the <i>shadow cells</i> for the cells in the <i>write-set</i> and clears the entry for that transaction in the <i>CT</i>.</li>
</ul>
<p>The following sections show step-by-step the process for creating transactions in client applications with the Omid APIs.</p></div>
<div class="section">
<h2><a name="Obtaining_the_Transaction_Manager"></a>Obtaining the Transaction Manager</h2>
<p>In order to use transactions, a client application needs to create an instance of the <tt>TransactionManager</tt> interface with is part of the Transactional Client described in the architecture. The current Omid version offers an implementation of a transaction manager for HBase. Please, make sure <tt>core-site.xml</tt> and <tt>hbase-site.xml</tt> HBase configuration files are present in the CLASSPATH of your client application.</p>
<p>To create a transaction manager just add the following code to your application:</p>
<div class="source">
<div class="source"><pre class="prettyprint"> ...
TransactionManager tm = HBaseTransactionManager.newInstance();
...
</pre></div></div>
<p>If nothing is specified, the HBase transaction manager instance is created with default configuration settings loaded from the <tt>default-hbase-omid-client-config.yml</tt> file included in the HBase Omid client jar. To change the client default settings, there are two possibilities:</p>
<p>1) Put the specific configuration settings in a file named <tt>hbase-omid-client-config.yml</tt> and include it in the CLASSPATH. The file has the following format:</p>
<div class="source">
<div class="source"><pre class="prettyprint"># HBase related
commitTableName: MY_OWN_OMID_COMMIT_TABLE_NAME
# TSO/ZK connection
omidClientConfiguration: !!com.yahoo.omid.tso.client.OmidClientConfiguration
connectionType: !!com.yahoo.omid.tso.client.OmidClientConfiguration$ConnType ZK
connectionString: "my_zk_cluster_conn_string"
# Instrumentation
metrics: !!com.yahoo.omid.metrics.NullMetricsProvider [ ]
</pre></div></div>
<p>2) Create an instance of the <tt>HBaseOmidClientConfiguration</tt> class in the application code and pass it in the creation of the transaction manager instance:</p>
<div class="source">
<div class="source"><pre class="prettyprint"> ...
HBaseOmidClientConfiguration omidClientConfiguration = new HBaseOmidClientConfiguration();
omidClientConfiguration.setConnectionType(DIRECT);
omidClientConfiguration.setConnectionString("my_tso_server_host:54758");
omidClientConfiguration.setRetryDelayMs(3000);
TransactionManager tm = HBaseTransactionManager.newInstance(omidClientConfiguration);
...
</pre></div></div>
<p>Please, refer to the <a class="externalLink" href="https://github.com/yahoo/omid/blob/master/examples/src/main/java/com/yahoo/omid/examples/ConfigurationExample.java">ConfigurationExample</a> in the source code to experiment with the configuration options.</p></div>
<div class="section">
<h2><a name="Creating_Transactions"></a>Creating Transactions</h2>
<p>Once the <tt>TransactionManager</tt> is created, client applications can use its interface to demarcate transactional boundaries.</p>
<p>In order to create a transaction the <tt>TransactionManager.begin()</tt> method is used:</p>
<div class="source">
<div class="source"><pre class="prettyprint"> ...
Transaction tx = tm.begin();
...
</pre></div></div>
<p>The transaction manager will return an instance of the <tt>Transaction</tt> interface representing the recently created transaction. This instance is necessary to instruct the operations on the data source, in which transactional context they should operate (See next section).</p></div>
<div class="section">
<h2><a name="Executing_Transactional_Operations"></a>Executing Transactional Operations</h2>
<p>In order to perform transaction operations on data, the client application requires to use a wrapper on the HBase’s <tt>HTableInterface</tt> abstraction. The wrapper is called <tt>TTable</tt> and is also part of what is described as Transactional Client in the Omid architecture (See section <a href="./About-Omid.html">About Omid</a>). <tt>TTable</tt> basically offers the same interface as <tt>HTableInterface</tt> enhanced with a parameter representing the transactional context. As was previously described, a <tt>Transaction</tt> instance is obtained on return of <tt>TransactionManager.begin()</tt> method calls.</p>
<div class="source">
<div class="source"><pre class="prettyprint"> ...
TTable txTable = new TTable(conf, "EXAMPLE_TABLE");
...
</pre></div></div>
<p>Once the access point to the data has been created, applications can use it to trigger transactional operations:</p>
<div class="source">
<div class="source"><pre class="prettyprint"> private final byte[] family = Bytes.toBytes("EXAMPLE_CF");
private final byte[] qualifier = Bytes.toBytes("foo");
...
// Retrieve transactionally a specific cell
Get get = new Get(Bytes.toBytes("EXAMPLE_ROW");
get.add(family, qualifier);
Result txGetResult = txTable.get(tx, get);
...
// Add a new cell value inside a transactional context
Put updatedRow = new Put(Bytes.toBytes("EXAMPLE_ROW");
updatedRow.add(family, qualifier, Bytes.toBytes("Another_value"));
txTable.put(tx, updatedRow);
...
</pre></div></div></div>
<div class="section">
<h2><a name="Committing_and_Aborting_Transactions"></a>Committing and Aborting Transactions</h2>
<p>Once the client application has finished reading/writting from/into the datasource, it must decide whether to make the changes visible or to discard them. In order to do this, it must instruct the Omid <tt>TransactionManager</tt> either to <tt>commit()</tt> or to <tt>rollback()</tt> the transactional context where the changes were produced. In case of commit, the TSO server will be notified to perform the SI validation phase. If the validation succeeds the changes will be visible to new transactions started from that point on. Otherwise, it will roll back the changes.</p>
<p>In order to commit the data, the client application should do something like this:</p>
<div class="source">
<div class="source"><pre class="prettyprint"> ...
try {
...
tm.commit(tx);
} catch (RollbackException e) {
// Here the transaction was rolled-back when
// trying to commit due to conflicts with other
// some other concurrent transaction
//
// The client application should do whatever is
// required according to its business logic
...
}
</pre></div></div>
<p>A transaction can also be specifically aborted, for example if something goes wrong when executing the business logic:</p>
<div class="source">
<div class="source"><pre class="prettyprint"> ...
try {
...
if( ! some_business_logic_condition ) {
tm.rollback(tx);
throw AnyApplicationException("Changes aborted due to...");
}
tm.commit(tx);
} catch (RollbackException e) {
...
}
</pre></div></div></div>
<div class="section">
<h2><a name="Complete_Example"></a>Complete Example</h2>
<p>The following example summarizes the steps described above.</p>
<div class="source">
<div class="source"><pre class="prettyprint">import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import com.yahoo.omid.transaction.HBaseTransactionManager;
import com.yahoo.omid.transaction.TTable;
import com.yahoo.omid.transaction.Transaction;
import com.yahoo.omid.transaction.TransactionManager;
public class Example {
public static final byte[] exampleRow = Bytes.toBytes("EXAMPLE_ROW");
public static final byte[] family = Bytes.toBytes("EXAMPLE_CF");
public static final byte[] qualifier = Bytes.toBytes("foo");
public static final byte[] dataValueToAvoid = Bytes.toBytes("valToAvoid");
public static final byte[] dataValue = Bytes.toBytes("val");
public static void main(String[] args) throws Exception {
try (TransactionManager tm = HBaseTransactionManager.newInstance();
TTable txTable = new TTable("EXAMPLE_TABLE")) {
Transaction tx = tm.begin();
System.out.printl("Transaction started");
// Retrieve data transactionally
Get get = new Get(exampleRow);
get.add(family, qualifier);
Result txGetResult = txTable.get(tx, get);
byte[] retrievedValue = txGetResult.getValue(family, qualifier);
// Add a condition in the application logic to show explicit transaction
// aborts just for illustrative purposes
if (Bytes.equals(retrievedValue, dataValueToAvoid)) {
tm.rollback(tx);
throw new RuntimeException("Illegal value found in database!");
}
// Otherwise, add a value in other column and try to commit the transaction
try {
Put putOnRow = new Put(exampleRow);
putOnRow.add(family, qualifier, dataValue);
txTable.put(tx, putOnRow);
tm.commit(tx);
System.out.println("Transaction committed. New value written to example row");
} catch(RollbackException e) {
System.out.println("Transaction aborted due to conflicts. Changes to row aborted");
}
}
}
}
</pre></div></div></div>
<div class="section">
<h2><a name="Additional_Examples"></a>Additional Examples</h2>
<p>The <tt>examples</tt> module contains <a class="externalLink" href="https://github.com/yahoo/omid/tree/master/examples/src/main/java/com/yahoo/omid/examples">complete examples</a> showing the Omid functionality that can be executed in your Omid+HBase environment. Just clone the Omid project, go to the <tt>examples</tt> module and execute <tt>mvn clean package</tt> to create a tar.gz file that includes all the examples. In order to execute each example, just execute the <tt>run.sh</tt> script and follow the instructions.</p></div>
</div>
</div>
<hr/>
<footer>
<div class="container">
<div class="row">
<p >Copyright © 2011–2016
<a href="http://www.apache.org">Apache Software Foundation</a>.
All rights reserved.
</p>
</div>
<p id="poweredBy" class="pull-right">
<a href="http://maven.apache.org/" title="Maven" class="builtBy">
<img class="builtBy" alt="Maven" src="http://maven.apache.org/images/logos/maven-feather.png" />
</a>
</p>
</div>
</footer>
</body>
</html>