View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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   * Class that handles the source of a replication stream.
78   * Currently does not handle more than 1 slave
79   * For each slave cluster it selects a random number of peers
80   * using a replication ratio. For example, if replication ration = 0.1
81   * and slave cluster has 100 region servers, 10 will be selected.
82   * <p>
83   * A stream is considered down when we cannot contact a region server on the
84   * peer cluster for more than 55 seconds by default.
85   * </p>
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    // Queues of logs to process, entry in format of walGroupId->queue,
94    // each presents a queue for one wal group
95    private Map<String, PriorityBlockingQueue<Path>> queues =
96        new HashMap<String, PriorityBlockingQueue<Path>>();
97    // per group queue size, keep no more than this number of logs in each wal group
98    private int queueSizePerGroup;
99    private ReplicationQueues replicationQueues;
100   private ReplicationPeers replicationPeers;
101 
102   private Configuration conf;
103   private ReplicationQueueInfo replicationQueueInfo;
104   // id of the peer cluster this source replicates to
105   private String peerId;
106   // The manager of all sources to which we ping back our progress
107   private ReplicationSourceManager manager;
108   // Should we stop everything?
109   private Stoppable stopper;
110   // How long should we sleep for each retry
111   private long sleepForRetries;
112   // Max size in bytes of entriesArray
113   private long replicationQueueSizeCapacity;
114   // Max number of entries in entriesArray
115   private int replicationQueueNbCapacity;
116   private FileSystem fs;
117   // id of this cluster
118   private UUID clusterId;
119   // id of the other cluster
120   private UUID peerClusterId;
121   // total number of edits we replicated
122   private AtomicLong totalReplicatedEdits = new AtomicLong(0);
123   // total number of edits we replicated
124   private AtomicLong totalReplicatedOperations = new AtomicLong(0);
125   // The znode we currently play with
126   private String peerClusterZnode;
127   // Maximum number of retries before taking bold actions
128   private int maxRetriesMultiplier;
129   // Indicates if this particular source is running
130   private volatile boolean sourceRunning = false;
131   // Metrics for this source
132   private MetricsSource metrics;
133   //WARN threshold for the number of queued logs, defaults to 2
134   private int logQueueWarnThreshold;
135   // ReplicationEndpoint which will handle the actual replication
136   private ReplicationEndpoint replicationEndpoint;
137   // A filter (or a chain of filters) for the WAL entries.
138   private WALEntryFilter walEntryFilter;
139   // throttler
140   private ReplicationThrottler throttler;
141   private ConcurrentHashMap<String, ReplicationSourceWorkerThread> workerThreads =
142       new ConcurrentHashMap<String, ReplicationSourceWorkerThread>();
143   // Hold the state of a replication worker thread
144   public enum WorkerState {
145     RUNNING,
146     STOPPED,
147     FINISHED  // The worker is done processing a recovered queue
148   }
149 
150   /**
151    * Instantiation method used by region servers
152    *
153    * @param conf configuration to use
154    * @param fs file system to use
155    * @param manager replication manager to ping to
156    * @param stopper     the atomic boolean to use to stop the regionserver
157    * @param peerClusterZnode the name of our znode
158    * @param clusterId unique UUID for the cluster
159    * @param replicationEndpoint the replication endpoint implementation
160    * @param metrics metrics for replication source
161    * @throws IOException
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);    // 1 second
179     this.maxRetriesMultiplier =
180         this.conf.getInt("replication.source.maxretriesmultiplier", 300); // 5 minutes @ 1 sec per
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     // ReplicationQueueInfo parses the peerId out of the znode for us
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         // new wal group observed after source startup, start a new worker thread to track it
215         // notice: it's possible that log enqueued when this.running is set but worker thread
216         // still not launched, so it's necessary to check workerThreads before start the worker
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     // This will log a warning for each new log that gets created above the warn threshold
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       // peerClusterZnode will be in the form peerId + "-" + rsZNode.
244       // A peerId will not have "-" in its name, see HBASE-11394
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       // user has explicitly not defined any table cfs for replication, means replicate all the
260       // data
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     // mark we are running now
278     this.sourceRunning = true;
279     try {
280       // start the endpoint, connect to the cluster
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     // get the WALEntryFilter from ReplicationEndpoint and add it to default filters
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     // delay this until we are in an asynchronous thread
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     // In rare case, zookeeper setting may be messed up. That leads to the incorrect
317     // peerClusterId value, which is the same as the source clusterId
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     // start workers
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    * Do the sleeping logic
344    * @param msg Why we sleep
345    * @param sleepMultiplier by how many times the default sleeping time is augmented
346    * @return True if <code>sleepMultiplier</code> is &lt; <code>maxRetriesMultiplier</code>
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    * check whether the peer is enabled or not
363    *
364    * @return true if the peer is enabled, otherwise false
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     // only for testing
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    * Comparator used to compare logs together based on their start time
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      * Split a path to get the start time
464      * For example: 10.20.20.171%3A60020.1277499063250
465      * @param p path to split
466      * @return start time
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     // Our reader for the current log. open/close handled by repLogReader
506     private WAL.Reader reader;
507     // Last position in the log that we sent to ZooKeeper
508     private long lastLoggedPosition = -1;
509     // Path of the current log
510     private volatile Path currentPath;
511     // Handle on the log reader helper
512     private ReplicationWALReaderManager repLogReader;
513     // Current number of operations (Put/Delete) that we need to replicate
514     private int currentNbOperations = 0;
515     // Current size of data we need to replicate
516     private int currentSize = 0;
517     // Current state of the worker thread
518     private WorkerState state;
519     // Current number of hfiles that we need to replicate
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       // If this is recovered, the queue is already full and the first log
536       // normally has a position (unless the RS failed between 2 logs)
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       // Loop until we close down
551       while (isWorkerActive()) {
552         // Sleep until replication is enabled again
553         if (!isPeerEnabled()) {
554           if (sleepForRetries("Replication is disabled", sleepMultiplier)) {
555             sleepMultiplier++;
556           }
557           continue;
558         }
559         Path oldPath = getCurrentPath(); //note that in the current scenario,
560                                          //oldPath will be null when a log roll
561                                          //happens.
562         // Get a new path
563         boolean hasCurrentPath = getNextPath();
564         if (getCurrentPath() != null && oldPath == null) {
565           sleepMultiplier = 1; //reset the sleepMultiplier on a path change
566         }
567         if (!hasCurrentPath) {
568           if (sleepForRetries("No log to process", sleepMultiplier)) {
569             sleepMultiplier++;
570           }
571           continue;
572         }
573         boolean currentWALisBeingWrittenTo = false;
574         //For WAL files we own (rather than recovered), take a snapshot of whether the
575         //current WAL file (this.currentPath) is in use (for writing) NOW!
576         //Since the new WAL paths are enqueued only after the prev WAL file
577         //is 'closed', presence of an element in the queue means that
578         //the previous WAL file was closed, else the file is in use (currentPath)
579         //We take the snapshot now so that we are protected against races
580         //where a new file gets enqueued while the current file is being processed
581         //(and where we just finished reading the current file).
582         if (!this.replicationQueueInfo.isQueueRecovered() && queue.size() == 0) {
583           currentWALisBeingWrittenTo = true;
584         }
585         // Open a reader on it
586         if (!openReader(sleepMultiplier)) {
587           // Reset the sleep multiplier, else it'd be reused for the next file
588           sleepMultiplier = 1;
589           continue;
590         }
591 
592         // If we got a null reader but didn't continue, then sleep and continue
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         // If we didn't get anything to replicate, or if we hit a IOE,
644         // wait a bit and retry.
645         // But if we need to stop, don't bother sleeping
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           // Reset the sleep multiplier if nothing has actually gone wrong
654           if (!gotIOE) {
655             sleepMultiplier = 1;
656             // if there was nothing to ship and it's not an error
657             // set "ageOfLastShippedOp" to <now> to indicate that we're current
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         // use synchronize to make sure one last thread will clean the queue
670         synchronized (workerThreads) {
671           Threads.sleep(100);// wait a short while for other worker thread to fully exit
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       // If the worker exits run loop without finishing it's task, mark it as stopped.
687       if (state != WorkerState.FINISHED) {
688         setWorkerState(WorkerState.STOPPED);
689       }
690     }
691 
692     /**
693      * Read all the entries from the current log files and retain those that need to be replicated.
694      * Else, process the end of the current file.
695      * @param currentWALisBeingWrittenTo is the current WAL being written to
696      * @param entries resulting entries to be replicated
697      * @return true if we got nothing and went to the next file, false if we got entries
698      * @throws IOException
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         // don't replicate if the log entries have already been consumed by the cluster
715         if (replicationEndpoint.canReplicateToSameCluster()
716             || !entry.getKey().getClusterIds().contains(peerClusterId)) {
717           // Remove all KVs that should not be replicated
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             // Mark that the current cluster has the change
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         // Stop if too many entries or too big
738         // FIXME check the relationship between single wal group and overall
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       // If we didn't get anything and the queue has an object, it means we
755       // hit the end of the file for sure
756       return seenEntries == 0 && processEndOfFile(false);
757     }
758 
759     /**
760      * Calculate the total size of all the store files
761      * @param edit edit to count row keys from
762      * @return the total size of the store files
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         // peerClusterZnode will be in the form peerId + "-" + rsZNode.
792         // A peerId will not have "-" in its name, see HBASE-11394
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      * Poll for the next path
814      * @return true if a path was obtained, false if not
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             // For recovered queue: must use peerClusterZnode since peerId is a parsed value
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      * Open a reader on the current path
838      *
839      * @param sleepMultiplier by how many times the default sleeping time is augmented
840      * @return true if we should continue with that file, false if we are over with it
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             // We didn't find the log in the archive directory, look if it still
852             // exists in the dead RS folder (there could be a chain of failures
853             // to look at)
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                   // We found the right new location
869                   LOG.info("Log " + this.currentPath + " still exists at " +
870                       possibleLogLocation);
871                   // When running ReplicationSyncUp tool, we should replicate the data from WAL
872                   // which is moved to WAL splitting directory also.
873                   if (stopper instanceof ReplicationSyncUp.DummyServer) {
874                     // Open the log at the this location
875                     this.currentPath = possibleLogLocation;
876                     this.openReader(sleepMultiplier);
877                   }
878                   return true;
879                 }
880               }
881             }
882             // In the case of disaster/recovery, HMaster may be shutdown/crashed before flush data
883             // from .logs to .oldlogs. Loop into .logs folders and check whether a match exists
884             if (stopper instanceof ReplicationSyncUp.DummyServer) {
885               // N.B. the ReplicationSyncUp tool sets the manager.getWALDir to the root of the wal
886               //      area rather than to the wal area for a particular region server.
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                     // Open the log at the new location
897                     this.openReader(sleepMultiplier);
898                     return true;
899                   }
900                 }
901               }
902             }
903 
904             // TODO What happens if the log was missing from every single location?
905             // Although we need to check a couple of times as the log could have
906             // been moved by the master between the checks
907             // It can also happen if a recovered queue wasn't properly cleaned,
908             // such that the znode pointing to a log exists but the log was
909             // deleted a long time ago.
910             // For the moment, we'll throw the IO and processEndOfFile
911             throw new IOException("File from recovered queue is " +
912                 "nowhere to be found", fnfe);
913           } else {
914             // If the log was archived, continue reading from there
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               // Open the log at the new location
922               this.openReader(sleepMultiplier);
923 
924             }
925             // TODO What happens the log is missing in both places?
926           }
927         }
928       } catch (LeaseNotRecoveredException lnre) {
929         // HBASE-15019 the WAL was not closed due to some hiccup.
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           // Workaround for race condition in HDFS-4380
939           // which throws a NPE if we open a file before any data node has the most recent block
940           // Just sleep and retry. Will require re-reading compressed WALs for compressionContext.
941           LOG.warn("Got NPE opening reader, will retry.");
942         } else if (sleepMultiplier >= maxRetriesMultiplier
943             && conf.getBoolean("replication.source.eof.autorecovery", false)) {
944           // TODO Need a better way to determine if a file is really gone but
945           // TODO without scanning all logs dir
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      * Checks whether the current log file is empty, and it is not a recovered queue. This is to
971      * handle scenario when in an idle cluster, there is no entry in the current log and we keep on
972      * trying to read the log file and get EOFException. In case of a recovered queue the last log
973      * file may be empty, and we don't want to retry that.
974      */
975     private boolean isCurrentLogEmpty() {
976       return (this.repLogReader.getPosition() == 0 &&
977           !this.replicationQueueInfo.isQueueRecovered() && queue.size() == 0);
978     }
979 
980     /**
981      * Count the number of different row keys in the given edit because of mini-batching. We assume
982      * that there's at least one Cell in the WALEdit.
983      * @param edit edit to count row keys from
984      * @return number of different row keys
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         // Count HFiles to be replicated
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      * Do the shipping logic
1020      * @param currentWALisBeingWrittenTo was the current WAL being (seemingly)
1021      * written to when this method was called
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                 // current thread might be interrupted to terminate
1043                 // directly go back to while() for confirm this
1044                 continue;
1045               }
1046               // reset throttler's cycle start tick when sleep for throttling occurs
1047               throttler.resetStartTick();
1048             }
1049           }
1050           // create replicateContext here, so the entries can be GC'd upon return from this call
1051           // stack
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           // send the edits to the endpoint. Will block until the edits are shipped and acknowledged
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             //Clean up hfile references
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             //Log and clean up WAL logs
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           // FIXME check relationship between wal group and overall
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      * If the queue isn't empty, switch to the next one Else if this is a recovered queue, it means
1112      * we're done! Else we'll just continue to try reading the log file
1113      * @return true if we're done with the current file, false if we should continue trying to read
1114      *         from it
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       // We presume this means the file we're reading is closed.
1120       if (this.queue.size() != 0) {
1121         // -1 means the wal wasn't closed cleanly.
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      * Set the worker state
1215      * @param state
1216      */
1217     public void setWorkerState(WorkerState state) {
1218       this.state = state;
1219     }
1220 
1221     /**
1222      * Get the current state of this worker.
1223      * @return WorkerState
1224      */
1225     public WorkerState getWorkerState() {
1226       return state;
1227     }
1228   }
1229 }