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