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.net.ConnectException;
25  import java.net.SocketTimeoutException;
26  import java.util.ArrayList;
27  import java.util.Comparator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.NavigableMap;
31  import java.util.UUID;
32  import java.util.concurrent.PriorityBlockingQueue;
33  import java.util.concurrent.TimeUnit;
34  
35  import org.apache.commons.lang.StringUtils;
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  import org.apache.hadoop.classification.InterfaceAudience;
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.HBaseConfiguration;
44  import org.apache.hadoop.hbase.HConstants;
45  import org.apache.hadoop.hbase.KeyValue;
46  import org.apache.hadoop.hbase.Stoppable;
47  import org.apache.hadoop.hbase.TableName;
48  import org.apache.hadoop.hbase.TableNotFoundException;
49  import org.apache.hadoop.hbase.client.HConnection;
50  import org.apache.hadoop.hbase.client.HConnectionManager;
51  import org.apache.hadoop.hbase.protobuf.ReplicationProtbufUtil;
52  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService.BlockingInterface;
53  import org.apache.hadoop.hbase.regionserver.wal.HLog;
54  import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
55  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
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.regionserver.ReplicationSinkManager.SinkPeer;
61  import org.apache.hadoop.hbase.util.Bytes;
62  import org.apache.hadoop.hbase.util.Threads;
63  import org.apache.hadoop.ipc.RemoteException;
64  
65  /**
66   * Class that handles the source of a replication stream.
67   * Currently does not handle more than 1 slave
68   * For each slave cluster it selects a random number of peers
69   * using a replication ratio. For example, if replication ration = 0.1
70   * and slave cluster has 100 region servers, 10 will be selected.
71   * <p/>
72   * A stream is considered down when we cannot contact a region server on the
73   * peer cluster for more than 55 seconds by default.
74   * <p/>
75   *
76   */
77  @InterfaceAudience.Private
78  public class ReplicationSource extends Thread
79      implements ReplicationSourceInterface {
80  
81    public static final Log LOG = LogFactory.getLog(ReplicationSource.class);
82    // Queue of logs to process
83    private PriorityBlockingQueue<Path> queue;
84    private HConnection conn;
85    private ReplicationQueues replicationQueues;
86    private ReplicationPeers replicationPeers;
87    private Configuration conf;
88    private ReplicationQueueInfo replicationQueueInfo;
89    // id of the peer cluster this source replicates to
90    private String peerId;
91    // The manager of all sources to which we ping back our progress
92    private ReplicationSourceManager manager;
93    // Should we stop everything?
94    private Stoppable stopper;
95    // How long should we sleep for each retry
96    private long sleepForRetries;
97    // Max size in bytes of entriesArray
98    private long replicationQueueSizeCapacity;
99    // Max number of entries in entriesArray
100   private int replicationQueueNbCapacity;
101   // Our reader for the current log
102   private HLog.Reader reader;
103   // Last position in the log that we sent to ZooKeeper
104   private long lastLoggedPosition = -1;
105   // Path of the current log
106   private volatile Path currentPath;
107   private FileSystem fs;
108   // id of this cluster
109   private UUID clusterId;
110   // id of the other cluster
111   private UUID peerClusterId;
112   // total number of edits we replicated
113   private long totalReplicatedEdits = 0;
114   // total number of edits we replicated
115   private long totalReplicatedOperations = 0;
116   // The znode we currently play with
117   private String peerClusterZnode;
118   // Maximum number of retries before taking bold actions
119   private int maxRetriesMultiplier;
120   // Socket timeouts require even bolder actions since we don't want to DDOS
121   private int socketTimeoutMultiplier;
122   // Current number of operations (Put/Delete) that we need to replicate
123   private int currentNbOperations = 0;
124   // Current size of data we need to replicate
125   private int currentSize = 0;
126   // Indicates if this particular source is running
127   private volatile boolean running = true;
128   // Metrics for this source
129   private MetricsSource metrics;
130   // Handle on the log reader helper
131   private ReplicationHLogReaderManager repLogReader;
132   // Handles connecting to peer region servers
133   private ReplicationSinkManager replicationSinkMgr;
134   //WARN threshold for the number of queued logs, defaults to 2
135   private int logQueueWarnThreshold;
136   // throttler
137   private ReplicationThrottler throttler;
138 
139   /**
140    * Instantiation method used by region servers
141    *
142    * @param conf configuration to use
143    * @param fs file system to use
144    * @param manager replication manager to ping to
145    * @param stopper     the atomic boolean to use to stop the regionserver
146    * @param peerClusterZnode the name of our znode
147    * @throws IOException
148    */
149   public void init(final Configuration conf, final FileSystem fs,
150       final ReplicationSourceManager manager, final ReplicationQueues replicationQueues,
151       final ReplicationPeers replicationPeers, final Stoppable stopper,
152       final String peerClusterZnode, final UUID clusterId) throws IOException {
153     this.stopper = stopper;
154     this.conf = HBaseConfiguration.create(conf);
155     decorateConf();
156     this.replicationQueueSizeCapacity =
157         this.conf.getLong("replication.source.size.capacity", 1024*1024*64);
158     this.replicationQueueNbCapacity =
159         this.conf.getInt("replication.source.nb.capacity", 25000);
160     this.maxRetriesMultiplier = this.conf.getInt("replication.source.maxretriesmultiplier", 10);
161     this.socketTimeoutMultiplier = this.conf.getInt("replication.source.socketTimeoutMultiplier",
162         maxRetriesMultiplier * maxRetriesMultiplier);
163     this.queue =
164         new PriorityBlockingQueue<Path>(
165             this.conf.getInt("hbase.regionserver.maxlogs", 32),
166             new LogsComparator());
167     // TODO: This connection is replication specific or we should make it particular to
168     // replication and make replication specific settings such as compression or codec to use
169     // passing Cells.
170     this.conn = HConnectionManager.getConnection(this.conf);
171     long bandwidth = this.conf.getLong("replication.source.per.peer.node.bandwidth", 0);
172     this.throttler = new ReplicationThrottler((double)bandwidth/10.0);
173     this.replicationQueues = replicationQueues;
174     this.replicationPeers = replicationPeers;
175     this.manager = manager;
176     this.sleepForRetries =
177         this.conf.getLong("replication.source.sleepforretries", 1000);
178     this.fs = fs;
179     this.metrics = new MetricsSource(peerClusterZnode);
180     this.repLogReader = new ReplicationHLogReaderManager(this.fs, this.conf);
181     this.clusterId = clusterId;
182 
183     this.peerClusterZnode = peerClusterZnode;
184     this.replicationQueueInfo = new ReplicationQueueInfo(peerClusterZnode);
185     // ReplicationQueueInfo parses the peerId out of the znode for us
186     this.peerId = this.replicationQueueInfo.getPeerId();
187     this.replicationSinkMgr = new ReplicationSinkManager(conn, peerId, replicationPeers, this.conf);
188     this.logQueueWarnThreshold = this.conf.getInt("replication.source.log.queue.warn", 2);
189   }
190 
191   private void decorateConf() {
192     String replicationCodec = this.conf.get(HConstants.REPLICATION_CODEC_CONF_KEY);
193     if (StringUtils.isNotEmpty(replicationCodec)) {
194       this.conf.set(HConstants.RPC_CODEC_CONF_KEY, replicationCodec);
195     }
196   }
197 
198   @Override
199   public void enqueueLog(Path log) {
200     this.queue.put(log);
201     int queueSize = queue.size();
202     this.metrics.setSizeOfLogQueue(queueSize);
203     // This will log a warning for each new log that gets created above the warn threshold
204     if (queueSize > this.logQueueWarnThreshold) {
205       LOG.warn("Queue size: " + queueSize +
206         " exceeds value of replication.source.log.queue.warn: " + logQueueWarnThreshold);
207     }
208   }
209 
210   private void uninitialize() {
211     if (this.conn != null) {
212       try {
213         this.conn.close();
214       } catch (IOException e) {
215         LOG.debug("Attempt to close connection failed", e);
216       }
217     }
218     LOG.debug("Source exiting " + this.peerId);
219     metrics.clear();
220   }
221 
222   @Override
223   public void run() {
224     connectToPeers();
225     // We were stopped while looping to connect to sinks, just abort
226     if (!this.isActive()) {
227       uninitialize();
228       return;
229     }
230 
231     int sleepMultiplier = 1;
232     // delay this until we are in an asynchronous thread
233     while (this.isActive() && this.peerClusterId == null) {
234       this.peerClusterId = replicationPeers.getPeerUUID(this.peerId);
235       if (this.isActive() && this.peerClusterId == null) {
236         if (sleepForRetries("Cannot contact the peer's zk ensemble", sleepMultiplier)) {
237           sleepMultiplier++;
238         }
239       }
240     }
241     // We were stopped while looping to contact peer's zk ensemble, just abort
242     if (!this.isActive()) {
243       uninitialize();
244       return;
245     }
246 
247     // resetting to 1 to reuse later
248     sleepMultiplier = 1;
249 
250     // In rare case, zookeeper setting may be messed up. That leads to the incorrect
251     // peerClusterId value, which is the same as the source clusterId
252     if (clusterId.equals(peerClusterId)) {
253       this.terminate("ClusterId " + clusterId + " is replicating to itself: peerClusterId "
254           + peerClusterId);
255     }
256     LOG.info("Replicating "+clusterId + " -> " + peerClusterId);
257 
258     // If this is recovered, the queue is already full and the first log
259     // normally has a position (unless the RS failed between 2 logs)
260     if (this.replicationQueueInfo.isQueueRecovered()) {
261       try {
262         this.repLogReader.setPosition(this.replicationQueues.getLogPosition(this.peerClusterZnode,
263           this.queue.peek().getName()));
264         if (LOG.isTraceEnabled()) {
265           LOG.trace("Recovered queue started with log " + this.queue.peek() +
266               " at position " + this.repLogReader.getPosition());
267         }
268       } catch (ReplicationException e) {
269         this.terminate("Couldn't get the position of this recovered queue " +
270             this.peerClusterZnode, e);
271       }
272     }
273     // Loop until we close down
274     while (isActive()) {
275       // Sleep until replication is enabled again
276       if (!isPeerEnabled()) {
277         if (sleepForRetries("Replication is disabled", sleepMultiplier)) {
278           sleepMultiplier++;
279         }
280         continue;
281       }
282       Path oldPath = getCurrentPath(); //note that in the current scenario,
283                                        //oldPath will be null when a log roll
284                                        //happens.
285       // Get a new path
286       boolean hasCurrentPath = getNextPath();
287       if (getCurrentPath() != null && oldPath == null) {
288         sleepMultiplier = 1; //reset the sleepMultiplier on a path change
289       }
290       if (!hasCurrentPath) {
291         if (sleepForRetries("No log to process", sleepMultiplier)) {
292           sleepMultiplier++;
293         }
294         continue;
295       }
296       boolean currentWALisBeingWrittenTo = false;
297       //For WAL files we own (rather than recovered), take a snapshot of whether the
298       //current WAL file (this.currentPath) is in use (for writing) NOW!
299       //Since the new WAL paths are enqueued only after the prev WAL file
300       //is 'closed', presence of an element in the queue means that
301       //the previous WAL file was closed, else the file is in use (currentPath)
302       //We take the snapshot now so that we are protected against races
303       //where a new file gets enqueued while the current file is being processed
304       //(and where we just finished reading the current file).
305       if (!this.replicationQueueInfo.isQueueRecovered() && queue.size() == 0) {
306         currentWALisBeingWrittenTo = true;
307       }
308       // Open a reader on it
309       if (!openReader(sleepMultiplier)) {
310         // Reset the sleep multiplier, else it'd be reused for the next file
311         sleepMultiplier = 1;
312         continue;
313       }
314 
315       // If we got a null reader but didn't continue, then sleep and continue
316       if (this.reader == null) {
317         if (sleepForRetries("Unable to open a reader", sleepMultiplier)) {
318           sleepMultiplier++;
319         }
320         continue;
321       }
322 
323       boolean gotIOE = false;
324       currentNbOperations = 0;
325       List<HLog.Entry> entries = new ArrayList<HLog.Entry>(1);
326       currentSize = 0;
327       try {
328         if (readAllEntriesToReplicateOrNextFile(currentWALisBeingWrittenTo, entries)) {
329           continue;
330         }
331       } catch (IOException ioe) {
332         LOG.warn(this.peerClusterZnode + " Got: ", ioe);
333         gotIOE = true;
334         if (ioe.getCause() instanceof EOFException) {
335 
336           boolean considerDumping = false;
337           if (this.replicationQueueInfo.isQueueRecovered()) {
338             try {
339               FileStatus stat = this.fs.getFileStatus(this.currentPath);
340               if (stat.getLen() == 0) {
341                 LOG.warn(this.peerClusterZnode + " Got EOF and the file was empty");
342               }
343               considerDumping = true;
344             } catch (IOException e) {
345               LOG.warn(this.peerClusterZnode + " Got while getting file size: ", e);
346             }
347           }
348 
349           if (considerDumping &&
350               sleepMultiplier == this.maxRetriesMultiplier &&
351               processEndOfFile()) {
352             continue;
353           }
354         }
355       } finally {
356         try {
357           this.reader = null;
358           this.repLogReader.closeReader();
359         } catch (IOException e) {
360           gotIOE = true;
361           LOG.warn("Unable to finalize the tailing of a file", e);
362         }
363       }
364 
365       // If we didn't get anything to replicate, or if we hit a IOE,
366       // wait a bit and retry.
367       // But if we need to stop, don't bother sleeping
368       if (this.isActive() && (gotIOE || entries.isEmpty())) {
369         if (this.lastLoggedPosition != this.repLogReader.getPosition()) {
370           this.manager.logPositionAndCleanOldLogs(this.currentPath,
371               this.peerClusterZnode, this.repLogReader.getPosition(),
372               this.replicationQueueInfo.isQueueRecovered(), currentWALisBeingWrittenTo);
373           this.lastLoggedPosition = this.repLogReader.getPosition();
374         }
375         // Reset the sleep multiplier if nothing has actually gone wrong
376         if (!gotIOE) {
377           sleepMultiplier = 1;
378         }
379         if (sleepForRetries("Nothing to replicate", sleepMultiplier)) {
380           sleepMultiplier++;
381         }
382         continue;
383       }
384       sleepMultiplier = 1;
385       shipEdits(currentWALisBeingWrittenTo, entries);
386     }
387     uninitialize();
388   }
389 
390   /**
391    * Read all the entries from the current log files and retain those
392    * that need to be replicated. Else, process the end of the current file.
393    * @param currentWALisBeingWrittenTo is the current WAL being written to
394    * @param entries resulting entries to be replicated
395    * @return true if we got nothing and went to the next file, false if we got
396    * entries
397    * @throws IOException
398    */
399   protected boolean readAllEntriesToReplicateOrNextFile(boolean currentWALisBeingWrittenTo, List<HLog.Entry> entries)
400       throws IOException{
401     long seenEntries = 0;
402     if (LOG.isTraceEnabled()) {
403       LOG.trace("Seeking in " + this.currentPath + " at position "
404           + this.repLogReader.getPosition());
405     }
406     this.repLogReader.seek();
407     long positionBeforeRead = this.repLogReader.getPosition();
408     HLog.Entry entry =
409         this.repLogReader.readNextAndSetPosition();
410     while (entry != null) {
411       WALEdit edit = entry.getEdit();
412       this.metrics.incrLogEditsRead();
413       seenEntries++;
414       // Remove all KVs that should not be replicated
415       HLogKey logKey = entry.getKey();
416       // don't replicate if the log entries have already been consumed by the cluster
417       if (!logKey.getClusterIds().contains(peerClusterId)) {
418         removeNonReplicableEdits(entry);
419         // Don't replicate catalog entries, if the WALEdit wasn't
420         // containing anything to replicate and if we're currently not set to replicate
421         if (!logKey.getTablename().equals(TableName.META_TABLE_NAME) &&
422             edit.size() != 0) {
423           //Mark that the current cluster has the change
424           logKey.addClusterId(clusterId);
425           currentNbOperations += countDistinctRowKeys(edit);
426           entries.add(entry);
427           currentSize += entry.getEdit().heapSize();
428         } else {
429           this.metrics.incrLogEditsFiltered();
430         }
431       }
432       // Stop if too many entries or too big
433       if (currentSize >= this.replicationQueueSizeCapacity ||
434           entries.size() >= this.replicationQueueNbCapacity) {
435         break;
436       }
437       try {
438         entry = this.repLogReader.readNextAndSetPosition();
439       } catch (IOException ie) {
440         LOG.debug("Break on IOE: " + ie.getMessage());
441         break;
442       }
443     }
444     metrics.incrLogReadInBytes(this.repLogReader.getPosition() - positionBeforeRead);
445     if (currentWALisBeingWrittenTo) {
446       return false;
447     }
448     // If we didn't get anything and the queue has an object, it means we
449     // hit the end of the file for sure
450     return seenEntries == 0 && processEndOfFile();
451   }
452 
453   private void connectToPeers() {
454     int sleepMultiplier = 1;
455 
456     // Connect to peer cluster first, unless we have to stop
457     while (this.isActive() && replicationSinkMgr.getSinks().size() == 0) {
458       replicationSinkMgr.chooseSinks();
459       if (this.isActive() && replicationSinkMgr.getSinks().size() == 0) {
460         if (sleepForRetries("Waiting for peers", sleepMultiplier)) {
461           sleepMultiplier++;
462         }
463       }
464     }
465   }
466 
467   /**
468    * Poll for the next path
469    * @return true if a path was obtained, false if not
470    */
471   protected boolean getNextPath() {
472     try {
473       if (this.currentPath == null) {
474         this.currentPath = queue.poll(this.sleepForRetries, TimeUnit.MILLISECONDS);
475         this.metrics.setSizeOfLogQueue(queue.size());
476         if (this.currentPath != null) {
477           this.manager.cleanOldLogs(this.currentPath.getName(),
478               this.peerId,
479               this.replicationQueueInfo.isQueueRecovered());
480           if (LOG.isTraceEnabled()) {
481             LOG.trace("New log: " + this.currentPath);
482           }
483         }
484       }
485     } catch (InterruptedException e) {
486       LOG.warn("Interrupted while reading edits", e);
487     }
488     return this.currentPath != null;
489   }
490 
491   /**
492    * Open a reader on the current path
493    *
494    * @param sleepMultiplier by how many times the default sleeping time is augmented
495    * @return true if we should continue with that file, false if we are over with it
496    */
497   protected boolean openReader(int sleepMultiplier) {
498     try {
499       try {
500         if (LOG.isTraceEnabled()) {
501           LOG.trace("Opening log " + this.currentPath);
502         }
503         this.reader = repLogReader.openReader(this.currentPath);
504       } catch (FileNotFoundException fnfe) {
505         if (this.replicationQueueInfo.isQueueRecovered()) {
506           // We didn't find the log in the archive directory, look if it still
507           // exists in the dead RS folder (there could be a chain of failures
508           // to look at)
509           List<String> deadRegionServers = this.replicationQueueInfo.getDeadRegionServers();
510           LOG.info("NB dead servers : " + deadRegionServers.size());
511           for (String curDeadServerName : deadRegionServers) {
512             Path deadRsDirectory =
513                 new Path(manager.getLogDir().getParent(), curDeadServerName);
514             Path[] locs = new Path[] {
515                 new Path(deadRsDirectory, currentPath.getName()),
516                 new Path(deadRsDirectory.suffix(HLog.SPLITTING_EXT),
517                                           currentPath.getName()),
518             };
519             for (Path possibleLogLocation : locs) {
520               LOG.info("Possible location " + possibleLogLocation.toUri().toString());
521               if (this.manager.getFs().exists(possibleLogLocation)) {
522                 // We found the right new location
523                 LOG.info("Log " + this.currentPath + " still exists at " +
524                     possibleLogLocation);
525                 // Breaking here will make us sleep since reader is null
526                 return true;
527               }
528             }
529           }
530           // In the case of disaster/recovery, HMaster may be shutdown/crashed before flush data
531           // from .logs to .oldlogs. Loop into .logs folders and check whether a match exists
532           if (stopper instanceof ReplicationSyncUp.DummyServer) {
533             FileStatus[] rss = fs.listStatus(manager.getLogDir());
534             for (FileStatus rs : rss) {
535               Path p = rs.getPath();
536               FileStatus[] logs = fs.listStatus(p);
537               for (FileStatus log : logs) {
538                 p = new Path(p, log.getPath().getName());
539                 if (p.getName().equals(currentPath.getName())) {
540                   currentPath = p;
541                   LOG.info("Log " + this.currentPath + " exists under " + manager.getLogDir());
542                   // Open the log at the new location
543                   this.openReader(sleepMultiplier);
544                   return true;
545                 }
546               }
547             }
548           }
549 
550           // TODO What happens if the log was missing from every single location?
551           // Although we need to check a couple of times as the log could have
552           // been moved by the master between the checks
553           // It can also happen if a recovered queue wasn't properly cleaned,
554           // such that the znode pointing to a log exists but the log was
555           // deleted a long time ago.
556           // For the moment, we'll throw the IO and processEndOfFile
557           throw new IOException("File from recovered queue is " +
558               "nowhere to be found", fnfe);
559         } else {
560           // If the log was archived, continue reading from there
561           Path archivedLogLocation =
562               new Path(manager.getOldLogDir(), currentPath.getName());
563           if (this.manager.getFs().exists(archivedLogLocation)) {
564             currentPath = archivedLogLocation;
565             LOG.info("Log " + this.currentPath + " was moved to " +
566                 archivedLogLocation);
567             // Open the log at the new location
568             this.openReader(sleepMultiplier);
569 
570           }
571           // TODO What happens the log is missing in both places?
572         }
573       }
574     } catch (IOException ioe) {
575       if (ioe instanceof EOFException && isCurrentLogEmpty()) return true;
576       LOG.warn(this.peerClusterZnode + " Got: ", ioe);
577       this.reader = null;
578       if (ioe.getCause() instanceof NullPointerException) {
579         // Workaround for race condition in HDFS-4380
580         // which throws a NPE if we open a file before any data node has the most recent block
581         // Just sleep and retry. Will require re-reading compressed HLogs for compressionContext.
582         LOG.warn("Got NPE opening reader, will retry.");
583       } else if (sleepMultiplier == this.maxRetriesMultiplier) {
584         // TODO Need a better way to determine if a file is really gone but
585         // TODO without scanning all logs dir
586         LOG.warn("Waited too long for this file, considering dumping");
587         return !processEndOfFile();
588       }
589     }
590     return true;
591   }
592 
593   /*
594    * Checks whether the current log file is empty, and it is not a recovered queue. This is to
595    * handle scenario when in an idle cluster, there is no entry in the current log and we keep on
596    * trying to read the log file and get EOFEception. In case of a recovered queue the last log file
597    * may be empty, and we don't want to retry that.
598    */
599   private boolean isCurrentLogEmpty() {
600     return (this.repLogReader.getPosition() == 0 &&
601         !this.replicationQueueInfo.isQueueRecovered() && queue.size() == 0);
602   }
603 
604   /**
605    * Do the sleeping logic
606    * @param msg Why we sleep
607    * @param sleepMultiplier by how many times the default sleeping time is augmented
608    * @return True if <code>sleepMultiplier</code> is &lt; <code>maxRetriesMultiplier</code>
609    */
610   protected boolean sleepForRetries(String msg, int sleepMultiplier) {
611     try {
612       if (LOG.isTraceEnabled()) {
613         LOG.trace(msg + ", sleeping " + sleepForRetries + " times " + sleepMultiplier);
614       }
615       Thread.sleep(this.sleepForRetries * sleepMultiplier);
616     } catch (InterruptedException e) {
617       LOG.debug("Interrupted while sleeping between retries");
618       Thread.currentThread().interrupt();
619     }
620     return sleepMultiplier < maxRetriesMultiplier;
621   }
622 
623   /**
624    * We only want KVs that are scoped other than local
625    * @param entry The entry to check for replication
626    */
627   protected void removeNonReplicableEdits(HLog.Entry entry) {
628     String tabName = entry.getKey().getTablename().getNameAsString();
629     ArrayList<KeyValue> kvs = entry.getEdit().getKeyValues();
630     Map<String, List<String>> tableCFs = null;
631     try {
632       tableCFs = this.replicationPeers.getTableCFs(peerId);
633     } catch (IllegalArgumentException e) {
634       LOG.error("should not happen: can't get tableCFs for peer " + peerId +
635           ", degenerate as if it's not configured by keeping tableCFs==null");
636     }
637     int size = kvs.size();
638 
639     // clear kvs(prevent replicating) if logKey's table isn't in this peer's
640     // replicable table list (empty tableCFs means all table are replicable)
641     if (tableCFs != null && !tableCFs.containsKey(tabName)) {
642       kvs.clear();
643     } else {
644       NavigableMap<byte[], Integer> scopes = entry.getKey().getScopes();
645       List<String> cfs = (tableCFs == null) ? null : tableCFs.get(tabName);
646       for (int i = size - 1; i >= 0; i--) {
647         KeyValue kv = kvs.get(i);
648         // The scope will be null or empty if
649         // there's nothing to replicate in that WALEdit
650         // ignore(remove) kv if its cf isn't in the replicable cf list
651         // (empty cfs means all cfs of this table are replicable)
652         if (scopes == null || !scopes.containsKey(kv.getFamily()) ||
653             (cfs != null && !cfs.contains(Bytes.toString(kv.getFamily())))) {
654           kvs.remove(i);
655         }
656       }
657     }
658 
659     if (kvs.size() < size/2) {
660       kvs.trimToSize();
661     }
662   }
663 
664   /**
665    * Count the number of different row keys in the given edit because of
666    * mini-batching. We assume that there's at least one KV in the WALEdit.
667    * @param edit edit to count row keys from
668    * @return number of different row keys
669    */
670   private int countDistinctRowKeys(WALEdit edit) {
671     List<KeyValue> kvs = edit.getKeyValues();
672     int distinctRowKeys = 1;
673     KeyValue lastKV = kvs.get(0);
674     for (int i = 0; i < edit.size(); i++) {
675       if (!kvs.get(i).matchingRow(lastKV)) {
676         distinctRowKeys++;
677       }
678     }
679     return distinctRowKeys;
680   }
681 
682   /**
683    * Do the shipping logic
684    * @param currentWALisBeingWrittenTo was the current WAL being (seemingly)
685    * written to when this method was called
686    */
687   protected void shipEdits(boolean currentWALisBeingWrittenTo, List<HLog.Entry> entries) {
688     int sleepMultiplier = 1;
689     if (entries.isEmpty()) {
690       LOG.warn("Was given 0 edits to ship");
691       return;
692     }
693     while (this.isActive()) {
694       if (!isPeerEnabled()) {
695         if (sleepForRetries("Replication is disabled", sleepMultiplier)) {
696           sleepMultiplier++;
697         }
698         continue;
699       }
700       SinkPeer sinkPeer = null;
701       try {
702         if (this.throttler.isEnabled()) {
703           long sleepTicks = this.throttler.getNextSleepInterval(currentSize);
704           if (sleepTicks > 0) {
705             try {
706               if (LOG.isTraceEnabled()) {
707                 LOG.trace("To sleep " + sleepTicks + "ms for throttling control");
708               }
709               Thread.sleep(sleepTicks);
710             } catch (InterruptedException e) {
711               LOG.debug("Interrupted while sleeping for throttling control");
712               Thread.currentThread().interrupt();
713               // current thread might be interrupted to terminate
714               // directly go back to while() for confirm this
715               continue;
716             }
717             // reset throttler's cycle start tick when sleep for throttling occurs
718             this.throttler.resetStartTick();
719           }
720         }
721         sinkPeer = replicationSinkMgr.getReplicationSink();
722         BlockingInterface rrs = sinkPeer.getRegionServer();
723         if (LOG.isTraceEnabled()) {
724           LOG.trace("Replicating " + entries.size() +
725               " entries of total size " + currentSize);
726         }
727         ReplicationProtbufUtil.replicateWALEntry(rrs,
728             entries.toArray(new HLog.Entry[entries.size()]));
729         if (this.lastLoggedPosition != this.repLogReader.getPosition()) {
730           this.manager.logPositionAndCleanOldLogs(this.currentPath,
731               this.peerClusterZnode, this.repLogReader.getPosition(),
732               this.replicationQueueInfo.isQueueRecovered(), currentWALisBeingWrittenTo);
733           this.lastLoggedPosition = this.repLogReader.getPosition();
734         }
735         if (this.throttler.isEnabled()) {
736           this.throttler.addPushSize(currentSize);
737         }
738         this.totalReplicatedEdits += entries.size();
739         this.totalReplicatedOperations += currentNbOperations;
740         this.metrics.shipBatch(this.currentNbOperations);
741         this.metrics.setAgeOfLastShippedOp(entries.get(entries.size()-1).getKey().getWriteTime());
742         if (LOG.isTraceEnabled()) {
743           LOG.trace("Replicated " + this.totalReplicatedEdits + " entries in total, or "
744               + this.totalReplicatedOperations + " operations");
745         }
746         break;
747 
748       } catch (IOException ioe) {
749         // Didn't ship anything, but must still age the last time we did
750         this.metrics.refreshAgeOfLastShippedOp();
751         if (ioe instanceof RemoteException) {
752           ioe = ((RemoteException) ioe).unwrapRemoteException();
753           LOG.warn("Can't replicate because of an error on the remote cluster: ", ioe);
754           if (ioe instanceof TableNotFoundException) {
755             if (sleepForRetries("A table is missing in the peer cluster. "
756                 + "Replication cannot proceed without losing data.", sleepMultiplier)) {
757               sleepMultiplier++;
758             }
759             // current thread might be interrupted to terminate
760             // directly go back to while() for confirm this
761             if (isInterrupted()) {
762               continue;
763             }
764           }
765         } else {
766           if (ioe instanceof SocketTimeoutException) {
767             // This exception means we waited for more than 60s and nothing
768             // happened, the cluster is alive and calling it right away
769             // even for a test just makes things worse.
770             sleepForRetries("Encountered a SocketTimeoutException. Since the " +
771               "call to the remote cluster timed out, which is usually " +
772               "caused by a machine failure or a massive slowdown",
773               this.socketTimeoutMultiplier);
774             // current thread might be interrupted to terminate
775             // directly go back to while() for confirm this
776             if (isInterrupted()) {
777               continue;
778             }
779           } else if (ioe instanceof ConnectException) {
780             LOG.warn("Peer is unavailable, rechecking all sinks: ", ioe);
781             replicationSinkMgr.chooseSinks();
782           } else {
783             LOG.warn("Can't replicate because of a local or network error: ", ioe);
784           }
785         }
786 
787         if (sinkPeer != null) {
788           replicationSinkMgr.reportBadSink(sinkPeer);
789         }
790         if (sleepForRetries("Since we are unable to replicate", sleepMultiplier)) {
791           sleepMultiplier++;
792         }
793       }
794     }
795   }
796 
797   /**
798    * check whether the peer is enabled or not
799    *
800    * @return true if the peer is enabled, otherwise false
801    */
802   protected boolean isPeerEnabled() {
803     return this.replicationPeers.getStatusOfConnectedPeer(this.peerId);
804   }
805 
806   /**
807    * If the queue isn't empty, switch to the next one
808    * Else if this is a recovered queue, it means we're done!
809    * Else we'll just continue to try reading the log file
810    * @return true if we're done with the current file, false if we should
811    * continue trying to read from it
812    */
813   protected boolean processEndOfFile() {
814     if (this.queue.size() != 0) {
815       if (LOG.isTraceEnabled()) {
816         String filesize = "N/A";
817         try {
818           FileStatus stat = this.fs.getFileStatus(this.currentPath);
819           filesize = stat.getLen()+"";
820         } catch (IOException ex) {}
821         LOG.trace("Reached the end of a log, stats: " + getStats() +
822             ", and the length of the file is " + filesize);
823       }
824       this.currentPath = null;
825       this.repLogReader.finishCurrentFile();
826       this.reader = null;
827       return true;
828     } else if (this.replicationQueueInfo.isQueueRecovered()) {
829       this.manager.closeRecoveredQueue(this);
830       LOG.info("Finished recovering the queue with the following stats " + getStats());
831       this.running = false;
832       return true;
833     }
834     return false;
835   }
836 
837   public void startup() {
838     String n = Thread.currentThread().getName();
839     Thread.UncaughtExceptionHandler handler =
840         new Thread.UncaughtExceptionHandler() {
841           public void uncaughtException(final Thread t, final Throwable e) {
842             LOG.error("Unexpected exception in ReplicationSource," +
843               " currentPath=" + currentPath, e);
844           }
845         };
846     Threads.setDaemonThreadRunning(
847         this, n + ".replicationSource," +
848         this.peerClusterZnode, handler);
849   }
850 
851   public void terminate(String reason) {
852     terminate(reason, null);
853   }
854 
855   public void terminate(String reason, Exception cause) {
856     if (cause == null) {
857       LOG.info("Closing source "
858           + this.peerClusterZnode + " because: " + reason);
859 
860     } else {
861       LOG.error("Closing source " + this.peerClusterZnode
862           + " because an error occurred: " + reason, cause);
863     }
864     this.running = false;
865     this.interrupt();
866     Threads.shutdown(this, this.sleepForRetries * this.maxRetriesMultiplier);
867   }
868 
869   public String getPeerClusterZnode() {
870     return this.peerClusterZnode;
871   }
872 
873   public String getPeerClusterId() {
874     return this.peerId;
875   }
876 
877   public Path getCurrentPath() {
878     return this.currentPath;
879   }
880 
881   private boolean isActive() {
882     return !this.stopper.isStopped() && this.running && !isInterrupted();
883   }
884 
885   /**
886    * Comparator used to compare logs together based on their start time
887    */
888   public static class LogsComparator implements Comparator<Path> {
889 
890     @Override
891     public int compare(Path o1, Path o2) {
892       return Long.valueOf(getTS(o1)).compareTo(getTS(o2));
893     }
894 
895     /**
896      * Split a path to get the start time
897      * For example: 10.20.20.171%3A60020.1277499063250
898      * @param p path to split
899      * @return start time
900      */
901     private long getTS(Path p) {
902       String[] parts = p.getName().split("\\.");
903       return Long.parseLong(parts[parts.length-1]);
904     }
905   }
906 
907   @Override
908   public String getStats() {
909     long position = this.repLogReader.getPosition();
910     return "Total replicated edits: " + totalReplicatedEdits +
911       ", currently replicating from: " + this.currentPath +
912       " at position: " + position;
913   }
914 }