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.yetus.audience.InterfaceAudience;
041import org.slf4j.Logger;
042import org.slf4j.LoggerFactory;
043
044import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
045
046/**
047 * A simple example shows how to use asynchronous client.
048 */
049@InterfaceAudience.Private
050public class AsyncClientExample extends Configured implements Tool {
051
052  private static final Logger LOG = LoggerFactory.getLogger(AsyncClientExample.class);
053
054  /**
055   * The size for thread pool.
056   */
057  private static final int THREAD_POOL_SIZE = 16;
058
059  /**
060   * The default number of operations.
061   */
062  private static final int DEFAULT_NUM_OPS = 100;
063
064  /**
065   * The name of the column family. d for default.
066   */
067  private static final byte[] FAMILY = Bytes.toBytes("d");
068
069  /**
070   * For the example we're just using one qualifier.
071   */
072  private static final byte[] QUAL = Bytes.toBytes("test");
073
074  private final AtomicReference<CompletableFuture<AsyncConnection>> future =
075    new AtomicReference<>();
076
077  private CompletableFuture<AsyncConnection> getConn() {
078    CompletableFuture<AsyncConnection> f = future.get();
079    if (f != null) {
080      return f;
081    }
082    for (;;) {
083      if (future.compareAndSet(null, new CompletableFuture<>())) {
084        CompletableFuture<AsyncConnection> toComplete = future.get();
085        addListener(ConnectionFactory.createAsyncConnection(getConf()), (conn, error) -> {
086          if (error != null) {
087            toComplete.completeExceptionally(error);
088            // we need to reset the future holder so we will get a chance to recreate an async
089            // connection at next try.
090            future.set(null);
091            return;
092          }
093          toComplete.complete(conn);
094        });
095        return toComplete;
096      } else {
097        f = future.get();
098        if (f != null) {
099          return f;
100        }
101      }
102    }
103  }
104
105  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NONNULL_PARAM_VIOLATION",
106      justification = "it is valid to pass NULL to CompletableFuture#completedFuture")
107  private CompletableFuture<Void> closeConn() {
108    CompletableFuture<AsyncConnection> f = future.get();
109    if (f == null) {
110      return CompletableFuture.completedFuture(null);
111    }
112    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
113    addListener(f, (conn, error) -> {
114      if (error == null) {
115        IOUtils.closeQuietly(conn, e -> LOG.warn("failed to close conn", e));
116      }
117      closeFuture.complete(null);
118    });
119    return closeFuture;
120  }
121
122  private byte[] getKey(int i) {
123    return Bytes.toBytes(String.format("%08x", i));
124  }
125
126  @Override
127  public int run(String[] args) throws Exception {
128    if (args.length < 1 || args.length > 2) {
129      System.out.println("Usage: " + this.getClass().getName() + " tableName [num_operations]");
130      return -1;
131    }
132    TableName tableName = TableName.valueOf(args[0]);
133    int numOps = args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_NUM_OPS;
134    ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE,
135      new ThreadFactoryBuilder().setNameFormat("AsyncClientExample-pool-%d").setDaemon(true)
136        .setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build());
137    // We use AsyncTable here so we need to provide a separated thread pool. RawAsyncTable does not
138    // need a thread pool and may have a better performance if you use it correctly as it can save
139    // some context switches. But if you use RawAsyncTable incorrectly, you may have a very bad
140    // impact on performance so use it with caution.
141    CountDownLatch latch = new CountDownLatch(numOps);
142    IntStream.range(0, numOps).forEach(i -> {
143      CompletableFuture<AsyncConnection> future = getConn();
144      addListener(future, (conn, error) -> {
145        if (error != null) {
146          LOG.warn("failed to get async connection for " + i, error);
147          latch.countDown();
148          return;
149        }
150        AsyncTable<?> table = conn.getTable(tableName, threadPool);
151        addListener(table.put(new Put(getKey(i)).addColumn(FAMILY, QUAL, Bytes.toBytes(i))),
152          (putResp, putErr) -> {
153            if (putErr != null) {
154              LOG.warn("put failed for " + i, putErr);
155              latch.countDown();
156              return;
157            }
158            LOG.info("put for " + i + " succeeded, try getting");
159            addListener(table.get(new Get(getKey(i))), (result, getErr) -> {
160              if (getErr != null) {
161                LOG.warn("get failed for " + i);
162                latch.countDown();
163                return;
164              }
165              if (result.isEmpty()) {
166                LOG.warn("get failed for " + i + ", server returns empty result");
167              } else if (!result.containsColumn(FAMILY, QUAL)) {
168                LOG.warn("get failed for " + i + ", the result does not contain "
169                  + Bytes.toString(FAMILY) + ":" + Bytes.toString(QUAL));
170              } else {
171                int v = Bytes.toInt(result.getValue(FAMILY, QUAL));
172                if (v != i) {
173                  LOG.warn("get failed for " + i + ", the value of " + Bytes.toString(FAMILY) + ":"
174                    + Bytes.toString(QUAL) + " is " + v + ", exected " + i);
175                } else {
176                  LOG.info("get for " + i + " succeeded");
177                }
178              }
179              latch.countDown();
180            });
181          });
182      });
183    });
184    latch.await();
185    closeConn().get();
186    return 0;
187  }
188
189  public static void main(String[] args) throws Exception {
190    ToolRunner.run(new AsyncClientExample(), args);
191  }
192}