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 com.google.common.annotations.VisibleForTesting;
22 import com.google.common.collect.Lists;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import com.google.common.util.concurrent.Service;
25
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Comparator;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.UUID;
34 import java.util.concurrent.ConcurrentHashMap;
35 import java.util.concurrent.PriorityBlockingQueue;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.atomic.AtomicLong;
38
39 import org.apache.commons.lang.StringUtils;
40 import org.apache.commons.logging.Log;
41 import org.apache.commons.logging.LogFactory;
42 import org.apache.hadoop.conf.Configuration;
43 import org.apache.hadoop.fs.FileStatus;
44 import org.apache.hadoop.fs.FileSystem;
45 import org.apache.hadoop.fs.Path;
46 import org.apache.hadoop.hbase.Cell;
47 import org.apache.hadoop.hbase.CellUtil;
48 import org.apache.hadoop.hbase.HBaseConfiguration;
49 import org.apache.hadoop.hbase.HConstants;
50 import org.apache.hadoop.hbase.Stoppable;
51 import org.apache.hadoop.hbase.TableName;
52 import org.apache.hadoop.hbase.classification.InterfaceAudience;
53 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.BulkLoadDescriptor;
54 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
55 import org.apache.hadoop.hbase.regionserver.RSRpcServices;
56 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
57 import org.apache.hadoop.hbase.replication.ChainWALEntryFilter;
58 import org.apache.hadoop.hbase.replication.ClusterMarkingEntryFilter;
59 import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
60 import org.apache.hadoop.hbase.replication.ReplicationException;
61 import org.apache.hadoop.hbase.replication.ReplicationPeer;
62 import org.apache.hadoop.hbase.replication.ReplicationPeers;
63 import org.apache.hadoop.hbase.replication.ReplicationQueueInfo;
64 import org.apache.hadoop.hbase.replication.ReplicationQueues;
65 import org.apache.hadoop.hbase.replication.SystemTableWALEntryFilter;
66 import org.apache.hadoop.hbase.replication.WALEntryFilter;
67 import org.apache.hadoop.hbase.replication.regionserver.ReplicationSourceWALReaderThread.WALEntryBatch;
68 import org.apache.hadoop.hbase.util.Bytes;
69 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
70 import org.apache.hadoop.hbase.util.FSUtils;
71 import org.apache.hadoop.hbase.util.Pair;
72 import org.apache.hadoop.hbase.util.Threads;
73 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
74 import org.apache.hadoop.hbase.wal.WAL.Entry;
75
76
77
78
79
80
81
82
83
84
85
86
87
88 @InterfaceAudience.Private
89 public class ReplicationSource extends Thread implements ReplicationSourceInterface {
90
91 private static final Log LOG = LogFactory.getLog(ReplicationSource.class);
92
93
94 private Map<String, PriorityBlockingQueue<Path>> queues =
95 new HashMap<String, PriorityBlockingQueue<Path>>();
96
97 private int queueSizePerGroup;
98 private ReplicationQueues replicationQueues;
99 private ReplicationPeers replicationPeers;
100
101 private Configuration conf;
102 private ReplicationQueueInfo replicationQueueInfo;
103
104 private String peerId;
105
106 private ReplicationSourceManager manager;
107
108 private Stoppable stopper;
109
110 private long sleepForRetries;
111 private FileSystem fs;
112
113 private UUID clusterId;
114
115 private UUID peerClusterId;
116
117 private AtomicLong totalReplicatedEdits = new AtomicLong(0);
118
119 private AtomicLong totalReplicatedOperations = new AtomicLong(0);
120
121 private String peerClusterZnode;
122
123 private int maxRetriesMultiplier;
124
125 private volatile boolean sourceRunning = false;
126
127 private MetricsSource metrics;
128
129 private int logQueueWarnThreshold;
130
131 private ReplicationEndpoint replicationEndpoint;
132
133 private WALEntryFilter walEntryFilter;
134
135 private ReplicationThrottler throttler;
136 private long defaultBandwidth;
137 private long currentBandwidth;
138 private ConcurrentHashMap<String, ReplicationSourceShipperThread> workerThreads =
139 new ConcurrentHashMap<String, ReplicationSourceShipperThread>();
140
141
142 public enum WorkerState {
143 RUNNING,
144 STOPPED,
145 FINISHED
146 }
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161 @Override
162 public void init(final Configuration conf, final FileSystem fs,
163 final ReplicationSourceManager manager, final ReplicationQueues replicationQueues,
164 final ReplicationPeers replicationPeers, final Stoppable stopper,
165 final String peerClusterZnode, final UUID clusterId, ReplicationEndpoint replicationEndpoint,
166 final MetricsSource metrics)
167 throws IOException {
168 this.stopper = stopper;
169 this.conf = HBaseConfiguration.create(conf);
170 decorateConf();
171 this.sleepForRetries =
172 this.conf.getLong("replication.source.sleepforretries", 1000);
173 this.maxRetriesMultiplier =
174 this.conf.getInt("replication.source.maxretriesmultiplier", 300);
175 this.queueSizePerGroup = this.conf.getInt("hbase.regionserver.maxlogs", 32);
176 this.replicationQueues = replicationQueues;
177 this.replicationPeers = replicationPeers;
178 this.manager = manager;
179 this.fs = fs;
180 this.metrics = metrics;
181 this.clusterId = clusterId;
182
183 this.peerClusterZnode = peerClusterZnode;
184 this.replicationQueueInfo = new ReplicationQueueInfo(peerClusterZnode);
185
186 this.peerId = this.replicationQueueInfo.getPeerId();
187 this.logQueueWarnThreshold = this.conf.getInt("replication.source.log.queue.warn", 2);
188 this.replicationEndpoint = replicationEndpoint;
189
190 defaultBandwidth = this.conf.getLong("replication.source.per.peer.node.bandwidth", 0);
191 currentBandwidth = getCurrentBandwidth();
192 this.throttler = new ReplicationThrottler((double) currentBandwidth / 10.0);
193
194 LOG.info("peerClusterZnode=" + peerClusterZnode + ", ReplicationSource : " + peerId
195 + ", currentBandwidth=" + this.currentBandwidth);
196 }
197
198 private void decorateConf() {
199 String replicationCodec = this.conf.get(HConstants.REPLICATION_CODEC_CONF_KEY);
200 if (StringUtils.isNotEmpty(replicationCodec)) {
201 this.conf.set(HConstants.RPC_CODEC_CONF_KEY, replicationCodec);
202 }
203 }
204
205 @Override
206 public void enqueueLog(Path log) {
207 String logPrefix = DefaultWALProvider.getWALPrefixFromWALName(log.getName());
208 PriorityBlockingQueue<Path> queue = queues.get(logPrefix);
209 if (queue == null) {
210 queue = new PriorityBlockingQueue<Path>(queueSizePerGroup, new LogsComparator());
211 queues.put(logPrefix, queue);
212 if (this.sourceRunning) {
213
214
215
216 final ReplicationSourceShipperThread worker =
217 new ReplicationSourceShipperThread(logPrefix, queue, replicationQueueInfo, this);
218 ReplicationSourceShipperThread extant = workerThreads.putIfAbsent(logPrefix, worker);
219 if (extant != null) {
220 LOG.debug("Someone has beat us to start a worker thread for wal group " + logPrefix);
221 } else {
222 LOG.debug("Starting up worker for wal group " + logPrefix);
223 worker.startup();
224 }
225 }
226 }
227 queue.put(log);
228 this.metrics.incrSizeOfLogQueue();
229
230 int queueSize = queue.size();
231 if (queueSize > this.logQueueWarnThreshold) {
232 LOG.warn("WAL group " + logPrefix + " queue size: " + queueSize
233 + " exceeds value of replication.source.log.queue.warn: " + logQueueWarnThreshold);
234 }
235 }
236
237 @Override
238 public void addHFileRefs(TableName tableName, byte[] family, List<Pair<Path, Path>> pairs)
239 throws ReplicationException {
240 String peerId = peerClusterZnode;
241 if (peerId.contains("-")) {
242
243
244 peerId = peerClusterZnode.split("-")[0];
245 }
246 Map<TableName, List<String>> tableCFMap = replicationPeers.getPeer(peerId).getTableCFs();
247 if (tableCFMap != null) {
248 List<String> tableCfs = tableCFMap.get(tableName);
249 if (tableCFMap.containsKey(tableName)
250 && (tableCfs == null || tableCfs.contains(Bytes.toString(family)))) {
251 this.replicationQueues.addHFileRefs(peerId, pairs);
252 metrics.incrSizeOfHFileRefsQueue(pairs.size());
253 } else {
254 LOG.debug("HFiles will not be replicated belonging to the table " + tableName + " family "
255 + Bytes.toString(family) + " to peer id " + peerId);
256 }
257 } else {
258
259
260 this.replicationQueues.addHFileRefs(peerId, pairs);
261 metrics.incrSizeOfHFileRefsQueue(pairs.size());
262 }
263 }
264
265 private void uninitialize() {
266 LOG.debug("Source exiting " + this.peerId);
267 metrics.clear();
268 if (replicationEndpoint.state() == Service.State.STARTING
269 || replicationEndpoint.state() == Service.State.RUNNING) {
270 replicationEndpoint.stopAndWait();
271 }
272 }
273
274 @Override
275 public void run() {
276
277 this.sourceRunning = true;
278 try {
279
280 Service.State state = replicationEndpoint.start().get();
281 if (state != Service.State.RUNNING) {
282 LOG.warn("ReplicationEndpoint was not started. Exiting");
283 uninitialize();
284 return;
285 }
286 } catch (Exception ex) {
287 LOG.warn("Error starting ReplicationEndpoint, exiting", ex);
288 throw new RuntimeException(ex);
289 }
290
291
292 ArrayList<WALEntryFilter> filters = Lists.newArrayList(
293 (WALEntryFilter)new SystemTableWALEntryFilter());
294 WALEntryFilter filterFromEndpoint = this.replicationEndpoint.getWALEntryfilter();
295 if (filterFromEndpoint != null) {
296 filters.add(filterFromEndpoint);
297 }
298 this.walEntryFilter = new ChainWALEntryFilter(filters);
299
300 int sleepMultiplier = 1;
301
302 while (this.isSourceActive() && this.peerClusterId == null) {
303 this.peerClusterId = replicationEndpoint.getPeerUUID();
304 if (this.isSourceActive() && this.peerClusterId == null) {
305 if (sleepForRetries("Cannot contact the peer's zk ensemble", sleepMultiplier)) {
306 sleepMultiplier++;
307 }
308 }
309 }
310
311 if (!this.isSourceActive()) {
312 return;
313 }
314
315
316
317 if (clusterId.equals(peerClusterId) && !replicationEndpoint.canReplicateToSameCluster()) {
318 this.terminate("ClusterId " + clusterId + " is replicating to itself: peerClusterId "
319 + peerClusterId + " which is not allowed by ReplicationEndpoint:"
320 + replicationEndpoint.getClass().getName(), null, false);
321 this.manager.closeQueue(this);
322 return;
323 }
324 LOG.info("Replicating " + clusterId + " -> " + peerClusterId);
325
326 for (Map.Entry<String, PriorityBlockingQueue<Path>> entry : queues.entrySet()) {
327 String walGroupId = entry.getKey();
328 PriorityBlockingQueue<Path> queue = entry.getValue();
329 final ReplicationSourceShipperThread worker =
330 new ReplicationSourceShipperThread(walGroupId, queue, replicationQueueInfo, this);
331 ReplicationSourceShipperThread extant = workerThreads.putIfAbsent(walGroupId, worker);
332 if (extant != null) {
333 LOG.debug("Someone has beat us to start a worker thread for wal group " + walGroupId);
334 } else {
335 LOG.debug("Starting up worker for wal group " + walGroupId);
336 worker.startup();
337 }
338 }
339 }
340
341
342
343
344
345
346
347 protected boolean sleepForRetries(String msg, int sleepMultiplier) {
348 try {
349 if (LOG.isTraceEnabled()) {
350 LOG.trace(msg + ", sleeping " + sleepForRetries + " times " + sleepMultiplier);
351 }
352 Thread.sleep(this.sleepForRetries * sleepMultiplier);
353 } catch (InterruptedException e) {
354 LOG.debug("Interrupted while sleeping between retries");
355 Thread.currentThread().interrupt();
356 }
357 return sleepMultiplier < maxRetriesMultiplier;
358 }
359
360
361
362
363
364
365 protected boolean isPeerEnabled() {
366 return this.replicationPeers.getStatusOfPeer(this.peerId);
367 }
368
369 @Override
370 public void startup() {
371 String n = Thread.currentThread().getName();
372 Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
373 @Override
374 public void uncaughtException(final Thread t, final Throwable e) {
375 LOG.error("Unexpected exception in ReplicationSource", e);
376 }
377 };
378 Threads
379 .setDaemonThreadRunning(this, n + ".replicationSource," + this.peerClusterZnode, handler);
380 }
381
382 @Override
383 public void terminate(String reason) {
384 terminate(reason, null);
385 }
386
387 @Override
388 public void terminate(String reason, Exception cause) {
389 terminate(reason, cause, true);
390 }
391
392 public void terminate(String reason, Exception cause, boolean join) {
393 if (cause == null) {
394 LOG.info("Closing source "
395 + this.peerClusterZnode + " because: " + reason);
396
397 } else {
398 LOG.error("Closing source " + this.peerClusterZnode
399 + " because an error occurred: " + reason, cause);
400 }
401 this.sourceRunning = false;
402 Collection<ReplicationSourceShipperThread> workers = workerThreads.values();
403 for (ReplicationSourceShipperThread worker : workers) {
404 worker.setWorkerState(WorkerState.STOPPED);
405 worker.entryReader.interrupt();
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 (ReplicationSourceShipperThread 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 @VisibleForTesting
441 public Path getCurrentPath() {
442 for (ReplicationSourceShipperThread worker : workerThreads.values()) {
443 if (worker.getCurrentPath() != null) return worker.getCurrentPath();
444 }
445 return null;
446 }
447
448 @VisibleForTesting
449 public Path getLastLoggedPath() {
450 for (ReplicationSourceShipperThread worker : workerThreads.values()) {
451 return worker.getLastLoggedPath();
452 }
453 return null;
454 }
455
456 @VisibleForTesting
457 public long getLastLoggedPosition() {
458 for (ReplicationSourceShipperThread worker : workerThreads.values()) {
459 return worker.getLastLoggedPosition();
460 }
461 return 0;
462 }
463
464 private boolean isSourceActive() {
465 return !this.stopper.isStopped() && this.sourceRunning;
466 }
467
468
469
470
471 public static class LogsComparator implements Comparator<Path> {
472
473 @Override
474 public int compare(Path o1, Path o2) {
475 return Long.compare(getTS(o1), getTS(o2));
476 }
477
478
479
480
481
482
483
484 private static long getTS(Path p) {
485 int tsIndex = p.getName().lastIndexOf('.') + 1;
486 return Long.parseLong(p.getName().substring(tsIndex));
487 }
488 }
489
490 @Override
491 public String getStats() {
492 StringBuilder sb = new StringBuilder();
493 sb.append("Total replicated edits: ").append(totalReplicatedEdits)
494 .append(", current progress: \n");
495 for (Map.Entry<String, ReplicationSourceShipperThread> entry : workerThreads.entrySet()) {
496 String walGroupId = entry.getKey();
497 ReplicationSourceShipperThread worker = entry.getValue();
498 long position = worker.getLastLoggedPosition();
499 Path currentPath = worker.getLastLoggedPath();
500 sb.append("walGroup [").append(walGroupId).append("]: ");
501 if (currentPath != null) {
502 sb.append("currently replicating from: ").append(currentPath).append(" at position: ")
503 .append(position).append("\n");
504 } else {
505 sb.append("no replication ongoing, waiting for new log");
506 }
507 }
508 return sb.toString();
509 }
510
511 @Override
512 public MetricsSource getSourceMetrics() {
513 return this.metrics;
514 }
515
516 private long getCurrentBandwidth() {
517 ReplicationPeer replicationPeer = this.replicationPeers.getPeer(peerId);
518 long peerBandwidth = replicationPeer != null ? replicationPeer.getPeerBandwidth() : 0;
519
520 return peerBandwidth != 0 ? peerBandwidth : defaultBandwidth;
521 }
522
523
524
525 public class ReplicationSourceShipperThread extends Thread {
526 ReplicationSourceInterface source;
527 String walGroupId;
528 PriorityBlockingQueue<Path> queue;
529 ReplicationQueueInfo replicationQueueInfo;
530
531 private long lastLoggedPosition = -1;
532
533 private volatile Path lastLoggedPath;
534
535 private WorkerState state;
536 ReplicationSourceWALReaderThread entryReader;
537
538 public ReplicationSourceShipperThread(String walGroupId,
539 PriorityBlockingQueue<Path> queue, ReplicationQueueInfo replicationQueueInfo,
540 ReplicationSourceInterface source) {
541 this.walGroupId = walGroupId;
542 this.queue = queue;
543 this.replicationQueueInfo = replicationQueueInfo;
544 this.source = source;
545 }
546
547 @Override
548 public void run() {
549 setWorkerState(WorkerState.RUNNING);
550
551 while (isWorkerActive()) {
552 int sleepMultiplier = 1;
553
554 if (!isPeerEnabled()) {
555 if (sleepForRetries("Replication is disabled", sleepMultiplier)) {
556 sleepMultiplier++;
557 }
558 continue;
559 }
560 while (entryReader == null) {
561 if (sleepForRetries("Replication WAL entry reader thread not initialized",
562 sleepMultiplier)) {
563 sleepMultiplier++;
564 }
565 if (sleepMultiplier == maxRetriesMultiplier) {
566 LOG.warn("Replication WAL entry reader thread not initialized");
567 }
568 }
569
570 try {
571 WALEntryBatch entryBatch = entryReader.take();
572 shipEdits(entryBatch);
573 if (!entryBatch.hasMoreEntries()) {
574 LOG.debug("Finished recovering queue for group "
575 + walGroupId + " of peer " + peerClusterZnode);
576 metrics.incrCompletedRecoveryQueue();
577 setWorkerState(WorkerState.FINISHED);
578 }
579 } catch (InterruptedException e) {
580 LOG.trace("Interrupted while waiting for next replication entry batch", e);
581 Thread.currentThread().interrupt();
582 }
583 }
584
585 if (getWorkerState() == WorkerState.FINISHED) {
586
587 synchronized (this) {
588 Threads.sleep(100);
589 boolean allOtherTaskDone = true;
590 for (ReplicationSourceShipperThread worker : workerThreads.values()) {
591 if (!worker.equals(this) && worker.getWorkerState() != WorkerState.FINISHED) {
592 allOtherTaskDone = false;
593 break;
594 }
595 }
596 if (allOtherTaskDone) {
597 manager.closeRecoveredQueue(this.source);
598
599 if (source instanceof ReplicationSource) {
600 ((ReplicationSource) source).replicationEndpoint.stop();
601 }
602 LOG.info("Finished recovering queue " + peerClusterZnode
603 + " with the following stats: " + getStats());
604 }
605 }
606 }
607
608 if (state != WorkerState.FINISHED) {
609 setWorkerState(WorkerState.STOPPED);
610 }
611 }
612
613 private void cleanUpHFileRefs(WALEdit edit) throws IOException {
614 String peerId = peerClusterZnode;
615 if (peerId.contains("-")) {
616
617
618 peerId = peerClusterZnode.split("-")[0];
619 }
620 List<Cell> cells = edit.getCells();
621 int totalCells = cells.size();
622 for (int i = 0; i < totalCells; i++) {
623 Cell cell = cells.get(i);
624 if (CellUtil.matchingQualifier(cell, WALEdit.BULK_LOAD)) {
625 BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cell);
626 List<StoreDescriptor> stores = bld.getStoresList();
627 int totalStores = stores.size();
628 for (int j = 0; j < totalStores; j++) {
629 List<String> storeFileList = stores.get(j).getStoreFileList();
630 manager.cleanUpHFileRefs(peerId, storeFileList);
631 metrics.decrSizeOfHFileRefsQueue(storeFileList.size());
632 }
633 }
634 }
635 }
636
637 private void checkBandwidthChangeAndResetThrottler() {
638 long peerBandwidth = getCurrentBandwidth();
639 if (peerBandwidth != currentBandwidth) {
640 currentBandwidth = peerBandwidth;
641 throttler.setBandwidth((double) currentBandwidth / 10.0);
642 LOG.info("ReplicationSource : " + peerId
643 + " bandwidth throttling changed, currentBandWidth=" + currentBandwidth);
644 }
645 }
646
647
648
649
650 protected void shipEdits(WALEntryBatch entryBatch) {
651 List<Entry> entries = entryBatch.getWalEntries();
652 long lastReadPosition = entryBatch.getLastWalPosition();
653 lastLoggedPath = entryBatch.getLastWalPath();
654 int sleepMultiplier = 0;
655 if (entries.isEmpty()) {
656 updateLogPosition(lastReadPosition);
657
658
659 metrics.setAgeOfLastShippedOp(EnvironmentEdgeManager.currentTime(), walGroupId);
660 return;
661 }
662 int currentSize = (int) entryBatch.getHeapSize();
663 while (isWorkerActive()) {
664 try {
665 checkBandwidthChangeAndResetThrottler();
666 if (throttler.isEnabled()) {
667 long sleepTicks = throttler.getNextSleepInterval(currentSize);
668 if (sleepTicks > 0) {
669 try {
670 if (LOG.isTraceEnabled()) {
671 LOG.trace("To sleep " + sleepTicks + "ms for throttling control");
672 }
673 Thread.sleep(sleepTicks);
674 } catch (InterruptedException e) {
675 LOG.debug("Interrupted while sleeping for throttling control");
676 Thread.currentThread().interrupt();
677
678
679 continue;
680 }
681
682 throttler.resetStartTick();
683 }
684 }
685
686
687 ReplicationEndpoint.ReplicateContext replicateContext =
688 new ReplicationEndpoint.ReplicateContext();
689 replicateContext.setEntries(entries).setSize(currentSize);
690 replicateContext.setWalGroupId(walGroupId);
691
692 long startTimeNs = System.nanoTime();
693
694 boolean replicated = replicationEndpoint.replicate(replicateContext);
695 long endTimeNs = System.nanoTime();
696
697 if (!replicated) {
698 continue;
699 } else {
700 sleepMultiplier = Math.max(sleepMultiplier - 1, 0);
701 }
702
703 if (this.lastLoggedPosition != lastReadPosition) {
704
705 int size = entries.size();
706 for (int i = 0; i < size; i++) {
707 cleanUpHFileRefs(entries.get(i).getEdit());
708
709 TableName tableName = entries.get(i).getKey().getTablename();
710 source.getSourceMetrics().setAgeOfLastShippedOpByTable(
711 entries.get(i).getKey().getWriteTime(),
712 tableName.getNameAsString());
713 }
714
715 updateLogPosition(lastReadPosition);
716 }
717 if (throttler.isEnabled()) {
718 throttler.addPushSize(currentSize);
719 }
720 totalReplicatedEdits.addAndGet(entries.size());
721 totalReplicatedOperations.addAndGet(entryBatch.getNbOperations());
722
723 metrics.shipBatch(entryBatch.getNbOperations(), currentSize, entryBatch.getNbHFiles());
724 metrics.setAgeOfLastShippedOp(entries.get(entries.size() - 1).getKey().getWriteTime(),
725 walGroupId);
726 if (LOG.isTraceEnabled()) {
727 LOG.trace("Replicated " + totalReplicatedEdits + " entries in total, or "
728 + totalReplicatedOperations + " operations in "
729 + ((endTimeNs - startTimeNs) / 1000000) + " ms");
730 }
731 break;
732 } catch (Exception ex) {
733 LOG.warn(replicationEndpoint.getClass().getName() + " threw unknown exception:"
734 + org.apache.hadoop.util.StringUtils.stringifyException(ex));
735 if (sleepForRetries("ReplicationEndpoint threw exception", sleepMultiplier)) {
736 sleepMultiplier++;
737 }
738 }
739 }
740 }
741
742 private void updateLogPosition(long lastReadPosition) {
743 manager.logPositionAndCleanOldLogs(lastLoggedPath, peerClusterZnode, lastReadPosition,
744 this.replicationQueueInfo.isQueueRecovered(), false);
745 lastLoggedPosition = lastReadPosition;
746 }
747
748 public void startup() {
749 String n = Thread.currentThread().getName();
750 Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
751 @Override
752 public void uncaughtException(final Thread t, final Throwable e) {
753 RSRpcServices.exitIfOOME(e);
754 LOG.error("Unexpected exception in ReplicationSourceWorkerThread," + " currentPath="
755 + getLastLoggedPath(), e);
756 stopper.stop("Unexpected exception in ReplicationSourceWorkerThread");
757 }
758 };
759 Threads.setDaemonThreadRunning(this, n + ".replicationSource." + walGroupId + ","
760 + peerClusterZnode, handler);
761 workerThreads.put(walGroupId, this);
762
763 long startPosition = 0;
764
765 if (this.replicationQueueInfo.isQueueRecovered()) {
766 startPosition = getRecoveredQueueStartPos(startPosition);
767 int numRetries = 0;
768 while (numRetries <= maxRetriesMultiplier) {
769 try {
770 locateRecoveredPaths();
771 break;
772 } catch (IOException e) {
773 LOG.error("Error while locating recovered queue paths, attempt #" + numRetries);
774 numRetries++;
775 }
776 }
777 }
778
779 startWALReaderThread(n, handler, startPosition);
780 }
781
782
783
784 private long getRecoveredQueueStartPos(long startPosition) {
785 try {
786 startPosition =
787 (replicationQueues.getLogPosition(peerClusterZnode, this.queue.peek().getName()));
788 if (LOG.isTraceEnabled()) {
789 LOG.trace("Recovered queue started with log " + this.queue.peek() + " at position "
790 + startPosition);
791 }
792 } catch (ReplicationException e) {
793 terminate("Couldn't get the position of this recovered queue " + peerClusterZnode, e);
794 }
795 return startPosition;
796 }
797
798
799 private void startWALReaderThread(String threadName, Thread.UncaughtExceptionHandler handler,
800 long startPosition) {
801 ArrayList<WALEntryFilter> filters = Lists.newArrayList(walEntryFilter,
802 new ClusterMarkingEntryFilter(clusterId, peerClusterId, replicationEndpoint));
803 ChainWALEntryFilter readerFilter = new ChainWALEntryFilter(filters);
804 entryReader = new ReplicationSourceWALReaderThread(manager, replicationQueueInfo, queue,
805 startPosition, fs, conf, readerFilter, metrics);
806 Threads.setDaemonThreadRunning(entryReader, threadName
807 + ".replicationSource.replicationWALReaderThread." + walGroupId + "," + peerClusterZnode,
808 handler);
809 }
810
811
812
813 private void locateRecoveredPaths() throws IOException {
814 boolean hasPathChanged = false;
815 PriorityBlockingQueue<Path> newPaths =
816 new PriorityBlockingQueue<Path>(queueSizePerGroup, new LogsComparator());
817 pathsLoop: for (Path path : queue) {
818 if (fs.exists(path)) {
819 newPaths.add(path);
820 continue;
821 }
822
823 hasPathChanged = true;
824 if (stopper instanceof ReplicationSyncUp.DummyServer) {
825
826
827 Path newPath = getReplSyncUpPath(path);
828 newPaths.add(newPath);
829 continue;
830 } else {
831
832
833 List<String> deadRegionServers = this.replicationQueueInfo.getDeadRegionServers();
834 LOG.info("NB dead servers : " + deadRegionServers.size());
835 final Path walDir = FSUtils.getWALRootDir(conf);
836 for (String curDeadServerName : deadRegionServers) {
837 final Path deadRsDirectory =
838 new Path(walDir, DefaultWALProvider.getWALDirectoryName(curDeadServerName));
839 Path[] locs = new Path[] { new Path(deadRsDirectory, path.getName()), new Path(
840 deadRsDirectory.suffix(DefaultWALProvider.SPLITTING_EXT), path.getName()) };
841 for (Path possibleLogLocation : locs) {
842 LOG.info("Possible location " + possibleLogLocation.toUri().toString());
843 if (manager.getFs().exists(possibleLogLocation)) {
844
845 LOG.info("Log " + path + " still exists at " + possibleLogLocation);
846 newPaths.add(possibleLogLocation);
847 continue pathsLoop;
848 }
849 }
850 }
851
852 LOG.error(
853 String.format("WAL Path %s doesn't exist and couldn't find its new location", path));
854 newPaths.add(path);
855 }
856 }
857
858 if (hasPathChanged) {
859 if (newPaths.size() != queue.size()) {
860 LOG.error("Recovery queue size is incorrect");
861 throw new IOException("Recovery queue size error");
862 }
863
864
865
866 queue.clear();
867 for (Path path : newPaths) {
868 queue.add(path);
869 }
870 }
871 }
872
873
874
875 private Path getReplSyncUpPath(Path path) throws IOException {
876 FileStatus[] rss = fs.listStatus(manager.getLogDir());
877 for (FileStatus rs : rss) {
878 Path p = rs.getPath();
879 FileStatus[] logs = fs.listStatus(p);
880 for (FileStatus log : logs) {
881 p = new Path(p, log.getPath().getName());
882 if (p.getName().equals(path.getName())) {
883 LOG.info("Log " + p.getName() + " found at " + p);
884 return p;
885 }
886 }
887 }
888 LOG.error("Didn't find path for: " + path.getName());
889 return path;
890 }
891
892 public Path getCurrentPath() {
893 return this.entryReader.getCurrentPath();
894 }
895
896 public Path getLastLoggedPath() {
897 return lastLoggedPath;
898 }
899
900 public long getLastLoggedPosition() {
901 return lastLoggedPosition;
902 }
903
904 private boolean isWorkerActive() {
905 return !stopper.isStopped() && state == WorkerState.RUNNING && !isInterrupted();
906 }
907
908 private void terminate(String reason, Exception cause) {
909 if (cause == null) {
910 LOG.info("Closing worker for wal group " + this.walGroupId + " because: " + reason);
911
912 } else {
913 LOG.error("Closing worker for wal group " + this.walGroupId
914 + " because an error occurred: " + reason, cause);
915 }
916 entryReader.interrupt();
917 Threads.shutdown(entryReader, sleepForRetries);
918 setWorkerState(WorkerState.STOPPED);
919 this.interrupt();
920 Threads.shutdown(this, sleepForRetries);
921 LOG.info("ReplicationSourceWorker " + this.getName() + " terminated");
922 }
923
924
925
926
927
928 public void setWorkerState(WorkerState state) {
929 this.state = state;
930 if (entryReader != null) {
931 entryReader.setReaderRunning(state == WorkerState.RUNNING);
932 }
933 }
934
935
936
937
938
939 public WorkerState getWorkerState() {
940 return state;
941 }
942 }
943 }