1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.replication.regionserver;
20
21 import java.io.EOFException;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.concurrent.BlockingQueue;
26 import java.util.concurrent.LinkedBlockingQueue;
27 import java.util.concurrent.PriorityBlockingQueue;
28 import java.util.concurrent.TimeUnit;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.hadoop.conf.Configuration;
33 import org.apache.hadoop.fs.FileSystem;
34 import org.apache.hadoop.fs.Path;
35 import org.apache.hadoop.hbase.Cell;
36 import org.apache.hadoop.hbase.CellUtil;
37 import org.apache.hadoop.hbase.classification.InterfaceAudience;
38 import org.apache.hadoop.hbase.classification.InterfaceStability;
39 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.BulkLoadDescriptor;
40 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
41 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
42 import org.apache.hadoop.hbase.replication.ReplicationQueueInfo;
43 import org.apache.hadoop.hbase.replication.WALEntryFilter;
44 import org.apache.hadoop.hbase.replication.regionserver.WALEntryStream.WALEntryStreamRuntimeException;
45 import org.apache.hadoop.hbase.util.Pair;
46 import org.apache.hadoop.hbase.util.Threads;
47 import org.apache.hadoop.hbase.wal.WAL.Entry;
48
49
50
51
52
53 @InterfaceAudience.Private
54 @InterfaceStability.Evolving
55 public class ReplicationSourceWALReaderThread extends Thread {
56 private static final Log LOG = LogFactory.getLog(ReplicationSourceWALReaderThread.class);
57
58 private PriorityBlockingQueue<Path> logQueue;
59 private FileSystem fs;
60 private Configuration conf;
61 private BlockingQueue<WALEntryBatch> entryBatchQueue;
62
63 private long replicationBatchSizeCapacity;
64
65 private int replicationBatchCountCapacity;
66
67 private long lastReadPosition;
68 private Path lastReadPath;
69 private WALEntryFilter filter;
70 private long sleepForRetries;
71
72 private boolean isReaderRunning = true;
73 private ReplicationQueueInfo replicationQueueInfo;
74 private int maxRetriesMultiplier;
75 private MetricsSource metrics;
76
77
78
79
80
81
82
83
84
85
86
87
88
89 public ReplicationSourceWALReaderThread(ReplicationSourceManager manager,
90 ReplicationQueueInfo replicationQueueInfo, PriorityBlockingQueue<Path> logQueue,
91 long startPosition,
92 FileSystem fs, Configuration conf, WALEntryFilter filter, MetricsSource metrics) {
93 this.replicationQueueInfo = replicationQueueInfo;
94 this.logQueue = logQueue;
95 this.lastReadPath = logQueue.peek();
96 this.lastReadPosition = startPosition;
97 this.fs = fs;
98 this.conf = conf;
99 this.filter = filter;
100 this.replicationBatchSizeCapacity =
101 this.conf.getLong("replication.source.size.capacity", 1024 * 1024 * 64);
102 this.replicationBatchCountCapacity = this.conf.getInt("replication.source.nb.capacity", 25000);
103
104
105 int batchCount = conf.getInt("replication.source.nb.batches", 1);
106 this.sleepForRetries =
107 this.conf.getLong("replication.source.sleepforretries", 1000);
108 this.maxRetriesMultiplier =
109 this.conf.getInt("replication.source.maxretriesmultiplier", 300);
110 this.metrics = metrics;
111 this.entryBatchQueue = new LinkedBlockingQueue<>(batchCount);
112 LOG.info("peerClusterZnode=" + replicationQueueInfo.getPeerClusterZnode()
113 + ", ReplicationSourceWALReaderThread : " + replicationQueueInfo.getPeerId()
114 + " inited, replicationBatchSizeCapacity=" + replicationBatchSizeCapacity
115 + ", replicationBatchCountCapacity=" + replicationBatchCountCapacity
116 + ", replicationBatchQueueCapacity=" + batchCount);
117 }
118
119 @Override
120 public void run() {
121 int sleepMultiplier = 1;
122 while (isReaderRunning()) {
123 try (WALEntryStream entryStream =
124 new WALEntryStream(logQueue, fs, conf, lastReadPosition, metrics)) {
125 while (isReaderRunning()) {
126 WALEntryBatch batch = new WALEntryBatch(replicationBatchCountCapacity);
127 boolean hasNext;
128 while ((hasNext = entryStream.hasNext()) == true) {
129 Entry entry = entryStream.next();
130 entry = filterEntry(entry);
131 if (entry != null) {
132 WALEdit edit = entry.getEdit();
133 if (edit != null && !edit.isEmpty()) {
134 long entrySize = getEntrySize(entry);
135 batch.addEntry(entry);
136 updateBatchStats(batch, entry, entryStream.getPosition(), entrySize);
137
138 if (batch.getHeapSize() >= replicationBatchSizeCapacity
139 || batch.getNbEntries() >= replicationBatchCountCapacity) {
140 break;
141 }
142 }
143 }
144 }
145
146 updateBatch(entryStream, batch, hasNext);
147 if (isShippable(batch)) {
148 sleepMultiplier = 1;
149 entryBatchQueue.put(batch);
150 if (!batch.hasMoreEntries()) {
151
152 setReaderRunning(false);
153 }
154 } else {
155 Thread.sleep(sleepForRetries);
156 }
157 resetStream(entryStream);
158 }
159 } catch (IOException | WALEntryStreamRuntimeException e) {
160 if (sleepMultiplier < maxRetriesMultiplier) {
161 LOG.debug("Failed to read stream of replication entries: " + e);
162 sleepMultiplier++;
163 } else {
164 LOG.error("Failed to read stream of replication entries", e);
165 handleEofException(e);
166 }
167 Threads.sleep(sleepForRetries * sleepMultiplier);
168 } catch (InterruptedException e) {
169 LOG.trace("Interrupted while sleeping between WAL reads");
170 Thread.currentThread().interrupt();
171 }
172 }
173 }
174
175 private void updateBatch(WALEntryStream entryStream, WALEntryBatch batch, boolean moreData) {
176 logMessage(batch);
177 batch.updatePosition(entryStream);
178 batch.setMoreEntries(!replicationQueueInfo.isQueueRecovered() || moreData);
179 }
180
181 private void logMessage(WALEntryBatch batch) {
182 if (LOG.isTraceEnabled()) {
183 if (batch.isEmpty()) {
184 LOG.trace("Didn't read any new entries from WAL");
185 } else {
186 LOG.trace(String.format("Read %s WAL entries eligible for replication",
187 batch.getNbEntries()));
188 }
189 }
190 }
191
192 private boolean isShippable(WALEntryBatch batch) {
193 return !batch.isEmpty() || checkIfWALRolled(batch) || !batch.hasMoreEntries();
194 }
195
196 private boolean checkIfWALRolled(WALEntryBatch batch) {
197 return lastReadPath == null && batch.lastWalPath != null
198 || lastReadPath != null && !lastReadPath.equals(batch.lastWalPath);
199 }
200
201 private void resetStream(WALEntryStream stream) throws IOException {
202 lastReadPosition = stream.getPosition();
203 lastReadPath = stream.getCurrentPath();
204 stream.reset();
205 }
206
207
208
209
210 private void handleEofException(Exception e) {
211 if (e.getCause() instanceof EOFException && logQueue.size() > 1
212 && conf.getBoolean("replication.source.eof.autorecovery", false)) {
213 try {
214 if (fs.getFileStatus(logQueue.peek()).getLen() == 0) {
215 LOG.warn("Forcing removal of 0 length log in queue: " + logQueue.peek());
216 lastReadPath = logQueue.remove();
217 lastReadPosition = 0;
218 }
219 } catch (IOException ioe) {
220 LOG.warn("Couldn't get file length information about log " + logQueue.peek());
221 }
222 }
223 }
224
225 public Path getCurrentPath() {
226 return logQueue.peek();
227 }
228
229 private Entry filterEntry(Entry entry) {
230 Entry filtered = filter.filter(entry);
231 if (entry != null && filtered == null) {
232 metrics.incrLogEditsFiltered();
233 }
234 return filtered;
235 }
236
237
238
239
240
241
242
243 public WALEntryBatch take() throws InterruptedException {
244 return entryBatchQueue.take();
245 }
246
247 public WALEntryBatch poll(long timeout) throws InterruptedException {
248 return entryBatchQueue.poll(timeout, TimeUnit.MILLISECONDS);
249 }
250
251 private long getEntrySize(Entry entry) {
252 WALEdit edit = entry.getEdit();
253 return edit.heapSize() + calculateTotalSizeOfStoreFiles(edit);
254 }
255
256 private void updateBatchStats(WALEntryBatch batch, Entry entry, long entryPosition, long entrySize) {
257 WALEdit edit = entry.getEdit();
258 if (edit != null && !edit.isEmpty()) {
259 batch.incrementHeapSize(entrySize);
260 Pair<Integer, Integer> nbRowsAndHFiles = countDistinctRowKeysAndHFiles(edit);
261 batch.incrementNbRowKeys(nbRowsAndHFiles.getFirst());
262 batch.incrementNbHFiles(nbRowsAndHFiles.getSecond());
263 }
264 batch.lastWalPosition = entryPosition;
265 }
266
267
268
269
270
271
272
273 private Pair<Integer, Integer> countDistinctRowKeysAndHFiles(WALEdit edit) {
274 List<Cell> cells = edit.getCells();
275 int distinctRowKeys = 1;
276 int totalHFileEntries = 0;
277 Cell lastCell = cells.get(0);
278
279 int totalCells = edit.size();
280 for (int i = 0; i < totalCells; i++) {
281
282 if (CellUtil.matchingQualifier(cells.get(i), WALEdit.BULK_LOAD)) {
283 try {
284 BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cells.get(i));
285 List<StoreDescriptor> stores = bld.getStoresList();
286 int totalStores = stores.size();
287 for (int j = 0; j < totalStores; j++) {
288 totalHFileEntries += stores.get(j).getStoreFileList().size();
289 }
290 } catch (IOException e) {
291 LOG.error("Failed to deserialize bulk load entry from wal edit. "
292 + "Then its hfiles count will not be added into metric.");
293 }
294 }
295
296 if (!CellUtil.matchingRow(cells.get(i), lastCell)) {
297 distinctRowKeys++;
298 }
299 lastCell = cells.get(i);
300 }
301
302 Pair<Integer, Integer> result = new Pair<>(distinctRowKeys, totalHFileEntries);
303 return result;
304 }
305
306
307
308
309
310
311 private int calculateTotalSizeOfStoreFiles(WALEdit edit) {
312 List<Cell> cells = edit.getCells();
313 int totalStoreFilesSize = 0;
314
315 int totalCells = edit.size();
316 for (int i = 0; i < totalCells; i++) {
317 if (CellUtil.matchingQualifier(cells.get(i), WALEdit.BULK_LOAD)) {
318 try {
319 BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cells.get(i));
320 List<StoreDescriptor> stores = bld.getStoresList();
321 int totalStores = stores.size();
322 for (int j = 0; j < totalStores; j++) {
323 totalStoreFilesSize += stores.get(j).getStoreFileSizeBytes();
324 }
325 } catch (IOException e) {
326 LOG.error("Failed to deserialize bulk load entry from wal edit. "
327 + "Size of HFiles part of cell will not be considered in replication "
328 + "request size calculation.",
329 e);
330 }
331 }
332 }
333 return totalStoreFilesSize;
334 }
335
336
337
338
339 public boolean isReaderRunning() {
340 return isReaderRunning && !isInterrupted();
341 }
342
343
344
345
346 public void setReaderRunning(boolean readerRunning) {
347 this.isReaderRunning = readerRunning;
348 }
349
350 public long getLastReadPosition() {
351 return this.lastReadPosition;
352 }
353
354
355
356
357
358 static class WALEntryBatch {
359 private List<Entry> walEntries;
360
361 private Path lastWalPath;
362
363 private long lastWalPosition = 0;
364
365 private int nbRowKeys = 0;
366
367 private int nbHFiles = 0;
368
369 private long heapSize = 0;
370
371 private boolean moreEntries = true;
372
373
374
375
376 private WALEntryBatch(int maxNbEntries) {
377 this.walEntries = new ArrayList<>(maxNbEntries);
378 }
379
380 public void addEntry(Entry entry) {
381 walEntries.add(entry);
382 }
383
384
385
386
387 public List<Entry> getWalEntries() {
388 return walEntries;
389 }
390
391
392
393
394 public Path getLastWalPath() {
395 return lastWalPath;
396 }
397
398
399
400
401 public long getLastWalPosition() {
402 return lastWalPosition;
403 }
404
405 public int getNbEntries() {
406 return walEntries.size();
407 }
408
409
410
411
412 public int getNbRowKeys() {
413 return nbRowKeys;
414 }
415
416
417
418
419 public int getNbHFiles() {
420 return nbHFiles;
421 }
422
423
424
425
426 public int getNbOperations() {
427 return getNbRowKeys() + getNbHFiles();
428 }
429
430
431
432
433 public long getHeapSize() {
434 return heapSize;
435 }
436
437 private void incrementNbRowKeys(int increment) {
438 nbRowKeys += increment;
439 }
440
441 private void incrementNbHFiles(int increment) {
442 nbHFiles += increment;
443 }
444
445 private void incrementHeapSize(long increment) {
446 heapSize += increment;
447 }
448
449 public boolean isEmpty() {
450 return walEntries.isEmpty();
451 }
452
453 public void updatePosition(WALEntryStream entryStream) {
454 lastWalPath = entryStream.getCurrentPath();
455 lastWalPosition = entryStream.getPosition();
456 }
457
458 public boolean hasMoreEntries() {
459 return moreEntries;
460 }
461
462 public void setMoreEntries(boolean moreEntries) {
463 this.moreEntries = moreEntries;
464 }
465 }
466 }