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