View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.replication.regionserver;
20  
21  import java.io.EOFException;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.List;
25  import java.util.concurrent.BlockingQueue;
26  import java.util.concurrent.LinkedBlockingQueue;
27  import java.util.concurrent.PriorityBlockingQueue;
28  import java.util.concurrent.TimeUnit;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.fs.FileSystem;
34  import org.apache.hadoop.fs.Path;
35  import org.apache.hadoop.hbase.Cell;
36  import org.apache.hadoop.hbase.CellUtil;
37  import org.apache.hadoop.hbase.classification.InterfaceAudience;
38  import org.apache.hadoop.hbase.classification.InterfaceStability;
39  import org.apache.hadoop.hbase.protobuf.generated.WALProtos.BulkLoadDescriptor;
40  import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
41  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
42  import org.apache.hadoop.hbase.replication.ReplicationQueueInfo;
43  import org.apache.hadoop.hbase.replication.WALEntryFilter;
44  import org.apache.hadoop.hbase.replication.regionserver.WALEntryStream.WALEntryStreamRuntimeException;
45  import org.apache.hadoop.hbase.util.Pair;
46  import org.apache.hadoop.hbase.util.Threads;
47  import org.apache.hadoop.hbase.wal.WAL.Entry;
48  
49  /**
50   * Reads and filters WAL entries, groups the filtered entries into batches, and puts the batches onto a queue
51   *
52   */
53  @InterfaceAudience.Private
54  @InterfaceStability.Evolving
55  public class ReplicationSourceWALReaderThread extends Thread {
56    private static final Log LOG = LogFactory.getLog(ReplicationSourceWALReaderThread.class);
57  
58    private PriorityBlockingQueue<Path> logQueue;
59    private FileSystem fs;
60    private Configuration conf;
61    private BlockingQueue<WALEntryBatch> entryBatchQueue;
62    // max (heap) size of each batch - multiply by number of batches in queue to get total
63    private long replicationBatchSizeCapacity;
64    // max count of each batch - multiply by number of batches in queue to get total
65    private int replicationBatchCountCapacity;
66    // position in the WAL to start reading at
67    private long lastReadPosition;
68    private Path lastReadPath;
69    private WALEntryFilter filter;
70    private long sleepForRetries;
71    //Indicates whether this particular worker is running
72    private boolean isReaderRunning = true;
73    private ReplicationQueueInfo replicationQueueInfo;
74    private int maxRetriesMultiplier;
75    private MetricsSource metrics;
76  
77    /**
78     * Creates a reader worker for a given WAL queue. Reads WAL entries off a given queue, batches the
79     * entries, and puts them on a batch queue.
80     * @param manager replication manager
81     * @param replicationQueueInfo
82     * @param logQueue The WAL queue to read off of
83     * @param startPosition position in the first WAL to start reading from
84     * @param fs the files system to use
85     * @param conf configuration to use
86     * @param filter The filter to use while reading
87     * @param metrics replication metrics
88     */
89    public ReplicationSourceWALReaderThread(ReplicationSourceManager manager,
90        ReplicationQueueInfo replicationQueueInfo, PriorityBlockingQueue<Path> logQueue,
91        long startPosition,
92        FileSystem fs, Configuration conf, WALEntryFilter filter, MetricsSource metrics) {
93      this.replicationQueueInfo = replicationQueueInfo;
94      this.logQueue = logQueue;
95      this.lastReadPath = logQueue.peek();
96      this.lastReadPosition = startPosition;
97      this.fs = fs;
98      this.conf = conf;
99      this.filter = filter;
100     this.replicationBatchSizeCapacity =
101         this.conf.getLong("replication.source.size.capacity", 1024 * 1024 * 64);
102     this.replicationBatchCountCapacity = this.conf.getInt("replication.source.nb.capacity", 25000);
103     // memory used will be batchSizeCapacity * (nb.batches + 1)
104     // the +1 is for the current thread reading before placing onto the queue
105     int batchCount = conf.getInt("replication.source.nb.batches", 1);
106     this.sleepForRetries =
107         this.conf.getLong("replication.source.sleepforretries", 1000);    // 1 second
108     this.maxRetriesMultiplier =
109         this.conf.getInt("replication.source.maxretriesmultiplier", 300); // 5 minutes @ 1 sec per
110     this.metrics = metrics;
111     this.entryBatchQueue = new LinkedBlockingQueue<>(batchCount);
112     LOG.info("peerClusterZnode=" + replicationQueueInfo.getPeerClusterZnode()
113         + ", ReplicationSourceWALReaderThread : " + replicationQueueInfo.getPeerId()
114         + " inited, replicationBatchSizeCapacity=" + replicationBatchSizeCapacity
115         + ", replicationBatchCountCapacity=" + replicationBatchCountCapacity
116         + ", replicationBatchQueueCapacity=" + batchCount);
117   }
118 
119   @Override
120   public void run() {
121     int sleepMultiplier = 1;
122     while (isReaderRunning()) { // we only loop back here if something fatal happened to our stream
123       try (WALEntryStream entryStream =
124           new WALEntryStream(logQueue, fs, conf, lastReadPosition, metrics)) {
125         while (isReaderRunning()) { // loop here to keep reusing stream while we can
126           WALEntryBatch batch = new WALEntryBatch(replicationBatchCountCapacity);
127           boolean hasNext;
128           while ((hasNext = entryStream.hasNext()) == true) {
129             Entry entry = entryStream.next();
130             entry = filterEntry(entry);
131             if (entry != null) {
132               WALEdit edit = entry.getEdit();
133               if (edit != null && !edit.isEmpty()) {
134                 long entrySize = getEntrySize(entry);
135                 batch.addEntry(entry);
136                 updateBatchStats(batch, entry, entryStream.getPosition(), entrySize);
137                 // Stop if too many entries or too big
138                 if (batch.getHeapSize() >= replicationBatchSizeCapacity
139                     || batch.getNbEntries() >= replicationBatchCountCapacity) {
140                   break;
141                 }
142               }
143             }
144           }
145 
146           updateBatch(entryStream, batch, hasNext);
147           if (isShippable(batch)) {
148             sleepMultiplier = 1;
149             entryBatchQueue.put(batch);
150             if (!batch.hasMoreEntries()) {
151               // we're done with queue recovery, shut ourselves down
152               setReaderRunning(false);
153             }
154           } else {
155             Thread.sleep(sleepForRetries);
156           }
157           resetStream(entryStream);
158         }
159       } catch (IOException | WALEntryStreamRuntimeException e) { // stream related
160         if (sleepMultiplier < maxRetriesMultiplier) {
161           LOG.debug("Failed to read stream of replication entries: " + e);
162           sleepMultiplier++;
163         } else {
164           LOG.error("Failed to read stream of replication entries", e);
165           handleEofException(e);
166         }
167         Threads.sleep(sleepForRetries * sleepMultiplier);
168       } catch (InterruptedException e) {
169         LOG.trace("Interrupted while sleeping between WAL reads");
170         Thread.currentThread().interrupt();
171       }
172     }
173   }
174 
175   private void updateBatch(WALEntryStream entryStream, WALEntryBatch batch, boolean moreData) {
176     logMessage(batch);
177     batch.updatePosition(entryStream);
178     batch.setMoreEntries(!replicationQueueInfo.isQueueRecovered() || moreData);
179   }
180 
181   private void logMessage(WALEntryBatch batch) {
182     if (LOG.isTraceEnabled()) {
183       if (batch.isEmpty()) {
184         LOG.trace("Didn't read any new entries from WAL");
185       } else {
186         LOG.trace(String.format("Read %s WAL entries eligible for replication",
187                 batch.getNbEntries()));
188       }
189     }
190   }
191 
192   private boolean isShippable(WALEntryBatch batch) {
193     return !batch.isEmpty() || checkIfWALRolled(batch) || !batch.hasMoreEntries();
194   }
195 
196   private boolean checkIfWALRolled(WALEntryBatch batch) {
197     return lastReadPath == null && batch.lastWalPath != null
198       || lastReadPath != null && !lastReadPath.equals(batch.lastWalPath);
199   }
200 
201   private void resetStream(WALEntryStream stream) throws IOException {
202     lastReadPosition = stream.getPosition();
203     lastReadPath = stream.getCurrentPath();
204     stream.reset(); // reuse stream
205   }
206 
207   // if we get an EOF due to a zero-length log, and there are other logs in queue
208   // (highly likely we've closed the current log), we've hit the max retries, and autorecovery is
209   // enabled, then dump the log
210   private void handleEofException(Exception e) {
211     if (e.getCause() instanceof EOFException && logQueue.size() > 1
212         && conf.getBoolean("replication.source.eof.autorecovery", false)) {
213       try {
214         if (fs.getFileStatus(logQueue.peek()).getLen() == 0) {
215           LOG.warn("Forcing removal of 0 length log in queue: " + logQueue.peek());
216           lastReadPath = logQueue.remove();
217           lastReadPosition = 0;
218         }
219       } catch (IOException ioe) {
220         LOG.warn("Couldn't get file length information about log " + logQueue.peek());
221       }
222     }
223   }
224 
225   public Path getCurrentPath() {
226     return logQueue.peek();
227   }
228 
229   private Entry filterEntry(Entry entry) {
230     Entry filtered = filter.filter(entry);
231     if (entry != null && filtered == null) {
232       metrics.incrLogEditsFiltered();
233     }
234     return filtered;
235   }
236 
237   /**
238    * Retrieves the next batch of WAL entries from the queue, waiting up to the specified time for a
239    * batch to become available
240    * @return A batch of entries, along with the position in the log after reading the batch
241    * @throws InterruptedException if interrupted while waiting
242    */
243   public WALEntryBatch take() throws InterruptedException {
244     return entryBatchQueue.take();
245   }
246 
247   public WALEntryBatch poll(long timeout) throws InterruptedException {
248     return entryBatchQueue.poll(timeout, TimeUnit.MILLISECONDS);
249   }
250 
251   private long getEntrySize(Entry entry) {
252     WALEdit edit = entry.getEdit();
253     return edit.heapSize() + calculateTotalSizeOfStoreFiles(edit);
254   }
255 
256   private void updateBatchStats(WALEntryBatch batch, Entry entry, long entryPosition, long entrySize) {
257     WALEdit edit = entry.getEdit();
258     if (edit != null && !edit.isEmpty()) {
259       batch.incrementHeapSize(entrySize);
260       Pair<Integer, Integer> nbRowsAndHFiles = countDistinctRowKeysAndHFiles(edit);
261       batch.incrementNbRowKeys(nbRowsAndHFiles.getFirst());
262       batch.incrementNbHFiles(nbRowsAndHFiles.getSecond());
263     }
264     batch.lastWalPosition = entryPosition;
265   }
266 
267   /**
268    * Count the number of different row keys in the given edit because of mini-batching. We assume
269    * that there's at least one Cell in the WALEdit.
270    * @param edit edit to count row keys from
271    * @return number of different row keys and HFiles
272    */
273   private Pair<Integer, Integer> countDistinctRowKeysAndHFiles(WALEdit edit) {
274     List<Cell> cells = edit.getCells();
275     int distinctRowKeys = 1;
276     int totalHFileEntries = 0;
277     Cell lastCell = cells.get(0);
278 
279     int totalCells = edit.size();
280     for (int i = 0; i < totalCells; i++) {
281       // Count HFiles to be replicated
282       if (CellUtil.matchingQualifier(cells.get(i), WALEdit.BULK_LOAD)) {
283         try {
284           BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cells.get(i));
285           List<StoreDescriptor> stores = bld.getStoresList();
286           int totalStores = stores.size();
287           for (int j = 0; j < totalStores; j++) {
288             totalHFileEntries += stores.get(j).getStoreFileList().size();
289           }
290         } catch (IOException e) {
291           LOG.error("Failed to deserialize bulk load entry from wal edit. "
292               + "Then its hfiles count will not be added into metric.");
293         }
294       }
295 
296       if (!CellUtil.matchingRow(cells.get(i), lastCell)) {
297         distinctRowKeys++;
298       }
299       lastCell = cells.get(i);
300     }
301 
302     Pair<Integer, Integer> result = new Pair<>(distinctRowKeys, totalHFileEntries);
303     return result;
304   }
305 
306   /**
307    * Calculate the total size of all the store files
308    * @param edit edit to count row keys from
309    * @return the total size of the store files
310    */
311   private int calculateTotalSizeOfStoreFiles(WALEdit edit) {
312     List<Cell> cells = edit.getCells();
313     int totalStoreFilesSize = 0;
314 
315     int totalCells = edit.size();
316     for (int i = 0; i < totalCells; i++) {
317       if (CellUtil.matchingQualifier(cells.get(i), WALEdit.BULK_LOAD)) {
318         try {
319           BulkLoadDescriptor bld = WALEdit.getBulkLoadDescriptor(cells.get(i));
320           List<StoreDescriptor> stores = bld.getStoresList();
321           int totalStores = stores.size();
322           for (int j = 0; j < totalStores; j++) {
323             totalStoreFilesSize += stores.get(j).getStoreFileSizeBytes();
324           }
325         } catch (IOException e) {
326           LOG.error("Failed to deserialize bulk load entry from wal edit. "
327               + "Size of HFiles part of cell will not be considered in replication "
328               + "request size calculation.",
329             e);
330         }
331       }
332     }
333     return totalStoreFilesSize;
334   }
335 
336   /**
337    * @return whether the reader thread is running
338    */
339   public boolean isReaderRunning() {
340     return isReaderRunning && !isInterrupted();
341   }
342 
343   /**
344    * @param readerRunning the readerRunning to set
345    */
346   public void setReaderRunning(boolean readerRunning) {
347     this.isReaderRunning = readerRunning;
348   }
349 
350   public long getLastReadPosition() {
351     return this.lastReadPosition;
352   }
353 
354   /**
355    * Holds a batch of WAL entries to replicate, along with some statistics
356    *
357    */
358   static class WALEntryBatch {
359     private List<Entry> walEntries;
360     // last WAL that was read
361     private Path lastWalPath;
362     // position in WAL of last entry in this batch
363     private long lastWalPosition = 0;
364     // number of distinct row keys in this batch
365     private int nbRowKeys = 0;
366     // number of HFiles
367     private int nbHFiles = 0;
368     // heap size of data we need to replicate
369     private long heapSize = 0;
370     // whether more entries to read exist in WALs or not
371     private boolean moreEntries = true;
372 
373     /**
374      * @param maxNbEntries the number of entries a batch can have
375      */
376     private WALEntryBatch(int maxNbEntries) {
377       this.walEntries = new ArrayList<>(maxNbEntries);
378     }
379 
380     public void addEntry(Entry entry) {
381       walEntries.add(entry);
382     }
383 
384     /**
385      * @return the WAL Entries.
386      */
387     public List<Entry> getWalEntries() {
388       return walEntries;
389     }
390 
391     /**
392      * @return the path of the last WAL that was read.
393      */
394     public Path getLastWalPath() {
395       return lastWalPath;
396     }
397 
398     /**
399      * @return the position in the last WAL that was read.
400      */
401     public long getLastWalPosition() {
402       return lastWalPosition;
403     }
404 
405     public int getNbEntries() {
406       return walEntries.size();
407     }
408 
409     /**
410      * @return the number of distinct row keys in this batch
411      */
412     public int getNbRowKeys() {
413       return nbRowKeys;
414     }
415 
416     /**
417      * @return the number of HFiles in this batch
418      */
419     public int getNbHFiles() {
420       return nbHFiles;
421     }
422 
423     /**
424      * @return total number of operations in this batch
425      */
426     public int getNbOperations() {
427       return getNbRowKeys() + getNbHFiles();
428     }
429 
430     /**
431      * @return the heap size of this batch
432      */
433     public long getHeapSize() {
434       return heapSize;
435     }
436 
437     private void incrementNbRowKeys(int increment) {
438       nbRowKeys += increment;
439     }
440 
441     private void incrementNbHFiles(int increment) {
442       nbHFiles += increment;
443     }
444 
445     private void incrementHeapSize(long increment) {
446       heapSize += increment;
447     }
448 
449     public boolean isEmpty() {
450       return walEntries.isEmpty();
451     }
452 
453     public void updatePosition(WALEntryStream entryStream) {
454       lastWalPath = entryStream.getCurrentPath();
455       lastWalPosition = entryStream.getPosition();
456     }
457 
458     public boolean hasMoreEntries() {
459       return moreEntries;
460     }
461 
462     public void setMoreEntries(boolean moreEntries) {
463       this.moreEntries = moreEntries;
464     }
465   }
466 }