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.FileNotFoundException;
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.UUID;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.PriorityBlockingQueue;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.atomic.AtomicLong;
35
36 import org.apache.commons.lang.StringUtils;
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.apache.hadoop.conf.Configuration;
40 import org.apache.hadoop.fs.FileStatus;
41 import org.apache.hadoop.fs.FileSystem;
42 import org.apache.hadoop.fs.Path;
43 import org.apache.hadoop.hbase.Cell;
44 import org.apache.hadoop.hbase.CellUtil;
45 import org.apache.hadoop.hbase.HBaseConfiguration;
46 import org.apache.hadoop.hbase.HConstants;
47 import org.apache.hadoop.hbase.Stoppable;
48 import org.apache.hadoop.hbase.TableName;
49 import org.apache.hadoop.hbase.classification.InterfaceAudience;
50 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.BulkLoadDescriptor;
51 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
52 import org.apache.hadoop.hbase.regionserver.RSRpcServices;
53 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
54 import org.apache.hadoop.hbase.replication.ChainWALEntryFilter;
55 import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
56 import org.apache.hadoop.hbase.replication.ReplicationException;
57 import org.apache.hadoop.hbase.replication.ReplicationPeers;
58 import org.apache.hadoop.hbase.replication.ReplicationQueueInfo;
59 import org.apache.hadoop.hbase.replication.ReplicationQueues;
60 import org.apache.hadoop.hbase.replication.SystemTableWALEntryFilter;
61 import org.apache.hadoop.hbase.replication.WALEntryFilter;
62 import org.apache.hadoop.hbase.util.Bytes;
63 import org.apache.hadoop.hbase.util.CancelableProgressable;
64 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
65 import org.apache.hadoop.hbase.util.FSUtils;
66 import org.apache.hadoop.hbase.util.LeaseNotRecoveredException;
67 import org.apache.hadoop.hbase.util.Threads;
68 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
69 import org.apache.hadoop.hbase.wal.WAL;
70 import org.apache.hadoop.hbase.wal.WALKey;
71
72 import com.google.common.collect.Lists;
73 import com.google.common.util.concurrent.ListenableFuture;
74 import com.google.common.util.concurrent.Service;
75
76
77
78
79
80
81
82
83
84
85
86
87
88 @InterfaceAudience.Private
89 public class ReplicationSource extends Thread
90 implements ReplicationSourceInterface {
91
92 private static final Log LOG = LogFactory.getLog(ReplicationSource.class);
93
94
95 private Map<String, PriorityBlockingQueue<Path>> queues =
96 new HashMap<String, PriorityBlockingQueue<Path>>();
97
98 private int queueSizePerGroup;
99 private ReplicationQueues replicationQueues;
100 private ReplicationPeers replicationPeers;
101
102 private Configuration conf;
103 private ReplicationQueueInfo replicationQueueInfo;
104
105 private String peerId;
106
107 private ReplicationSourceManager manager;
108
109 private Stoppable stopper;
110
111 private long sleepForRetries;
112
113 private long replicationQueueSizeCapacity;
114
115 private int replicationQueueNbCapacity;
116 private FileSystem fs;
117
118 private UUID clusterId;
119
120 private UUID peerClusterId;
121
122 private AtomicLong totalReplicatedEdits = new AtomicLong(0);
123
124 private AtomicLong totalReplicatedOperations = new AtomicLong(0);
125
126 private String peerClusterZnode;
127
128 private int maxRetriesMultiplier;
129
130 private volatile boolean sourceRunning = false;
131
132 private MetricsSource metrics;
133
134 private int logQueueWarnThreshold;
135
136 private ReplicationEndpoint replicationEndpoint;
137
138 private WALEntryFilter walEntryFilter;
139
140 private ReplicationThrottler throttler;
141 private ConcurrentHashMap<String, ReplicationSourceWorkerThread> workerThreads =
142 new ConcurrentHashMap<String, ReplicationSourceWorkerThread>();
143
144 public enum WorkerState {
145 RUNNING,
146 STOPPED,
147 FINISHED
148 }
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163 @Override
164 public void init(final Configuration conf, final FileSystem fs,
165 final ReplicationSourceManager manager, final ReplicationQueues replicationQueues,
166 final ReplicationPeers replicationPeers, final Stoppable stopper,
167 final String peerClusterZnode, final UUID clusterId, ReplicationEndpoint replicationEndpoint,
168 final MetricsSource metrics)
169 throws IOException {
170 this.stopper = stopper;
171 this.conf = HBaseConfiguration.create(conf);
172 decorateConf();
173 this.replicationQueueSizeCapacity =
174 this.conf.getLong("replication.source.size.capacity", 1024*1024*64);
175 this.replicationQueueNbCapacity =
176 this.conf.getInt("replication.source.nb.capacity", 25000);
177 this.sleepForRetries =
178 this.conf.getLong("replication.source.sleepforretries", 1000);
179 this.maxRetriesMultiplier =
180 this.conf.getInt("replication.source.maxretriesmultiplier", 300);
181 this.queueSizePerGroup = this.conf.getInt("hbase.regionserver.maxlogs", 32);
182 long bandwidth = this.conf.getLong("replication.source.per.peer.node.bandwidth", 0);
183 this.throttler = new ReplicationThrottler((double)bandwidth/10.0);
184 this.replicationQueues = replicationQueues;
185 this.replicationPeers = replicationPeers;
186 this.manager = manager;
187 this.fs = fs;
188 this.metrics = metrics;
189 this.clusterId = clusterId;
190
191 this.peerClusterZnode = peerClusterZnode;
192 this.replicationQueueInfo = new ReplicationQueueInfo(peerClusterZnode);
193
194 this.peerId = this.replicationQueueInfo.getPeerId();
195 this.logQueueWarnThreshold = this.conf.getInt("replication.source.log.queue.warn", 2);
196 this.replicationEndpoint = replicationEndpoint;
197 }
198
199 private void decorateConf() {
200 String replicationCodec = this.conf.get(HConstants.REPLICATION_CODEC_CONF_KEY);
201 if (StringUtils.isNotEmpty(replicationCodec)) {
202 this.conf.set(HConstants.RPC_CODEC_CONF_KEY, replicationCodec);
203 }
204 }
205
206 @Override
207 public void enqueueLog(Path log) {
208 String logPrefix = DefaultWALProvider.getWALPrefixFromWALName(log.getName());
209 PriorityBlockingQueue<Path> queue = queues.get(logPrefix);
210 if (queue == null) {
211 queue = new PriorityBlockingQueue<Path>(queueSizePerGroup, new LogsComparator());
212 queues.put(logPrefix, queue);
213 if (this.sourceRunning) {
214
215
216
217 final ReplicationSourceWorkerThread worker =
218 new ReplicationSourceWorkerThread(logPrefix, queue, replicationQueueInfo, this);
219 ReplicationSourceWorkerThread extant = workerThreads.putIfAbsent(logPrefix, worker);
220 if (extant != null) {
221 LOG.debug("Someone has beat us to start a worker thread for wal group " + logPrefix);
222 } else {
223 LOG.debug("Starting up worker for wal group " + logPrefix);
224 worker.startup();
225 }
226 }
227 }
228 queue.put(log);
229 this.metrics.incrSizeOfLogQueue();
230
231 int queueSize = queue.size();
232 if (queueSize > this.logQueueWarnThreshold) {
233 LOG.warn("WAL group " + logPrefix + " queue size: " + queueSize
234 + " exceeds value of replication.source.log.queue.warn: " + logQueueWarnThreshold);
235 }
236 }
237
238 @Override
239 public void addHFileRefs(TableName tableName, byte[] family, List<String> files)
240 throws ReplicationException {
241 String peerId = peerClusterZnode;
242 if (peerId.contains("-")) {
243
244
245 peerId = peerClusterZnode.split("-")[0];
246 }
247 Map<TableName, List<String>> tableCFMap = replicationPeers.getPeer(peerId).getTableCFs();
248 if (tableCFMap != null) {
249 List<String> tableCfs = tableCFMap.get(tableName);
250 if (tableCFMap.containsKey(tableName)
251 && (tableCfs == null || tableCfs.contains(Bytes.toString(family)))) {
252 this.replicationQueues.addHFileRefs(peerId, files);
253 metrics.incrSizeOfHFileRefsQueue(files.size());
254 } else {
255 LOG.debug("HFiles will not be replicated belonging to the table " + tableName + " family "
256 + Bytes.toString(family) + " to peer id " + peerId);
257 }
258 } else {
259
260
261 this.replicationQueues.addHFileRefs(peerId, files);
262 metrics.incrSizeOfHFileRefsQueue(files.size());
263 }
264 }
265
266 private void uninitialize() {
267 LOG.debug("Source exiting " + this.peerId);
268 metrics.clear();
269 if (replicationEndpoint.state() == Service.State.STARTING
270 || replicationEndpoint.state() == Service.State.RUNNING) {
271 replicationEndpoint.stopAndWait();
272 }
273 }
274
275 @Override
276 public void run() {
277
278 this.sourceRunning = true;
279 try {
280
281 Service.State state = replicationEndpoint.start().get();
282 if (state != Service.State.RUNNING) {
283 LOG.warn("ReplicationEndpoint was not started. Exiting");
284 uninitialize();
285 return;
286 }
287 } catch (Exception ex) {
288 LOG.warn("Error starting ReplicationEndpoint, exiting", ex);
289 throw new RuntimeException(ex);
290 }
291
292
293 ArrayList<WALEntryFilter> filters = Lists.newArrayList(
294 (WALEntryFilter)new SystemTableWALEntryFilter());
295 WALEntryFilter filterFromEndpoint = this.replicationEndpoint.getWALEntryfilter();
296 if (filterFromEndpoint != null) {
297 filters.add(filterFromEndpoint);
298 }
299 this.walEntryFilter = new ChainWALEntryFilter(filters);
300
301 int sleepMultiplier = 1;
302
303 while (this.isSourceActive() && this.peerClusterId == null) {
304 this.peerClusterId = replicationEndpoint.getPeerUUID();
305 if (this.isSourceActive() && this.peerClusterId == null) {
306 if (sleepForRetries("Cannot contact the peer's zk ensemble", sleepMultiplier)) {
307 sleepMultiplier++;
308 }
309 }
310 }
311
312 if (!this.isSourceActive()) {
313 return;
314 }
315
316
317
318 if (clusterId.equals(peerClusterId) && !replicationEndpoint.canReplicateToSameCluster()) {
319 this.terminate("ClusterId " + clusterId + " is replicating to itself: peerClusterId "
320 + peerClusterId + " which is not allowed by ReplicationEndpoint:"
321 + replicationEndpoint.getClass().getName(), null, false);
322 this.manager.closeQueue(this);
323 return;
324 }
325 LOG.info("Replicating " + clusterId + " -> " + peerClusterId);
326
327 for (Map.Entry<String, PriorityBlockingQueue<Path>> entry : queues.entrySet()) {
328 String walGroupId = entry.getKey();
329 PriorityBlockingQueue<Path> queue = entry.getValue();
330 final ReplicationSourceWorkerThread worker =
331 new ReplicationSourceWorkerThread(walGroupId, queue, replicationQueueInfo, this);
332 ReplicationSourceWorkerThread extant = workerThreads.putIfAbsent(walGroupId, worker);
333 if (extant != null) {
334 LOG.debug("Someone has beat us to start a worker thread for wal group " + walGroupId);
335 } else {
336 LOG.debug("Starting up worker for wal group " + walGroupId);
337 worker.startup();
338 }
339 }
340 }
341
342
343
344
345
346
347
348 protected boolean sleepForRetries(String msg, int sleepMultiplier) {
349 try {
350 if (LOG.isTraceEnabled()) {
351 LOG.trace(msg + ", sleeping " + sleepForRetries + " times " + sleepMultiplier);
352 }
353 Thread.sleep(this.sleepForRetries * sleepMultiplier);
354 } catch (InterruptedException e) {
355 LOG.debug("Interrupted while sleeping between retries");
356 Thread.currentThread().interrupt();
357 }
358 return sleepMultiplier < maxRetriesMultiplier;
359 }
360
361
362
363
364
365
366 protected boolean isPeerEnabled() {
367 return this.replicationPeers.getStatusOfPeer(this.peerId);
368 }
369
370 @Override
371 public void startup() {
372 String n = Thread.currentThread().getName();
373 Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
374 @Override
375 public void uncaughtException(final Thread t, final Throwable e) {
376 LOG.error("Unexpected exception in ReplicationSource", e);
377 }
378 };
379 Threads
380 .setDaemonThreadRunning(this, n + ".replicationSource," + this.peerClusterZnode, handler);
381 }
382
383 @Override
384 public void terminate(String reason) {
385 terminate(reason, null);
386 }
387
388 @Override
389 public void terminate(String reason, Exception cause) {
390 terminate(reason, cause, true);
391 }
392
393 public void terminate(String reason, Exception cause, boolean join) {
394 if (cause == null) {
395 LOG.info("Closing source "
396 + this.peerClusterZnode + " because: " + reason);
397
398 } else {
399 LOG.error("Closing source " + this.peerClusterZnode
400 + " because an error occurred: " + reason, cause);
401 }
402 this.sourceRunning = false;
403 Collection<ReplicationSourceWorkerThread> workers = workerThreads.values();
404 for (ReplicationSourceWorkerThread worker : workers) {
405 worker.setWorkerState(WorkerState.STOPPED);
406 worker.interrupt();
407 }
408 ListenableFuture<Service.State> future = null;
409 if (this.replicationEndpoint != null) {
410 future = this.replicationEndpoint.stop();
411 }
412 if (join) {
413 for (ReplicationSourceWorkerThread worker : workers) {
414 Threads.shutdown(worker, this.sleepForRetries);
415 LOG.info("ReplicationSourceWorker " + worker.getName() + " terminated");
416 }
417 if (future != null) {
418 try {
419 future.get(sleepForRetries * maxRetriesMultiplier, TimeUnit.MILLISECONDS);
420 } catch (Exception e) {
421 LOG.warn("Got exception while waiting for endpoint to shutdown for replication source :"
422 + this.peerClusterZnode,
423 e);
424 }
425 }
426 }
427 }
428
429 @Override
430 public String getPeerClusterZnode() {
431 return this.peerClusterZnode;
432 }
433
434 @Override
435 public String getPeerClusterId() {
436 return this.peerId;
437 }
438
439 @Override
440 public Path getCurrentPath() {
441
442 for (ReplicationSourceWorkerThread worker : workerThreads.values()) {
443 if (worker.getCurrentPath() != null) return worker.getCurrentPath();
444 }
445 return null;
446 }
447
448 private boolean isSourceActive() {
449 return !this.stopper.isStopped() && this.sourceRunning;
450 }
451
452
453
454
455 public static class LogsComparator implements Comparator<Path> {
456
457 @Override
458 public int compare(Path o1, Path o2) {
459 return Long.compare(getTS(o1), getTS(o2));
460 }
461
462
463
464
465
466
467
468 private static long getTS(Path p) {
469 int tsIndex = p.getName().lastIndexOf('.') + 1;
470 return Long.parseLong(p.getName().substring(tsIndex));
471 }
472 }
473
474 @Override
475 public String getStats() {
476 StringBuilder sb = new StringBuilder();
477 sb.append("Total replicated edits: ").append(totalReplicatedEdits)
478 .append(", current progress: \n");
479 for (Map.Entry<String, ReplicationSourceWorkerThread> entry : workerThreads.entrySet()) {
480 String walGroupId = entry.getKey();
481 ReplicationSourceWorkerThread worker = entry.getValue();
482 long position = worker.getCurrentPosition();
483 Path currentPath = worker.getCurrentPath();
484 sb.append("walGroup [").append(walGroupId).append("]: ");
485 if (currentPath != null) {
486 sb.append("currently replicating from: ").append(currentPath).append(" at position: ")
487 .append(position).append("\n");
488 } else {
489 sb.append("no replication ongoing, waiting for new log");
490 }
491 }
492 return sb.toString();
493 }
494
495 @Override
496 public MetricsSource getSourceMetrics() {
497 return this.metrics;
498 }
499
500 public class ReplicationSourceWorkerThread extends Thread {
501 private ReplicationSource source;
502 private String walGroupId;
503 private PriorityBlockingQueue<Path> queue;
504 private ReplicationQueueInfo replicationQueueInfo;
505
506 private WAL.Reader reader;
507
508 private long lastLoggedPosition = -1;
509
510 private volatile Path currentPath;
511
512 private ReplicationWALReaderManager repLogReader;
513
514 private int currentNbOperations = 0;
515
516 private int currentSize = 0;
517
518 private WorkerState state;
519
520 private long currentNbHFiles = 0;
521
522
523 public ReplicationSourceWorkerThread(String walGroupId, PriorityBlockingQueue<Path> queue,
524 ReplicationQueueInfo replicationQueueInfo, ReplicationSource source) {
525 this.walGroupId = walGroupId;
526 this.queue = queue;
527 this.replicationQueueInfo = replicationQueueInfo;
528 this.repLogReader = new ReplicationWALReaderManager(fs, conf);
529 this.source = source;
530 }
531
532 @Override
533 public void run() {
534 setWorkerState(WorkerState.RUNNING);
535
536
537 if (this.replicationQueueInfo.isQueueRecovered()) {
538 try {
539 this.repLogReader.setPosition(replicationQueues.getLogPosition(peerClusterZnode,
540 this.queue.peek().getName()));
541 if (LOG.isTraceEnabled()) {
542 LOG.trace("Recovered queue started with log " + this.queue.peek() + " at position "
543 + this.repLogReader.getPosition());
544 }
545 } catch (ReplicationException e) {
546 terminate("Couldn't get the position of this recovered queue " + peerClusterZnode, e);
547 }
548 }
549 int sleepMultiplier = 1;
550
551 while (isWorkerActive()) {
552
553 if (!isPeerEnabled()) {
554 if (sleepForRetries("Replication is disabled", sleepMultiplier)) {
555 sleepMultiplier++;
556 }
557 continue;
558 }
559 Path oldPath = getCurrentPath();
560
561
562
563 boolean hasCurrentPath = getNextPath();
564 if (getCurrentPath() != null && oldPath == null) {
565 sleepMultiplier = 1;
566 }
567 if (!hasCurrentPath) {
568 if (sleepForRetries("No log to process", sleepMultiplier)) {
569 sleepMultiplier++;
570 }
571 continue;
572 }
573 boolean currentWALisBeingWrittenTo = false;
574
575
576
577
578
579
580
581
582 if (!this.replicationQueueInfo.isQueueRecovered() && queue.size() == 0) {
583 currentWALisBeingWrittenTo = true;
584 }
585
586 if (!openReader(sleepMultiplier)) {
587
588 sleepMultiplier = 1;
589 continue;
590 }
591
592
593 if (this.reader == null) {
594 if (sleepForRetries("Unable to open a reader", sleepMultiplier)) {
595 sleepMultiplier++;
596 }
597 continue;
598 }
599
600 boolean gotIOE = false;
601 currentNbOperations = 0;
602 currentNbHFiles = 0;
603 List<WAL.Entry> entries = new ArrayList<WAL.Entry>(1);
604 currentSize = 0;
605 try {
606 if (readAllEntriesToReplicateOrNextFile(currentWALisBeingWrittenTo, entries)) {
607 continue;
608 }
609 } catch (IOException ioe) {
610 LOG.warn(peerClusterZnode + " Got: ", ioe);
611 gotIOE = true;
612 if (ioe.getCause() instanceof EOFException) {
613
614 boolean considerDumping = false;
615 if (this.replicationQueueInfo.isQueueRecovered()) {
616 try {
617 FileStatus stat = fs.getFileStatus(this.currentPath);
618 if (stat.getLen() == 0) {
619 LOG.warn(peerClusterZnode + " Got EOF and the file was empty");
620 }
621 considerDumping = true;
622 } catch (IOException e) {
623 LOG.warn(peerClusterZnode + " Got while getting file size: ", e);
624 }
625 }
626
627 if (considerDumping &&
628 sleepMultiplier == maxRetriesMultiplier &&
629 processEndOfFile(false)) {
630 continue;
631 }
632 }
633 } finally {
634 try {
635 this.reader = null;
636 this.repLogReader.closeReader();
637 } catch (IOException e) {
638 gotIOE = true;
639 LOG.warn("Unable to finalize the tailing of a file", e);
640 }
641 }
642
643
644
645
646 if (isWorkerActive() && (gotIOE || entries.isEmpty())) {
647 if (this.lastLoggedPosition != this.repLogReader.getPosition()) {
648 manager.logPositionAndCleanOldLogs(this.currentPath,
649 peerClusterZnode, this.repLogReader.getPosition(),
650 this.replicationQueueInfo.isQueueRecovered(), currentWALisBeingWrittenTo);
651 this.lastLoggedPosition = this.repLogReader.getPosition();
652 }
653
654 if (!gotIOE) {
655 sleepMultiplier = 1;
656
657
658 metrics.setAgeOfLastShippedOp(EnvironmentEdgeManager.currentTime(), walGroupId);
659 }
660 if (sleepForRetries("Nothing to replicate", sleepMultiplier)) {
661 sleepMultiplier++;
662 }
663 continue;
664 }
665 sleepMultiplier = 1;
666 shipEdits(currentWALisBeingWrittenTo, entries);
667 }
668 if (replicationQueueInfo.isQueueRecovered() && getWorkerState() == WorkerState.FINISHED) {
669
670 synchronized (workerThreads) {
671 Threads.sleep(100);
672 boolean allOtherTaskDone = true;
673 for (ReplicationSourceWorkerThread worker : workerThreads.values()) {
674 if (!worker.equals(this) && worker.getWorkerState() != WorkerState.FINISHED) {
675 allOtherTaskDone = false;
676 break;
677 }
678 }
679 if (allOtherTaskDone) {
680 manager.closeRecoveredQueue(this.source);
681 LOG.info("Finished recovering queue " + peerClusterZnode
682 + " with the following stats: " + getStats());
683 }
684 }
685 }
686
687 if (state != WorkerState.FINISHED) {
688 setWorkerState(WorkerState.STOPPED);
689 }
690 }
691
692
693
694
695
696
697
698
699
700 protected boolean readAllEntriesToReplicateOrNextFile(boolean currentWALisBeingWrittenTo,
701 List<WAL.Entry> entries) throws IOException {
702 long seenEntries = 0;
703 if (LOG.isTraceEnabled()) {
704 LOG.trace("Seeking in " + this.currentPath + " at position "
705 + this.repLogReader.getPosition());
706 }
707 this.repLogReader.seek();
708 long positionBeforeRead = this.repLogReader.getPosition();
709 WAL.Entry entry = this.repLogReader.readNextAndSetPosition();
710 while (entry != null) {
711 metrics.incrLogEditsRead();
712 seenEntries++;
713
714
715 if (replicationEndpoint.canReplicateToSameCluster()
716 || !entry.getKey().getClusterIds().contains(peerClusterId)) {
717
718 entry = walEntryFilter.filter(entry);
719 WALEdit edit = null;
720 WALKey logKey = null;
721 if (entry != null) {
722 edit = entry.getEdit();
723 logKey = entry.getKey();
724 }
725
726 if (edit != null && edit.size() != 0) {
727
728 logKey.addClusterId(clusterId);
729 currentNbOperations += countDistinctRowKeys(edit);
730 entries.add(entry);
731 currentSize += entry.getEdit().heapSize();
732 currentSize += calculateTotalSizeOfStoreFiles(edit);
733 } else {
734 metrics.incrLogEditsFiltered();
735 }
736 }
737
738
739 if (currentSize >= replicationQueueSizeCapacity
740 || entries.size() >= replicationQueueNbCapacity) {
741 break;
742 }
743 try {
744 entry = this.repLogReader.readNextAndSetPosition();
745 } catch (IOException ie) {
746 LOG.debug("Break on IOE: " + ie.getMessage());
747 break;
748 }
749 }
750 metrics.incrLogReadInBytes(this.repLogReader.getPosition() - positionBeforeRead);
751 if (currentWALisBeingWrittenTo) {
752 return false;
753 }
754
755
756 return seenEntries == 0 && processEndOfFile(false);
757 }
758
759
760
761
762
763
764 private int calculateTotalSizeOfStoreFiles(WALEdit edit) {
765 List<Cell> cells = edit.getCells();
766 int totalStoreFilesSize = 0;
767
768 int totalCells = edit.size();
769 for (int i = 0; i < totalCells; i++) {
770 if (CellUtil.matchingQualifier(cells.get(i), WALEdit.BULK_LOAD)) {
771 try {
772 BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cells.get(i));
773 List<StoreDescriptor> stores = bld.getStoresList();
774 int totalStores = stores.size();
775 for (int j = 0; j < totalStores; j++) {
776 totalStoreFilesSize += stores.get(j).getStoreFileSizeBytes();
777 }
778 } catch (IOException e) {
779 LOG.error("Failed to deserialize bulk load entry from wal edit. "
780 + "Size of HFiles part of cell will not be considered in replication "
781 + "request size calculation.", e);
782 }
783 }
784 }
785 return totalStoreFilesSize;
786 }
787
788 private void cleanUpHFileRefs(WALEdit edit) throws IOException {
789 String peerId = peerClusterZnode;
790 if (peerId.contains("-")) {
791
792
793 peerId = peerClusterZnode.split("-")[0];
794 }
795 List<Cell> cells = edit.getCells();
796 int totalCells = cells.size();
797 for (int i = 0; i < totalCells; i++) {
798 Cell cell = cells.get(i);
799 if (CellUtil.matchingQualifier(cell, WALEdit.BULK_LOAD)) {
800 BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cell);
801 List<StoreDescriptor> stores = bld.getStoresList();
802 int totalStores = stores.size();
803 for (int j = 0; j < totalStores; j++) {
804 List<String> storeFileList = stores.get(j).getStoreFileList();
805 manager.cleanUpHFileRefs(peerId, storeFileList);
806 metrics.decrSizeOfHFileRefsQueue(storeFileList.size());
807 }
808 }
809 }
810 }
811
812
813
814
815
816 protected boolean getNextPath() {
817 try {
818 if (this.currentPath == null) {
819 this.currentPath = queue.poll(sleepForRetries, TimeUnit.MILLISECONDS);
820 metrics.decrSizeOfLogQueue();
821 if (this.currentPath != null) {
822
823 manager.cleanOldLogs(this.currentPath.getName(), peerClusterZnode,
824 this.replicationQueueInfo.isQueueRecovered());
825 if (LOG.isTraceEnabled()) {
826 LOG.trace("New log: " + this.currentPath);
827 }
828 }
829 }
830 } catch (InterruptedException e) {
831 LOG.warn("Interrupted while reading edits", e);
832 }
833 return this.currentPath != null;
834 }
835
836
837
838
839
840
841
842 protected boolean openReader(int sleepMultiplier) {
843 try {
844 try {
845 if (LOG.isTraceEnabled()) {
846 LOG.trace("Opening log " + this.currentPath);
847 }
848 this.reader = repLogReader.openReader(this.currentPath);
849 } catch (FileNotFoundException fnfe) {
850 if (this.replicationQueueInfo.isQueueRecovered()) {
851
852
853
854 List<String> deadRegionServers = this.replicationQueueInfo.getDeadRegionServers();
855 LOG.info("NB dead servers : " + deadRegionServers.size());
856 final Path walDir = FSUtils.getWALRootDir(conf);
857 for (String curDeadServerName : deadRegionServers) {
858 final Path deadRsDirectory = new Path(walDir,
859 DefaultWALProvider.getWALDirectoryName(curDeadServerName));
860 Path[] locs = new Path[] {
861 new Path(deadRsDirectory, currentPath.getName()),
862 new Path(deadRsDirectory.suffix(DefaultWALProvider.SPLITTING_EXT),
863 currentPath.getName()),
864 };
865 for (Path possibleLogLocation : locs) {
866 LOG.info("Possible location " + possibleLogLocation.toUri().toString());
867 if (manager.getFs().exists(possibleLogLocation)) {
868
869 LOG.info("Log " + this.currentPath + " still exists at " +
870 possibleLogLocation);
871
872
873 if (stopper instanceof ReplicationSyncUp.DummyServer) {
874
875 this.currentPath = possibleLogLocation;
876 this.openReader(sleepMultiplier);
877 }
878 return true;
879 }
880 }
881 }
882
883
884 if (stopper instanceof ReplicationSyncUp.DummyServer) {
885
886
887 FileStatus[] rss = fs.listStatus(manager.getLogDir());
888 for (FileStatus rs : rss) {
889 Path p = rs.getPath();
890 FileStatus[] logs = fs.listStatus(p);
891 for (FileStatus log : logs) {
892 p = new Path(p, log.getPath().getName());
893 if (p.getName().equals(currentPath.getName())) {
894 currentPath = p;
895 LOG.info("Log " + currentPath.getName() + " found at " + currentPath);
896
897 this.openReader(sleepMultiplier);
898 return true;
899 }
900 }
901 }
902 }
903
904
905
906
907
908
909
910
911 throw new IOException("File from recovered queue is " +
912 "nowhere to be found", fnfe);
913 } else {
914
915 Path archivedLogLocation =
916 new Path(manager.getOldLogDir(), currentPath.getName());
917 if (manager.getFs().exists(archivedLogLocation)) {
918 currentPath = archivedLogLocation;
919 LOG.info("Log " + this.currentPath + " was moved to " +
920 archivedLogLocation);
921
922 this.openReader(sleepMultiplier);
923
924 }
925
926 }
927 }
928 } catch (LeaseNotRecoveredException lnre) {
929
930 LOG.warn(peerClusterZnode + " Try to recover the WAL lease " + currentPath, lnre);
931 recoverLease(conf, currentPath);
932 this.reader = null;
933 } catch (IOException ioe) {
934 if (ioe instanceof EOFException && isCurrentLogEmpty()) return true;
935 LOG.warn(peerClusterZnode + " Got: ", ioe);
936 this.reader = null;
937 if (ioe.getCause() instanceof NullPointerException) {
938
939
940
941 LOG.warn("Got NPE opening reader, will retry.");
942 } else if (sleepMultiplier >= maxRetriesMultiplier
943 && conf.getBoolean("replication.source.eof.autorecovery", false)) {
944
945
946 LOG.warn("Waited too long for this file, considering dumping");
947 return !processEndOfFile(true);
948 }
949 }
950 return true;
951 }
952
953 private void recoverLease(final Configuration conf, final Path path) {
954 try {
955 final FileSystem dfs = FSUtils.getCurrentFileSystem(conf);
956 FSUtils fsUtils = FSUtils.getInstance(dfs, conf);
957 fsUtils.recoverFileLease(dfs, path, conf, new CancelableProgressable() {
958 @Override
959 public boolean progress() {
960 LOG.debug("recover WAL lease: " + path);
961 return isWorkerActive();
962 }
963 });
964 } catch (IOException e) {
965 LOG.warn("unable to recover lease for WAL: " + path, e);
966 }
967 }
968
969
970
971
972
973
974
975 private boolean isCurrentLogEmpty() {
976 return (this.repLogReader.getPosition() == 0 &&
977 !this.replicationQueueInfo.isQueueRecovered() && queue.size() == 0);
978 }
979
980
981
982
983
984
985
986 private int countDistinctRowKeys(WALEdit edit) {
987 List<Cell> cells = edit.getCells();
988 int distinctRowKeys = 1;
989 int totalHFileEntries = 0;
990 Cell lastCell = cells.get(0);
991
992 int totalCells = edit.size();
993 for (int i = 0; i < totalCells; i++) {
994
995 if (CellUtil.matchingQualifier(cells.get(i), WALEdit.BULK_LOAD)) {
996 try {
997 BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cells.get(i));
998 List<StoreDescriptor> stores = bld.getStoresList();
999 int totalStores = stores.size();
1000 for (int j = 0; j < totalStores; j++) {
1001 totalHFileEntries += stores.get(j).getStoreFileList().size();
1002 }
1003 } catch (IOException e) {
1004 LOG.error("Failed to deserialize bulk load entry from wal edit. "
1005 + "Then its hfiles count will not be added into metric.");
1006 }
1007 }
1008
1009 if (!CellUtil.matchingRow(cells.get(i), lastCell)) {
1010 distinctRowKeys++;
1011 }
1012 lastCell = cells.get(i);
1013 }
1014 currentNbHFiles += totalHFileEntries;
1015 return distinctRowKeys + totalHFileEntries;
1016 }
1017
1018
1019
1020
1021
1022
1023 protected void shipEdits(boolean currentWALisBeingWrittenTo, List<WAL.Entry> entries) {
1024 int sleepMultiplier = 0;
1025 if (entries.isEmpty()) {
1026 LOG.warn("Was given 0 edits to ship");
1027 return;
1028 }
1029 while (isWorkerActive()) {
1030 try {
1031 if (throttler.isEnabled()) {
1032 long sleepTicks = throttler.getNextSleepInterval(currentSize);
1033 if (sleepTicks > 0) {
1034 try {
1035 if (LOG.isTraceEnabled()) {
1036 LOG.trace("To sleep " + sleepTicks + "ms for throttling control");
1037 }
1038 Thread.sleep(sleepTicks);
1039 } catch (InterruptedException e) {
1040 LOG.debug("Interrupted while sleeping for throttling control");
1041 Thread.currentThread().interrupt();
1042
1043
1044 continue;
1045 }
1046
1047 throttler.resetStartTick();
1048 }
1049 }
1050
1051
1052 ReplicationEndpoint.ReplicateContext replicateContext =
1053 new ReplicationEndpoint.ReplicateContext();
1054 replicateContext.setEntries(entries).setSize(currentSize);
1055 replicateContext.setWalGroupId(walGroupId);
1056
1057 long startTimeNs = System.nanoTime();
1058
1059 boolean replicated = replicationEndpoint.replicate(replicateContext);
1060 long endTimeNs = System.nanoTime();
1061
1062 if (!replicated) {
1063 continue;
1064 } else {
1065 sleepMultiplier = Math.max(sleepMultiplier - 1, 0);
1066 }
1067
1068 if (this.lastLoggedPosition != this.repLogReader.getPosition()) {
1069
1070 int size = entries.size();
1071 for (int i = 0; i < size; i++) {
1072 cleanUpHFileRefs(entries.get(i).getEdit());
1073
1074 TableName tableName = entries.get(i).getKey().getTablename();
1075 source.getSourceMetrics().setAgeOfLastShippedOpByTable(
1076 entries.get(i).getKey().getWriteTime(),
1077 tableName.getNameAsString());
1078 }
1079
1080 manager.logPositionAndCleanOldLogs(this.currentPath, peerClusterZnode,
1081 this.repLogReader.getPosition(), this.replicationQueueInfo.isQueueRecovered(),
1082 currentWALisBeingWrittenTo);
1083 this.lastLoggedPosition = this.repLogReader.getPosition();
1084 }
1085 if (throttler.isEnabled()) {
1086 throttler.addPushSize(currentSize);
1087 }
1088 totalReplicatedEdits.addAndGet(entries.size());
1089 totalReplicatedOperations.addAndGet(currentNbOperations);
1090
1091 metrics.shipBatch(currentNbOperations, currentSize, currentNbHFiles);
1092 metrics.setAgeOfLastShippedOp(entries.get(entries.size() - 1).getKey().getWriteTime(),
1093 walGroupId);
1094 if (LOG.isTraceEnabled()) {
1095 LOG.trace("Replicated " + totalReplicatedEdits + " entries in total, or "
1096 + totalReplicatedOperations + " operations in "
1097 + ((endTimeNs - startTimeNs) / 1000000) + " ms");
1098 }
1099 break;
1100 } catch (Exception ex) {
1101 LOG.warn(replicationEndpoint.getClass().getName() + " threw unknown exception:"
1102 + org.apache.hadoop.util.StringUtils.stringifyException(ex));
1103 if (sleepForRetries("ReplicationEndpoint threw exception", sleepMultiplier)) {
1104 sleepMultiplier++;
1105 }
1106 }
1107 }
1108 }
1109
1110
1111
1112
1113
1114
1115
1116 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DE_MIGHT_IGNORE",
1117 justification = "Yeah, this is how it works")
1118 protected boolean processEndOfFile(boolean dumpOnlyIfZeroLength) {
1119
1120 if (this.queue.size() != 0) {
1121
1122 final long trailerSize = this.repLogReader.currentTrailerSize();
1123 final long currentPosition = this.repLogReader.getPosition();
1124 FileStatus stat = null;
1125 try {
1126 stat = fs.getFileStatus(this.currentPath);
1127 } catch (IOException exception) {
1128 LOG.warn("Couldn't get file length information about log " + this.currentPath + ", it " + (trailerSize < 0 ? "was not" : "was") + " closed cleanly"
1129 + ", stats: " + getStats());
1130 metrics.incrUnknownFileLengthForClosedWAL();
1131 }
1132 if (stat != null) {
1133 if (trailerSize < 0) {
1134 if (currentPosition < stat.getLen()) {
1135 final long skippedBytes = stat.getLen() - currentPosition;
1136 LOG.info("Reached the end of WAL file '" + currentPath + "'. It was not closed cleanly, so we did not parse " + skippedBytes + " bytes of data.");
1137 metrics.incrUncleanlyClosedWALs();
1138 metrics.incrBytesSkippedInUncleanlyClosedWALs(skippedBytes);
1139 }
1140 } else if (currentPosition + trailerSize < stat.getLen()){
1141 LOG.warn("Processing end of WAL file '" + currentPath + "'. At position " + currentPosition + ", which is too far away from reported file length " + stat.getLen() +
1142 ". Restarting WAL reading (see HBASE-15983 for details). stats: " + getStats());
1143 repLogReader.setPosition(0);
1144 metrics.incrRestartedWALReading();
1145 metrics.incrRepeatedFileBytes(currentPosition);
1146 return false;
1147 }
1148 }
1149 if (LOG.isTraceEnabled()) {
1150 LOG.trace("Reached the end of log " + this.currentPath + ", stats: " + getStats()
1151 + ", and the length of the file is " + (stat == null ? "N/A" : stat.getLen()));
1152 }
1153 if (dumpOnlyIfZeroLength && stat.getLen() != 0) {
1154 return false;
1155 }
1156 this.currentPath = null;
1157 this.repLogReader.finishCurrentFile();
1158 this.reader = null;
1159 metrics.incrCompletedWAL();
1160 return true;
1161 } else if (this.replicationQueueInfo.isQueueRecovered()) {
1162 LOG.debug("Finished recovering queue for group " + walGroupId + " of peer "
1163 + peerClusterZnode);
1164 metrics.incrCompletedRecoveryQueue();
1165 setWorkerState(WorkerState.FINISHED);
1166 return true;
1167 }
1168 return false;
1169 }
1170
1171 public void startup() {
1172 String n = Thread.currentThread().getName();
1173 Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
1174 @Override
1175 public void uncaughtException(final Thread t, final Throwable e) {
1176 RSRpcServices.exitIfOOME(e);
1177 LOG.error("Unexpected exception in ReplicationSourceWorkerThread," + " currentPath="
1178 + getCurrentPath(), e);
1179 stopper.stop("Unexpected exception in ReplicationSourceWorkerThread");
1180 }
1181 };
1182 Threads.setDaemonThreadRunning(this, n + ".replicationSource." + walGroupId + ","
1183 + peerClusterZnode, handler);
1184 workerThreads.put(walGroupId, this);
1185 }
1186
1187 public Path getCurrentPath() {
1188 return this.currentPath;
1189 }
1190
1191 public long getCurrentPosition() {
1192 return this.repLogReader.getPosition();
1193 }
1194
1195 private boolean isWorkerActive() {
1196 return !stopper.isStopped() && state == WorkerState.RUNNING && !isInterrupted();
1197 }
1198
1199 private void terminate(String reason, Exception cause) {
1200 if (cause == null) {
1201 LOG.info("Closing worker for wal group " + this.walGroupId + " because: " + reason);
1202
1203 } else {
1204 LOG.error("Closing worker for wal group " + this.walGroupId
1205 + " because an error occurred: " + reason, cause);
1206 }
1207 setWorkerState(WorkerState.STOPPED);
1208 this.interrupt();
1209 Threads.shutdown(this, sleepForRetries);
1210 LOG.info("ReplicationSourceWorker " + this.getName() + " terminated");
1211 }
1212
1213
1214
1215
1216
1217 public void setWorkerState(WorkerState state) {
1218 this.state = state;
1219 }
1220
1221
1222
1223
1224
1225 public WorkerState getWorkerState() {
1226 return state;
1227 }
1228 }
1229 }