View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
4    * agreements. See the NOTICE file distributed with this work for additional information regarding
5    * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
6    * "License"); you may not use this file except in compliance with the License. You may obtain a
7    * copy of the License at
8    *
9    *  http://www.apache.org/licenses/LICENSE-2.0
10   *
11   *  Unless required by applicable law or agreed to in writing, software distributed under the
12   * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13   * express or implied. See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.hadoop.hbase.client;
17  
18  import com.google.common.annotations.VisibleForTesting;
19  import java.io.Closeable;
20  import org.apache.commons.logging.Log;
21  import org.apache.commons.logging.LogFactory;
22  import org.apache.hadoop.conf.Configuration;
23  import org.apache.hadoop.hbase.TableName;
24  import org.apache.hadoop.hbase.classification.InterfaceAudience;
25  import org.apache.hadoop.hbase.classification.InterfaceStability;
26  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
27  
28  import java.io.IOException;
29  import java.io.InterruptedIOException;
30  import java.util.Arrays;
31  import java.util.Iterator;
32  import java.util.List;
33  import java.util.NoSuchElementException;
34  import java.util.concurrent.ConcurrentLinkedQueue;
35  import java.util.concurrent.ExecutorService;
36  import java.util.concurrent.TimeUnit;
37  import java.util.concurrent.atomic.AtomicInteger;
38  import java.util.concurrent.atomic.AtomicLong;
39  
40  /**
41   * <p>
42   * Used to communicate with a single HBase table similar to {@link HTable}
43   * but meant for batched, potentially asynchronous puts. Obtain an instance from
44   * a {@link Connection} and call {@link #close()} afterwards.
45   * </p>
46   *
47   * <p>
48   * While this can be used accross threads, great care should be used when doing so.
49   * Errors are global to the buffered mutator and the Exceptions can be thrown on any
50   * thread that causes the flush for requests.
51   * </p>
52   *
53   * @see ConnectionFactory
54   * @see Connection
55   * @since 1.0.0
56   */
57  @InterfaceAudience.Private
58  @InterfaceStability.Evolving
59  public class BufferedMutatorImpl implements BufferedMutator {
60  
61    private static final Log LOG = LogFactory.getLog(BufferedMutatorImpl.class);
62  
63    private final ExceptionListener listener;
64  
65    protected ClusterConnection connection; // non-final so can be overridden in test
66    private final TableName tableName;
67    private volatile Configuration conf;
68    @VisibleForTesting
69    final ConcurrentLinkedQueue<Mutation> writeAsyncBuffer = new ConcurrentLinkedQueue<Mutation>();
70    @VisibleForTesting
71    AtomicLong currentWriteBufferSize = new AtomicLong(0);
72  
73    /**
74     * Count the size of {@link BufferedMutatorImpl#writeAsyncBuffer}.
75     * The {@link ConcurrentLinkedQueue#size()} is NOT a constant-time operation.
76     */
77    @VisibleForTesting
78    AtomicInteger undealtMutationCount = new AtomicInteger(0);
79    private long writeBufferSize;
80    private final int maxKeyValueSize;
81    private boolean closed = false;
82    private final ExecutorService pool;
83    private int writeRpcTimeout; // needed to pass in through AsyncProcess constructor
84    private int operationTimeout;
85  
86    @VisibleForTesting
87    protected AsyncProcess ap; // non-final so can be overridden in test
88  
89    BufferedMutatorImpl(ClusterConnection conn, RpcRetryingCallerFactory rpcCallerFactory,
90        RpcControllerFactory rpcFactory, BufferedMutatorParams params) {
91      if (conn == null || conn.isClosed()) {
92        throw new IllegalArgumentException("Connection is null or closed.");
93      }
94  
95      this.tableName = params.getTableName();
96      this.connection = conn;
97      this.conf = connection.getConfiguration();
98      this.pool = params.getPool();
99      this.listener = params.getListener();
100 
101     ConnectionConfiguration connConf = conn.getConnectionConfiguration();
102     if (connConf == null) {
103       // Slow: parse conf in ConnectionConfiguration constructor
104       connConf = new ConnectionConfiguration(conf);
105     }
106     this.writeBufferSize = params.getWriteBufferSize() != BufferedMutatorParams.UNSET ?
107         params.getWriteBufferSize() : connConf.getWriteBufferSize();
108     this.maxKeyValueSize = params.getMaxKeyValueSize() != BufferedMutatorParams.UNSET ?
109         params.getMaxKeyValueSize() : connConf.getMaxKeyValueSize();
110 
111     this.writeRpcTimeout = connConf.getWriteRpcTimeout();
112     this.operationTimeout = connConf.getOperationTimeout();
113     // puts need to track errors globally due to how the APIs currently work.
114     ap = new AsyncProcess(connection, conf, pool, rpcCallerFactory, true, rpcFactory, writeRpcTimeout);
115   }
116 
117   @Override
118   public TableName getName() {
119     return tableName;
120   }
121 
122   @Override
123   public Configuration getConfiguration() {
124     return conf;
125   }
126 
127   @Override
128   public void mutate(Mutation m) throws InterruptedIOException,
129       RetriesExhaustedWithDetailsException {
130     mutate(Arrays.asList(m));
131   }
132 
133   @Override
134   public void mutate(List<? extends Mutation> ms) throws InterruptedIOException,
135       RetriesExhaustedWithDetailsException {
136 
137     if (closed) {
138       throw new IllegalStateException("Cannot put when the BufferedMutator is closed.");
139     }
140 
141     long toAddSize = 0;
142     int toAddCount = 0;
143     for (Mutation m : ms) {
144       if (m instanceof Put) {
145         validatePut((Put) m);
146       }
147       toAddSize += m.heapSize();
148       ++toAddCount;
149     }
150 
151     // This behavior is highly non-intuitive... it does not protect us against
152     // 94-incompatible behavior, which is a timing issue because hasError, the below code
153     // and setter of hasError are not synchronized. Perhaps it should be removed.
154     if (ap.hasError()) {
155       currentWriteBufferSize.addAndGet(toAddSize);
156       writeAsyncBuffer.addAll(ms);
157       undealtMutationCount.addAndGet(toAddCount);
158       backgroundFlushCommits(true);
159     } else {
160       currentWriteBufferSize.addAndGet(toAddSize);
161       writeAsyncBuffer.addAll(ms);
162       undealtMutationCount.addAndGet(toAddCount);
163     }
164 
165     // Now try and queue what needs to be queued.
166     while (undealtMutationCount.get() != 0
167         && currentWriteBufferSize.get() > writeBufferSize) {
168       backgroundFlushCommits(false);
169     }
170   }
171 
172   // validate for well-formedness
173   public void validatePut(final Put put) throws IllegalArgumentException {
174     HTable.validatePut(put, maxKeyValueSize);
175   }
176 
177   @Override
178   public synchronized void close() throws IOException {
179     try {
180       if (this.closed) {
181         return;
182       }
183       // As we can have an operation in progress even if the buffer is empty, we call
184       // backgroundFlushCommits at least one time.
185       backgroundFlushCommits(true);
186       this.pool.shutdown();
187       boolean terminated;
188       int loopCnt = 0;
189       do {
190         // wait until the pool has terminated
191         terminated = this.pool.awaitTermination(60, TimeUnit.SECONDS);
192         loopCnt += 1;
193         if (loopCnt >= 10) {
194           LOG.warn("close() failed to terminate pool after 10 minutes. Abandoning pool.");
195           break;
196         }
197       } while (!terminated);
198 
199     } catch (InterruptedException e) {
200       LOG.warn("waitForTermination interrupted");
201 
202     } finally {
203       this.closed = true;
204     }
205   }
206 
207   @Override
208   public synchronized void flush() throws InterruptedIOException,
209       RetriesExhaustedWithDetailsException {
210     // As we can have an operation in progress even if the buffer is empty, we call
211     // backgroundFlushCommits at least one time.
212     backgroundFlushCommits(true);
213   }
214 
215   /**
216    * Send the operations in the buffer to the servers. Does not wait for the server's answer. If
217    * the is an error (max retried reach from a previous flush or bad operation), it tries to send
218    * all operations in the buffer and sends an exception.
219    *
220    * @param synchronous - if true, sends all the writes and wait for all of them to finish before
221    *        returning.
222    */
223   private void backgroundFlushCommits(boolean synchronous) throws
224       InterruptedIOException,
225       RetriesExhaustedWithDetailsException {
226     if (!synchronous && writeAsyncBuffer.isEmpty()) {
227       return;
228     }
229 
230     if (!synchronous) {
231       try (QueueRowAccess taker = createQueueRowAccess()){
232         ap.submit(tableName, taker, true, null, false);
233         if (ap.hasError()) {
234           LOG.debug(tableName + ": One or more of the operations have failed -"
235               + " waiting for all operation in progress to finish (successfully or not)");
236         }
237       }
238     }
239     if (synchronous || ap.hasError()) {
240       while (true) {
241         try (QueueRowAccess taker = createQueueRowAccess()){
242           if (taker.isEmpty()) {
243             break;
244           }
245           ap.submit(tableName, taker, true, null, false);
246         }
247       }
248 
249       RetriesExhaustedWithDetailsException error =
250           ap.waitForAllPreviousOpsAndReset(null, tableName.getNameAsString());
251       if (error != null) {
252         if (listener == null) {
253           throw error;
254         } else {
255           this.listener.onException(error, this);
256         }
257       }
258     }
259   }
260 
261   /**
262    * This is used for legacy purposes in {@link HTable#setWriteBufferSize(long)} only. This ought
263    * not be called for production uses.
264    * @deprecated Going away when we drop public support for {@link HTableInterface}.
265    */
266   @Deprecated
267   public void setWriteBufferSize(long writeBufferSize) throws RetriesExhaustedWithDetailsException,
268       InterruptedIOException {
269     this.writeBufferSize = writeBufferSize;
270     if (currentWriteBufferSize.get() > writeBufferSize) {
271       flush();
272     }
273   }
274 
275   /**
276    * {@inheritDoc}
277    */
278   @Override
279   public long getWriteBufferSize() {
280     return this.writeBufferSize;
281   }
282 
283   public void setRpcTimeout(int writeRpcTimeout) {
284     this.writeRpcTimeout = writeRpcTimeout;
285     this.ap.setRpcTimeout(writeRpcTimeout);
286   }
287 
288   public void setOperationTimeout(int operationTimeout) {
289     this.operationTimeout = operationTimeout;
290     this.ap.setOperationTimeout(operationTimeout);
291   }
292 
293   /**
294    * This is used for legacy purposes in {@link HTable#getWriteBuffer()} only. This should not beÓ
295    * called from production uses.
296    * @deprecated Going away when we drop public support for {@link HTableInterface}.
297 Ó   */
298   @Deprecated
299   public List<Row> getWriteBuffer() {
300     return Arrays.asList(writeAsyncBuffer.toArray(new Row[0]));
301   }
302 
303   @VisibleForTesting
304   QueueRowAccess createQueueRowAccess() {
305     return new QueueRowAccess();
306   }
307 
308   @VisibleForTesting
309   class QueueRowAccess implements RowAccess<Row>, Closeable {
310     private int remainder = undealtMutationCount.getAndSet(0);
311     private Mutation last = null;
312 
313     @Override
314     public Iterator<Row> iterator() {
315       return new Iterator<Row>() {
316         private int countDown = remainder;
317         @Override
318         public boolean hasNext() {
319           return countDown > 0;
320         }
321         @Override
322         public Row next() {
323           restoreLastMutation();
324           if (!hasNext()) {
325             throw new NoSuchElementException();
326           }
327           last = writeAsyncBuffer.poll();
328           if (last == null) {
329             throw new NoSuchElementException();
330           }
331           currentWriteBufferSize.addAndGet(-last.heapSize());
332           --countDown;
333           return last;
334         }
335         @Override
336         public void remove() {
337           if (last == null) {
338             throw new IllegalStateException();
339           }
340           --remainder;
341           last = null;
342         }
343       };
344     }
345 
346     private void restoreLastMutation() {
347       // restore the last mutation since it isn't submitted
348       if (last != null) {
349         writeAsyncBuffer.add(last);
350         currentWriteBufferSize.addAndGet(last.heapSize());
351         last = null;
352       }
353     }
354 
355     @Override
356     public int size() {
357       return remainder;
358     }
359 
360     @Override
361     public boolean isEmpty() {
362       return remainder <= 0;
363     }
364     @Override
365     public void close() {
366       restoreLastMutation();
367       if (remainder > 0) {
368         undealtMutationCount.addAndGet(remainder);
369         remainder = 0;
370       }
371     }
372   }
373 }