001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client.example;
019
020import static org.apache.hadoop.hbase.util.FutureUtils.addListener;
021
022import java.util.concurrent.CompletableFuture;
023import java.util.concurrent.CountDownLatch;
024import java.util.concurrent.ExecutorService;
025import java.util.concurrent.Executors;
026import java.util.concurrent.atomic.AtomicReference;
027import java.util.stream.IntStream;
028import org.apache.commons.io.IOUtils;
029import org.apache.hadoop.conf.Configured;
030import org.apache.hadoop.hbase.TableName;
031import org.apache.hadoop.hbase.client.AsyncConnection;
032import org.apache.hadoop.hbase.client.AsyncTable;
033import org.apache.hadoop.hbase.client.ConnectionFactory;
034import org.apache.hadoop.hbase.client.Get;
035import org.apache.hadoop.hbase.client.Put;
036import org.apache.hadoop.hbase.util.Bytes;
037import org.apache.hadoop.hbase.util.Threads;
038import org.apache.hadoop.util.Tool;
039import org.apache.hadoop.util.ToolRunner;
040import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
041import org.apache.yetus.audience.InterfaceAudience;
042import org.slf4j.Logger;
043import org.slf4j.LoggerFactory;
044
045/**
046 * A simple example shows how to use asynchronous client.
047 */
048@InterfaceAudience.Private
049public class AsyncClientExample extends Configured implements Tool {
050
051  private static final Logger LOG = LoggerFactory.getLogger(AsyncClientExample.class);
052
053  /**
054   * The size for thread pool.
055   */
056  private static final int THREAD_POOL_SIZE = 16;
057
058  /**
059   * The default number of operations.
060   */
061  private static final int DEFAULT_NUM_OPS = 100;
062
063  /**
064   * The name of the column family. d for default.
065   */
066  private static final byte[] FAMILY = Bytes.toBytes("d");
067
068  /**
069   * For the example we're just using one qualifier.
070   */
071  private static final byte[] QUAL = Bytes.toBytes("test");
072
073  private final AtomicReference<CompletableFuture<AsyncConnection>> future =
074      new AtomicReference<>();
075
076  private CompletableFuture<AsyncConnection> getConn() {
077    CompletableFuture<AsyncConnection> f = future.get();
078    if (f != null) {
079      return f;
080    }
081    for (;;) {
082      if (future.compareAndSet(null, new CompletableFuture<>())) {
083        CompletableFuture<AsyncConnection> toComplete = future.get();
084        addListener(ConnectionFactory.createAsyncConnection(getConf()),(conn, error) -> {
085          if (error != null) {
086            toComplete.completeExceptionally(error);
087            // we need to reset the future holder so we will get a chance to recreate an async
088            // connection at next try.
089            future.set(null);
090            return;
091          }
092          toComplete.complete(conn);
093        });
094        return toComplete;
095      } else {
096        f = future.get();
097        if (f != null) {
098          return f;
099        }
100      }
101    }
102  }
103
104  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NONNULL_PARAM_VIOLATION",
105      justification = "it is valid to pass NULL to CompletableFuture#completedFuture")
106  private CompletableFuture<Void> closeConn() {
107    CompletableFuture<AsyncConnection> f = future.get();
108    if (f == null) {
109      return CompletableFuture.completedFuture(null);
110    }
111    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
112    addListener(f, (conn, error) -> {
113      if (error == null) {
114        IOUtils.closeQuietly(conn, e -> LOG.warn("failed to close conn", e));
115      }
116      closeFuture.complete(null);
117    });
118    return closeFuture;
119  }
120
121  private byte[] getKey(int i) {
122    return Bytes.toBytes(String.format("%08x", i));
123  }
124
125  @Override
126  public int run(String[] args) throws Exception {
127    if (args.length < 1 || args.length > 2) {
128      System.out.println("Usage: " + this.getClass().getName() + " tableName [num_operations]");
129      return -1;
130    }
131    TableName tableName = TableName.valueOf(args[0]);
132    int numOps = args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_NUM_OPS;
133    ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE,
134      new ThreadFactoryBuilder().setNameFormat("AsyncClientExample-pool-%d").setDaemon(true)
135        .setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build());
136    // We use AsyncTable here so we need to provide a separated thread pool. RawAsyncTable does not
137    // need a thread pool and may have a better performance if you use it correctly as it can save
138    // some context switches. But if you use RawAsyncTable incorrectly, you may have a very bad
139    // impact on performance so use it with caution.
140    CountDownLatch latch = new CountDownLatch(numOps);
141    IntStream.range(0, numOps).forEach(i -> {
142      CompletableFuture<AsyncConnection> future = getConn();
143      addListener(future, (conn, error) -> {
144        if (error != null) {
145          LOG.warn("failed to get async connection for " + i, error);
146          latch.countDown();
147          return;
148        }
149        AsyncTable<?> table = conn.getTable(tableName, threadPool);
150        addListener(table.put(new Put(getKey(i)).addColumn(FAMILY, QUAL, Bytes.toBytes(i))),
151          (putResp, putErr) -> {
152            if (putErr != null) {
153              LOG.warn("put failed for " + i, putErr);
154              latch.countDown();
155              return;
156            }
157            LOG.info("put for " + i + " succeeded, try getting");
158            addListener(table.get(new Get(getKey(i))), (result, getErr) -> {
159              if (getErr != null) {
160                LOG.warn("get failed for " + i);
161                latch.countDown();
162                return;
163              }
164              if (result.isEmpty()) {
165                LOG.warn("get failed for " + i + ", server returns empty result");
166              } else if (!result.containsColumn(FAMILY, QUAL)) {
167                LOG.warn("get failed for " + i + ", the result does not contain " +
168                  Bytes.toString(FAMILY) + ":" + Bytes.toString(QUAL));
169              } else {
170                int v = Bytes.toInt(result.getValue(FAMILY, QUAL));
171                if (v != i) {
172                  LOG.warn("get failed for " + i + ", the value of " + Bytes.toString(FAMILY) +
173                    ":" + Bytes.toString(QUAL) + " is " + v + ", exected " + i);
174                } else {
175                  LOG.info("get for " + i + " succeeded");
176                }
177              }
178              latch.countDown();
179            });
180          });
181      });
182    });
183    latch.await();
184    closeConn().get();
185    return 0;
186  }
187
188  public static void main(String[] args) throws Exception {
189    ToolRunner.run(new AsyncClientExample(), args);
190  }
191}