Tuesday, March 9, 2021

Java: Checking if HBase Master is reachable from hbase-client

As of HBase 2.1 methods like HBaseAdmin.available() are deprecated. How do we go about checking if the HBase connection is valid?

It turns out the hbase-client will continually retry the connection transparently. 

So this means without changing the retry you might wait indefinitely to get an exception from HBase telling you if (and why) your connection failed.

Here is a snippet that you can incorporate into your existing Java code. Note that this code will not run as-is without being placed into a Java class.

// This code is compatible with HBase 2.1+
// hbase-client, and hbase-common are required dependencies for this code
// imports...
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Admin; // hbase-common
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
// Create an HBase configuration object, this object subclasses Properties
Configuration hconf = HBaseConfiguration.create();
hconf.addResource("hbase-site.xml");
hconf.addResource("core-site.xml");
hconf.set("hbase.client.retries.number", Integer.toString(HBASE_CLIENT_RETRIES));
hconf.set("zookeeper.session.timeout", Integer.toString(HBASE_ZK_TIMEOUT));
hconf.set("zookeeper.recovery.retry", Integer.toString(HBASE_ZK_RETRIES));
// Create our connection, an exception will be thrown here if HBase cannot connect
Connection connection = ConnectionFactory.createConnection(hconf);
// To verify the master is truly reachable, we'll use the `HBaseAdmin` class via `getAdmin()`
// to contact the hbase master.
Admin admin = connection.getAdmin();
ClusterMetrics metrics = admin.getClusterMetrics();
ServerName master = metrics.getMasterName();
// print the hostname of the current HBase Master
System.out.println(String.format("HBase Master: %s", master.getHostname()));