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  
20  package org.apache.hadoop.hbase.replication.regionserver;
21  
22  import com.google.common.annotations.VisibleForTesting;
23  import com.google.common.util.concurrent.ThreadFactoryBuilder;
24  
25  import java.io.IOException;
26  import java.util.ArrayList;
27  import java.util.Collections;
28  import java.util.HashMap;
29  import java.util.HashSet;
30  import java.util.Iterator;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.Random;
34  import java.util.Set;
35  import java.util.SortedSet;
36  import java.util.TreeSet;
37  import java.util.UUID;
38  import java.util.concurrent.ConcurrentHashMap;
39  import java.util.concurrent.CopyOnWriteArrayList;
40  import java.util.concurrent.LinkedBlockingQueue;
41  import java.util.concurrent.RejectedExecutionException;
42  import java.util.concurrent.ThreadPoolExecutor;
43  import java.util.concurrent.TimeUnit;
44  
45  import org.apache.commons.logging.Log;
46  import org.apache.commons.logging.LogFactory;
47  import org.apache.hadoop.conf.Configuration;
48  import org.apache.hadoop.fs.FileSystem;
49  import org.apache.hadoop.fs.Path;
50  import org.apache.hadoop.hbase.HConstants;
51  import org.apache.hadoop.hbase.Server;
52  import org.apache.hadoop.hbase.TableDescriptors;
53  import org.apache.hadoop.hbase.TableName;
54  import org.apache.hadoop.hbase.classification.InterfaceAudience;
55  import org.apache.hadoop.hbase.regionserver.HRegionServer;
56  import org.apache.hadoop.hbase.regionserver.RegionServerCoprocessorHost;
57  import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
58  import org.apache.hadoop.hbase.replication.ReplicationException;
59  import org.apache.hadoop.hbase.replication.ReplicationListener;
60  import org.apache.hadoop.hbase.replication.ReplicationPeer;
61  import org.apache.hadoop.hbase.replication.ReplicationPeer.PeerState;
62  import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
63  import org.apache.hadoop.hbase.replication.ReplicationPeers;
64  import org.apache.hadoop.hbase.replication.ReplicationQueueInfo;
65  import org.apache.hadoop.hbase.replication.ReplicationQueues;
66  import org.apache.hadoop.hbase.replication.ReplicationTracker;
67  import org.apache.hadoop.hbase.util.Pair;
68  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
69  
70  /**
71   * This class is responsible to manage all the replication
72   * sources. There are two classes of sources:
73   * <ul>
74   * <li> Normal sources are persistent and one per peer cluster</li>
75   * <li> Old sources are recovered from a failed region server and our
76   * only goal is to finish replicating the WAL queue it had up in ZK</li>
77   * </ul>
78   *
79   * When a region server dies, this class uses a watcher to get notified and it
80   * tries to grab a lock in order to transfer all the queues in a local
81   * old source.
82   *
83   * This class implements the ReplicationListener interface so that it can track changes in
84   * replication state.
85   */
86  @InterfaceAudience.Private
87  public class ReplicationSourceManager implements ReplicationListener {
88    private static final Log LOG =
89        LogFactory.getLog(ReplicationSourceManager.class);
90    // List of all the sources that read this RS's logs
91    private final List<ReplicationSourceInterface> sources;
92    // List of all the sources we got from died RSs
93    private final List<ReplicationSourceInterface> oldsources;
94    private final ReplicationQueues replicationQueues;
95    private final ReplicationTracker replicationTracker;
96    private final ReplicationPeers replicationPeers;
97    // UUID for this cluster
98    private final UUID clusterId;
99    // All about stopping
100   private final Server server;
101   // All logs we are currently tracking
102   // Index structure of the map is: peer_id->logPrefix/logGroup->logs
103   private final Map<String, Map<String, SortedSet<String>>> walsById;
104   // Logs for recovered sources we are currently tracking
105   private final Map<String, Map<String, SortedSet<String>>> walsByIdRecoveredQueues;
106   private final Configuration conf;
107   private final FileSystem fs;
108   // The paths to the latest log of each wal group, for new coming peers
109   private Set<Path> latestPaths;
110   // Path to the wals directories
111   private final Path logDir;
112   // Path to the wal archive
113   private final Path oldLogDir;
114   // The number of ms that we wait before moving znodes, HBASE-3596
115   private final long sleepBeforeFailover;
116   // Homemade executer service for replication
117   private final ThreadPoolExecutor executor;
118 
119   private final Random rand;
120   private final boolean replicationForBulkLoadDataEnabled;
121 
122 
123   /**
124    * Creates a replication manager and sets the watch on all the other registered region servers
125    * @param replicationQueues the interface for manipulating replication queues
126    * @param replicationPeers
127    * @param replicationTracker
128    * @param conf the configuration to use
129    * @param server the server for this region server
130    * @param fs the file system to use
131    * @param logDir the directory that contains all wal directories of live RSs
132    * @param oldLogDir the directory where old logs are archived
133    * @param clusterId
134    */
135   public ReplicationSourceManager(final ReplicationQueues replicationQueues,
136       final ReplicationPeers replicationPeers, final ReplicationTracker replicationTracker,
137       final Configuration conf, final Server server, final FileSystem fs, final Path logDir,
138       final Path oldLogDir, final UUID clusterId) {
139     //CopyOnWriteArrayList is thread-safe.
140     //Generally, reading is more than modifying.
141     this.sources = new CopyOnWriteArrayList<ReplicationSourceInterface>();
142     this.replicationQueues = replicationQueues;
143     this.replicationPeers = replicationPeers;
144     this.replicationTracker = replicationTracker;
145     this.server = server;
146     this.walsById = new HashMap<String, Map<String, SortedSet<String>>>();
147     this.walsByIdRecoveredQueues = new ConcurrentHashMap<String, Map<String, SortedSet<String>>>();
148     this.oldsources = new CopyOnWriteArrayList<ReplicationSourceInterface>();
149     this.conf = conf;
150     this.fs = fs;
151     this.logDir = logDir;
152     this.oldLogDir = oldLogDir;
153     this.sleepBeforeFailover =
154         conf.getLong("replication.sleep.before.failover", 30000); // 30 seconds
155     this.clusterId = clusterId;
156     this.replicationTracker.registerListener(this);
157     this.replicationPeers.getAllPeerIds();
158     // It's preferable to failover 1 RS at a time, but with good zk servers
159     // more could be processed at the same time.
160     int nbWorkers = conf.getInt("replication.executor.workers", 1);
161     // use a short 100ms sleep since this could be done inline with a RS startup
162     // even if we fail, other region servers can take care of it
163     this.executor = new ThreadPoolExecutor(nbWorkers, nbWorkers,
164         100, TimeUnit.MILLISECONDS,
165         new LinkedBlockingQueue<Runnable>());
166     ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
167     tfb.setNameFormat("ReplicationExecutor-%d");
168     tfb.setDaemon(true);
169     this.executor.setThreadFactory(tfb.build());
170     this.rand = new Random();
171     this.latestPaths = Collections.synchronizedSet(new HashSet<Path>());
172     replicationForBulkLoadDataEnabled =
173         conf.getBoolean(HConstants.REPLICATION_BULKLOAD_ENABLE_KEY,
174           HConstants.REPLICATION_BULKLOAD_ENABLE_DEFAULT);
175   }
176 
177   /**
178    * Provide the id of the peer and a log key and this method will figure which
179    * wal it belongs to and will log, for this region server, the current
180    * position. It will also clean old logs from the queue.
181    * @param log Path to the log currently being replicated from
182    * replication status in zookeeper. It will also delete older entries.
183    * @param id id of the peer cluster
184    * @param position current location in the log
185    * @param queueRecovered indicates if this queue comes from another region server
186    * @param holdLogInZK if true then the log is retained in ZK
187    */
188   public void logPositionAndCleanOldLogs(Path log, String id, long position,
189       boolean queueRecovered, boolean holdLogInZK) {
190     String fileName = log.getName();
191     this.replicationQueues.setLogPosition(id, fileName, position);
192     if (holdLogInZK) {
193      return;
194     }
195     cleanOldLogs(fileName, id, queueRecovered);
196   }
197 
198   /**
199    * Cleans a log file and all older files from ZK. Called when we are sure that a
200    * log file is closed and has no more entries.
201    * @param key Path to the log
202    * @param id id of the peer cluster
203    * @param queueRecovered Whether this is a recovered queue
204    */
205   public void cleanOldLogs(String key, String id, boolean queueRecovered) {
206     String logPrefix = DefaultWALProvider.getWALPrefixFromWALName(key);
207     if (queueRecovered) {
208       SortedSet<String> wals = walsByIdRecoveredQueues.get(id).get(logPrefix);
209       if (wals != null && !wals.first().equals(key)) {
210         cleanOldLogs(wals, key, id);
211       }
212     } else {
213       synchronized (this.walsById) {
214         SortedSet<String> wals = walsById.get(id).get(logPrefix);
215         if (wals != null && !wals.first().equals(key)) {
216           cleanOldLogs(wals, key, id);
217         }
218       }
219     }
220  }
221 
222   private void cleanOldLogs(SortedSet<String> wals, String key, String id) {
223     SortedSet<String> walSet = wals.headSet(key);
224     LOG.debug("Removing " + walSet.size() + " logs in the list: " + walSet);
225     for (String wal : walSet) {
226       this.replicationQueues.removeLog(id, wal);
227     }
228     walSet.clear();
229   }
230 
231   /**
232    * Adds a normal source per registered peer cluster and tries to process all
233    * old region server wal queues
234    */
235   protected void init() throws IOException, ReplicationException {
236     for (String id : this.replicationPeers.getPeerIds()) {
237       addSource(id);
238       if (replicationForBulkLoadDataEnabled) {
239         // Check if peer exists in hfile-refs queue, if not add it. This can happen in the case
240         // when a peer was added before replication for bulk loaded data was enabled.
241         this.replicationQueues.addPeerToHFileRefs(id);
242       }
243     }
244     List<String> currentReplicators = this.replicationQueues.getListOfReplicators();
245     if (currentReplicators == null || currentReplicators.isEmpty()) {
246       return;
247     }
248     List<String> otherRegionServers = replicationTracker.getListOfRegionServers();
249     LOG.info("Current list of replicators: " + currentReplicators + " other RSs: "
250         + otherRegionServers);
251 
252     // Look if there's anything to process after a restart
253     for (String rs : currentReplicators) {
254       if (!otherRegionServers.contains(rs)) {
255         transferQueues(rs);
256       }
257     }
258   }
259 
260   /**
261    * Add sources for the given peer cluster on this region server. For the newly added peer, we only
262    * need to enqueue the latest log of each wal group and do replication
263    * @param id the id of the peer cluster
264    * @return the source that was created
265    * @throws IOException
266    */
267   protected ReplicationSourceInterface addSource(String id) throws IOException,
268       ReplicationException {
269     ReplicationPeerConfig peerConfig = replicationPeers.getReplicationPeerConfig(id);
270     ReplicationPeer peer = replicationPeers.getPeer(id);
271     ReplicationSourceInterface src =
272         getReplicationSource(this.conf, this.fs, this, this.replicationQueues,
273           this.replicationPeers, server, id, this.clusterId, peerConfig, peer);
274     synchronized (this.walsById) {
275       this.sources.add(src);
276       Map<String, SortedSet<String>> walsByGroup = new HashMap<String, SortedSet<String>>();
277       this.walsById.put(id, walsByGroup);
278       // Add the latest wal to that source's queue
279       synchronized (latestPaths) {
280         if (this.latestPaths.size() > 0) {
281           for (Path logPath : latestPaths) {
282             String name = logPath.getName();
283             String walPrefix = DefaultWALProvider.getWALPrefixFromWALName(name);
284             SortedSet<String> logs = new TreeSet<String>();
285             logs.add(name);
286             walsByGroup.put(walPrefix, logs);
287             try {
288               this.replicationQueues.addLog(id, name);
289             } catch (ReplicationException e) {
290               String message =
291                   "Cannot add log to queue when creating a new source, queueId=" + id
292                       + ", filename=" + name;
293               server.stop(message);
294               throw e;
295             }
296             src.enqueueLog(logPath);
297           }
298         }
299       }
300     }
301     src.startup();
302     return src;
303   }
304 
305   /**
306    * Delete a complete queue of wals associated with a peer cluster
307    * @param peerId Id of the peer cluster queue of wals to delete
308    */
309   public void deleteSource(String peerId, boolean closeConnection) {
310     this.replicationQueues.removeQueue(peerId);
311     if (closeConnection) {
312       this.replicationPeers.peerRemoved(peerId);
313     }
314   }
315 
316   /**
317    * Terminate the replication on this region server
318    */
319   public void join() {
320     this.executor.shutdown();
321     if (this.sources.size() == 0) {
322       this.replicationQueues.removeAllQueues();
323     }
324     for (ReplicationSourceInterface source : this.sources) {
325       source.terminate("Region server is closing");
326     }
327   }
328 
329   /**
330    * Get a copy of the wals of the first source on this rs
331    * @return a sorted set of wal names
332    */
333   protected Map<String, Map<String, SortedSet<String>>> getWALs() {
334     return Collections.unmodifiableMap(walsById);
335   }
336 
337   /**
338    * Get a copy of the wals of the recovered sources on this rs
339    * @return a sorted set of wal names
340    */
341   protected Map<String, Map<String, SortedSet<String>>> getWalsByIdRecoveredQueues() {
342     return Collections.unmodifiableMap(walsByIdRecoveredQueues);
343   }
344 
345   /**
346    * Get a list of all the normal sources of this rs
347    * @return lis of all sources
348    */
349   public List<ReplicationSourceInterface> getSources() {
350     return this.sources;
351   }
352 
353   /**
354    * Get a list of all the old sources of this rs
355    * @return list of all old sources
356    */
357   public List<ReplicationSourceInterface> getOldSources() {
358     return this.oldsources;
359   }
360 
361   /**
362    * Get the normal source for a given peer
363    * @param peerId
364    * @return the normal source for the give peer if it exists, otherwise null.
365    */
366   public ReplicationSourceInterface getSource(String peerId) {
367     for (ReplicationSourceInterface source: getSources()) {
368       if (source.getPeerClusterId().equals(peerId)) {
369         return source;
370       }
371     }
372     return null;
373   }
374 
375   @VisibleForTesting
376   List<String> getAllQueues() {
377     return replicationQueues.getAllQueues();
378   }
379 
380   void preLogRoll(Path newLog) throws IOException {
381     recordLog(newLog);
382     String logName = newLog.getName();
383     String logPrefix = DefaultWALProvider.getWALPrefixFromWALName(logName);
384     synchronized (latestPaths) {
385       Iterator<Path> iterator = latestPaths.iterator();
386       while (iterator.hasNext()) {
387         Path path = iterator.next();
388         if (path.getName().contains(logPrefix)) {
389           iterator.remove();
390           break;
391         }
392       }
393       this.latestPaths.add(newLog);
394     }
395   }
396 
397   /**
398    * Check and enqueue the given log to the correct source. If there's still no source for the
399    * group to which the given log belongs, create one
400    * @param logPath the log path to check and enqueue
401    * @throws IOException
402    */
403   private void recordLog(Path logPath) throws IOException {
404     String logName = logPath.getName();
405     String logPrefix = DefaultWALProvider.getWALPrefixFromWALName(logName);
406     // update replication queues on ZK
407     // synchronize on replicationPeers to avoid adding source for the to-be-removed peer
408     synchronized (replicationPeers) {
409       for (String id : replicationPeers.getPeerIds()) {
410         try {
411           this.replicationQueues.addLog(id, logName);
412         } catch (ReplicationException e) {
413           throw new IOException("Cannot add log to replication queue"
414               + " when creating a new source, queueId=" + id + ", filename=" + logName, e);
415         }
416       }
417     }
418     // update walsById map
419     synchronized (walsById) {
420       for (Map.Entry<String, Map<String, SortedSet<String>>> entry : this.walsById.entrySet()) {
421         String peerId = entry.getKey();
422         Map<String, SortedSet<String>> walsByPrefix = entry.getValue();
423         boolean existingPrefix = false;
424         for (Map.Entry<String, SortedSet<String>> walsEntry : walsByPrefix.entrySet()) {
425           SortedSet<String> wals = walsEntry.getValue();
426           if (this.sources.isEmpty()) {
427             // If there's no slaves, don't need to keep the old wals since
428             // we only consider the last one when a new slave comes in
429             wals.clear();
430           }
431           if (logPrefix.equals(walsEntry.getKey())) {
432             wals.add(logName);
433             existingPrefix = true;
434           }
435         }
436         if (!existingPrefix) {
437           // The new log belongs to a new group, add it into this peer
438           LOG.debug("Start tracking logs for wal group " + logPrefix + " for peer " + peerId);
439           SortedSet<String> wals = new TreeSet<String>();
440           wals.add(logName);
441           walsByPrefix.put(logPrefix, wals);
442         }
443       }
444     }
445   }
446 
447   void postLogRoll(Path newLog) throws IOException {
448     // This only updates the sources we own, not the recovered ones
449     for (ReplicationSourceInterface source : this.sources) {
450       source.enqueueLog(newLog);
451     }
452   }
453 
454   /**
455    * Factory method to create a replication source
456    * @param conf the configuration to use
457    * @param fs the file system to use
458    * @param manager the manager to use
459    * @param server the server object for this region server
460    * @param peerId the id of the peer cluster
461    * @return the created source
462    * @throws IOException
463    */
464   protected ReplicationSourceInterface getReplicationSource(final Configuration conf,
465       final FileSystem fs, final ReplicationSourceManager manager,
466       final ReplicationQueues replicationQueues, final ReplicationPeers replicationPeers,
467       final Server server, final String peerId, final UUID clusterId,
468       final ReplicationPeerConfig peerConfig, final ReplicationPeer replicationPeer)
469       throws IOException {
470     RegionServerCoprocessorHost rsServerHost = null;
471     TableDescriptors tableDescriptors = null;
472     if (server instanceof HRegionServer) {
473       rsServerHost = ((HRegionServer) server).getRegionServerCoprocessorHost();
474       tableDescriptors = ((HRegionServer) server).getTableDescriptors();
475     }
476     ReplicationSourceInterface src;
477     try {
478       @SuppressWarnings("rawtypes")
479       Class c = Class.forName(conf.get("replication.replicationsource.implementation",
480           ReplicationSource.class.getCanonicalName()));
481       src = (ReplicationSourceInterface) c.newInstance();
482     } catch (Exception e) {
483       LOG.warn("Passed replication source implementation throws errors, " +
484           "defaulting to ReplicationSource", e);
485       src = new ReplicationSource();
486     }
487 
488     ReplicationEndpoint replicationEndpoint = null;
489     try {
490       String replicationEndpointImpl = peerConfig.getReplicationEndpointImpl();
491       if (replicationEndpointImpl == null) {
492         // Default to HBase inter-cluster replication endpoint
493         replicationEndpointImpl = HBaseInterClusterReplicationEndpoint.class.getName();
494       }
495       @SuppressWarnings("rawtypes")
496       Class c = Class.forName(replicationEndpointImpl);
497       replicationEndpoint = (ReplicationEndpoint) c.newInstance();
498       if(rsServerHost != null) {
499         ReplicationEndpoint newReplicationEndPoint = rsServerHost
500             .postCreateReplicationEndPoint(replicationEndpoint);
501         if(newReplicationEndPoint != null) {
502           // Override the newly created endpoint from the hook with configured end point
503           replicationEndpoint = newReplicationEndPoint;
504         }
505       }
506     } catch (Exception e) {
507       LOG.warn("Passed replication endpoint implementation throws errors"
508           + " while initializing ReplicationSource for peer: " + peerId, e);
509       throw new IOException(e);
510     }
511 
512     MetricsSource metrics = new MetricsSource(peerId);
513     // init replication source
514     src.init(conf, fs, manager, replicationQueues, replicationPeers, server, peerId,
515       clusterId, replicationEndpoint, metrics);
516 
517     // init replication endpoint
518     replicationEndpoint.init(new ReplicationEndpoint.Context(conf, replicationPeer.getConfiguration(),
519       fs, peerId, clusterId, replicationPeer, metrics, tableDescriptors, server));
520 
521     return src;
522   }
523 
524   /**
525    * Transfer all the queues of the specified to this region server.
526    * First it tries to grab a lock and if it works it will move the
527    * znodes and finally will delete the old znodes.
528    *
529    * It creates one old source for any type of source of the old rs.
530    * @param rsZnode
531    */
532   private void transferQueues(String rsZnode) {
533     NodeFailoverWorker transfer =
534         new NodeFailoverWorker(rsZnode, this.replicationQueues, this.replicationPeers,
535             this.clusterId);
536     try {
537       this.executor.execute(transfer);
538     } catch (RejectedExecutionException ex) {
539       LOG.info("Cancelling the transfer of " + rsZnode + " because of " + ex.getMessage());
540     }
541   }
542 
543   /**
544    * Clear the references to the specified old source
545    * @param src source to clear
546    */
547   public void closeRecoveredQueue(ReplicationSourceInterface src) {
548     LOG.info("Done with the recovered queue " + src.getPeerClusterZnode());
549     src.getSourceMetrics().clear();
550     this.oldsources.remove(src);
551     deleteSource(src.getPeerClusterZnode(), false);
552     this.walsByIdRecoveredQueues.remove(src.getPeerClusterZnode());
553   }
554 
555   /**
556    * Clear the references to the specified old source
557    * @param src source to clear
558    */
559   public void closeQueue(ReplicationSourceInterface src) {
560     LOG.info("Done with the queue " + src.getPeerClusterZnode());
561     src.getSourceMetrics().clear();
562     this.sources.remove(src);
563     deleteSource(src.getPeerClusterZnode(), true);
564     this.walsById.remove(src.getPeerClusterZnode());
565   }
566 
567   /**
568    * Thie method first deletes all the recovered sources for the specified
569    * id, then deletes the normal source (deleting all related data in ZK).
570    * @param id The id of the peer cluster
571    */
572   public void removePeer(String id) {
573     LOG.info("Closing the following queue " + id + ", currently have "
574         + sources.size() + " and another "
575         + oldsources.size() + " that were recovered");
576     String terminateMessage = "Replication stream was removed by a user";
577     List<ReplicationSourceInterface> oldSourcesToDelete =
578         new ArrayList<ReplicationSourceInterface>();
579     // synchronized on oldsources to avoid adding recovered source for the to-be-removed peer
580     // see NodeFailoverWorker.run
581     synchronized (oldsources) {
582       // First close all the recovered sources for this peer
583       for (ReplicationSourceInterface src : oldsources) {
584         if (id.equals(src.getPeerClusterId())) {
585           oldSourcesToDelete.add(src);
586         }
587       }
588       for (ReplicationSourceInterface src : oldSourcesToDelete) {
589         src.terminate(terminateMessage);
590         closeRecoveredQueue(src);
591       }
592     }
593     LOG.info("Number of deleted recovered sources for " + id + ": "
594         + oldSourcesToDelete.size());
595     // Now look for the one on this cluster
596     List<ReplicationSourceInterface> srcToRemove = new ArrayList<ReplicationSourceInterface>();
597     // synchronize on replicationPeers to avoid adding source for the to-be-removed peer
598     synchronized (this.replicationPeers) {
599       for (ReplicationSourceInterface src : this.sources) {
600         if (id.equals(src.getPeerClusterId())) {
601           srcToRemove.add(src);
602         }
603       }
604       if (srcToRemove.isEmpty()) {
605         LOG.error("The peer we wanted to remove is missing a ReplicationSourceInterface. " +
606             "This could mean that ReplicationSourceInterface initialization failed for this peer " +
607             "and that replication on this peer may not be caught up. peerId=" + id);
608       }
609       for (ReplicationSourceInterface toRemove : srcToRemove) {
610         toRemove.terminate(terminateMessage);
611         closeQueue(toRemove);
612       }
613       deleteSource(id, true);
614     }
615   }
616 
617   @Override
618   public void regionServerRemoved(String regionserver) {
619     transferQueues(regionserver);
620   }
621 
622   @Override
623   public void peerRemoved(String peerId) {
624     removePeer(peerId);
625     this.replicationQueues.removePeerFromHFileRefs(peerId);
626   }
627 
628   @Override
629   public void peerListChanged(List<String> peerIds) {
630     for (String id : peerIds) {
631       try {
632         boolean added = this.replicationPeers.peerAdded(id);
633         if (added) {
634           addSource(id);
635           if (replicationForBulkLoadDataEnabled) {
636             this.replicationQueues.addPeerToHFileRefs(id);
637           }
638         }
639       } catch (Exception e) {
640         LOG.error("Error while adding a new peer", e);
641       }
642     }
643   }
644 
645   /**
646    * Class responsible to setup new ReplicationSources to take care of the
647    * queues from dead region servers.
648    */
649   class NodeFailoverWorker extends Thread {
650 
651     private String rsZnode;
652     private final ReplicationQueues rq;
653     private final ReplicationPeers rp;
654     private final UUID clusterId;
655 
656     /**
657      * @param rsZnode
658      */
659     public NodeFailoverWorker(String rsZnode) {
660       this(rsZnode, replicationQueues, replicationPeers, ReplicationSourceManager.this.clusterId);
661     }
662 
663     public NodeFailoverWorker(String rsZnode, final ReplicationQueues replicationQueues,
664         final ReplicationPeers replicationPeers, final UUID clusterId) {
665       super("Failover-for-"+rsZnode);
666       this.rsZnode = rsZnode;
667       this.rq = replicationQueues;
668       this.rp = replicationPeers;
669       this.clusterId = clusterId;
670     }
671 
672     @Override
673     public void run() {
674       if (this.rq.isThisOurZnode(rsZnode)) {
675         return;
676       }
677       // Wait a bit before transferring the queues, we may be shutting down.
678       // This sleep may not be enough in some cases.
679       try {
680         Thread.sleep(sleepBeforeFailover + (long) (rand.nextFloat() * sleepBeforeFailover));
681       } catch (InterruptedException e) {
682         LOG.warn("Interrupted while waiting before transferring a queue.");
683         Thread.currentThread().interrupt();
684       }
685       // We try to lock that rs' queue directory
686       if (server.isStopped()) {
687         LOG.info("Not transferring queue since we are shutting down");
688         return;
689       }
690 
691       Map<String, SortedSet<String>> newQueues = new HashMap<>();
692       List<String> peers = rq.getUnClaimedQueueIds(rsZnode);
693       while (peers != null && !peers.isEmpty()) {
694         Pair<String, SortedSet<String>> peer = this.rq.claimQueue(rsZnode,
695             peers.get(rand.nextInt(peers.size())));
696         long sleep = sleepBeforeFailover/2;
697         if (peer != null) {
698           newQueues.put(peer.getFirst(), peer.getSecond());
699           sleep = sleepBeforeFailover;
700         }
701         try {
702           Thread.sleep(sleep);
703         } catch (InterruptedException e) {
704           LOG.warn("Interrupted while waiting before transferring a queue.");
705           Thread.currentThread().interrupt();
706         }
707         peers = rq.getUnClaimedQueueIds(rsZnode);
708       }
709       if (peers != null) {
710         rq.removeReplicatorIfQueueIsEmpty(rsZnode);
711       }
712 
713       // Copying over the failed queue is completed.
714       if (newQueues.isEmpty()) {
715         // We either didn't get the lock or the failed region server didn't have any outstanding
716         // WALs to replicate, so we are done.
717         return;
718       }
719 
720       for (Map.Entry<String, SortedSet<String>> entry : newQueues.entrySet()) {
721         String peerId = entry.getKey();
722         SortedSet<String> walsSet = entry.getValue();
723         try {
724           // there is not an actual peer defined corresponding to peerId for the failover.
725           ReplicationQueueInfo replicationQueueInfo = new ReplicationQueueInfo(peerId);
726           String actualPeerId = replicationQueueInfo.getPeerId();
727           ReplicationPeer peer = replicationPeers.getPeer(actualPeerId);
728           ReplicationPeerConfig peerConfig = null;
729           try {
730             peerConfig = replicationPeers.getReplicationPeerConfig(actualPeerId);
731           } catch (ReplicationException ex) {
732             LOG.warn("Received exception while getting replication peer config, skipping replay"
733                 + ex);
734           }
735           if (peer == null || peerConfig == null) {
736             LOG.warn("Skipping failover for peer:" + actualPeerId + " of node" + rsZnode);
737             replicationQueues.removeQueue(peerId);
738             continue;
739           }
740           if (server instanceof ReplicationSyncUp.DummyServer
741               && peer.getPeerState().equals(PeerState.DISABLED)) {
742             LOG.warn("Peer " + actualPeerId + " is disbaled. ReplicationSyncUp tool will skip "
743                 + "replicating data to this peer.");
744             continue;
745           }
746           // track sources in walsByIdRecoveredQueues
747           Map<String, SortedSet<String>> walsByGroup = new HashMap<String, SortedSet<String>>();
748           walsByIdRecoveredQueues.put(peerId, walsByGroup);
749           for (String wal : walsSet) {
750             String walPrefix = DefaultWALProvider.getWALPrefixFromWALName(wal);
751             SortedSet<String> wals = walsByGroup.get(walPrefix);
752             if (wals == null) {
753               wals = new TreeSet<String>();
754               walsByGroup.put(walPrefix, wals);
755             }
756             wals.add(wal);
757           }
758 
759           // enqueue sources
760           ReplicationSourceInterface src =
761               getReplicationSource(conf, fs, ReplicationSourceManager.this, this.rq, this.rp,
762                 server, peerId, this.clusterId, peerConfig, peer);
763           // synchronized on oldsources to avoid adding recovered source for the to-be-removed peer
764           // see removePeer
765           synchronized (oldsources) {
766             if (!this.rp.getPeerIds().contains(src.getPeerClusterId())) {
767               src.terminate("Recovered queue doesn't belong to any current peer");
768               closeRecoveredQueue(src);
769               continue;
770             }
771             oldsources.add(src);
772             for (String wal : walsSet) {
773               src.enqueueLog(new Path(oldLogDir, wal));
774             }
775             src.startup();
776           }
777         } catch (IOException e) {
778           // TODO manage it
779           LOG.error("Failed creating a source", e);
780         }
781       }
782     }
783   }
784 
785   /**
786    * Get the directory where wals are archived
787    * @return the directory where wals are archived
788    */
789   public Path getOldLogDir() {
790     return this.oldLogDir;
791   }
792 
793   /**
794    * Get the directory where wals are stored by their RSs
795    * @return the directory where wals are stored by their RSs
796    */
797   public Path getLogDir() {
798     return this.logDir;
799   }
800 
801   /**
802    * Get the handle on the local file system
803    * @return Handle on the local file system
804    */
805   public FileSystem getFs() {
806     return this.fs;
807   }
808 
809   /**
810    * Get the ReplicationPeers used by this ReplicationSourceManager
811    * @return the ReplicationPeers used by this ReplicationSourceManager
812    */
813   public ReplicationPeers getReplicationPeers() {return this.replicationPeers;}
814 
815   /**
816    * Get a string representation of all the sources' metrics
817    */
818   public String getStats() {
819     StringBuffer stats = new StringBuffer();
820     for (ReplicationSourceInterface source : sources) {
821       stats.append("Normal source for cluster " + source.getPeerClusterId() + ": ");
822       stats.append(source.getStats() + "\n");
823     }
824     for (ReplicationSourceInterface oldSource : oldsources) {
825       stats.append("Recovered source for cluster/machine(s) " + oldSource.getPeerClusterId()+": ");
826       stats.append(oldSource.getStats()+ "\n");
827     }
828     return stats.toString();
829   }
830 
831   public void addHFileRefs(TableName tableName, byte[] family, List<Pair<Path, Path>> pairs)
832       throws ReplicationException {
833     for (ReplicationSourceInterface source : this.sources) {
834       source.addHFileRefs(tableName, family, pairs);
835     }
836   }
837 
838   public void cleanUpHFileRefs(String peerId, List<String> files) {
839     this.replicationQueues.removeHFileRefs(peerId, files);
840   }
841 }