1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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;
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
75
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;
84 private int operationTimeout;
85
86 @VisibleForTesting
87 protected AsyncProcess ap;
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
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
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
152
153
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
166 while (undealtMutationCount.get() != 0
167 && currentWriteBufferSize.get() > writeBufferSize) {
168 backgroundFlushCommits(false);
169 }
170 }
171
172
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
184
185 backgroundFlushCommits(true);
186 this.pool.shutdown();
187 boolean terminated;
188 int loopCnt = 0;
189 do {
190
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
211
212 backgroundFlushCommits(true);
213 }
214
215
216
217
218
219
220
221
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
263
264
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
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
295
296
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
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 }