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.Closeable;
22  import java.io.FileNotFoundException;
23  import java.io.IOException;
24  import java.util.Iterator;
25  import java.util.NoSuchElementException;
26  import java.util.concurrent.PriorityBlockingQueue;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.fs.FileStatus;
32  import org.apache.hadoop.fs.FileSystem;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.classification.InterfaceStability;
37  import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
38  import org.apache.hadoop.hbase.util.CancelableProgressable;
39  import org.apache.hadoop.hbase.util.FSUtils;
40  import org.apache.hadoop.hbase.util.LeaseNotRecoveredException;
41  import org.apache.hadoop.hbase.wal.WAL.Entry;
42  import org.apache.hadoop.hbase.wal.WAL.Reader;
43  import org.apache.hadoop.hbase.wal.WALFactory;
44  import org.apache.hadoop.ipc.RemoteException;
45  
46  /**
47   * Streaming access to WAL entries. This class is given a queue of WAL {@link Path}, and continually
48   * iterates through all the WAL {@link Entry} in the queue. When it's done reading from a Path, it
49   * dequeues it and starts reading from the next.
50   */
51  @InterfaceAudience.Private
52  @InterfaceStability.Evolving
53  public class WALEntryStream implements Iterator<Entry>, Closeable, Iterable<Entry> {
54    private static final Log LOG = LogFactory.getLog(WALEntryStream.class);
55  
56    private Reader reader;
57    private Path currentPath;
58    // cache of next entry for hasNext()
59    private Entry currentEntry;
60    // position after reading current entry
61    private long currentPosition = 0;
62    private PriorityBlockingQueue<Path> logQueue;
63    private FileSystem fs;
64    private Configuration conf;
65    private MetricsSource metrics;
66  
67    /**
68     * Create an entry stream over the given queue
69     * @param logQueue the queue of WAL paths
70     * @param fs {@link FileSystem} to use to create {@link Reader} for this stream
71     * @param conf {@link Configuration} to use to create {@link Reader} for this stream
72     * @param metrics replication metrics
73     * @throws IOException
74     */
75    public WALEntryStream(PriorityBlockingQueue<Path> logQueue, FileSystem fs, Configuration conf,
76        MetricsSource metrics)
77        throws IOException {
78      this(logQueue, fs, conf, 0, metrics);
79    }
80  
81    /**
82     * Create an entry stream over the given queue at the given start position
83     * @param logQueue the queue of WAL paths
84     * @param conf the {@link Configuration} to use to create {@link Reader} for this stream
85     * @param startPosition the position in the first WAL to start reading at
86     * @param metrics the replication metrics
87     * @throws IOException
88     */
89    public WALEntryStream(PriorityBlockingQueue<Path> logQueue, FileSystem fs, Configuration conf,
90        long startPosition, MetricsSource metrics) throws IOException {
91      this.logQueue = logQueue;
92      this.fs = fs;
93      this.conf = conf;
94      this.currentPosition = startPosition;
95      this.metrics = metrics;
96    }
97  
98    /**
99     * @return true if there is another WAL {@link Entry}
100    * @throws WALEntryStreamRuntimeException if there was an Exception while reading
101    */
102   @Override
103   public boolean hasNext() {
104     if (currentEntry == null) {
105       try {
106         tryAdvanceEntry();
107       } catch (Exception e) {
108         throw new WALEntryStreamRuntimeException(e);
109       }
110     }
111     return currentEntry != null;
112   }
113 
114   /**
115    * @return the next WAL entry in this stream
116    * @throws WALEntryStreamRuntimeException if there was an IOException
117    * @throws NoSuchElementException if no more entries in the stream.
118    */
119   @Override
120   public Entry next() {
121     if (!hasNext()) throw new NoSuchElementException();
122     Entry save = currentEntry;
123     currentEntry = null; // gets reloaded by hasNext()
124     return save;
125   }
126 
127   /**
128    * Not supported.
129    */
130   @Override
131   public void remove() {
132     throw new UnsupportedOperationException();
133   }
134 
135   /**
136    * {@inheritDoc}
137    */
138   @Override
139   public void close() throws IOException {
140     closeReader();
141   }
142 
143   /**
144    * @return the iterator over WAL entries in the queue.
145    */
146   @Override
147   public Iterator<Entry> iterator() {
148     return this;
149   }
150 
151   /**
152    * @return the position of the last Entry returned by next()
153    */
154   public long getPosition() {
155     return currentPosition;
156   }
157 
158   /**
159    * @return the {@link Path} of the current WAL
160    */
161   public Path getCurrentPath() {
162     return currentPath;
163   }
164 
165   private String getCurrentPathStat() {
166     StringBuilder sb = new StringBuilder();
167     if (currentPath != null) {
168       sb.append("currently replicating from: ").append(currentPath).append(" at position: ")
169           .append(currentPosition).append("\n");
170     } else {
171       sb.append("no replication ongoing, waiting for new log");
172     }
173     return sb.toString();
174   }
175 
176   /**
177    * Should be called if the stream is to be reused (i.e. used again after hasNext() has returned
178    * false)
179    * @throws IOException
180    */
181   public void reset() throws IOException {
182     if (reader != null && currentPath != null) {
183       resetReader();
184     }
185   }
186 
187   private void setPosition(long position) {
188     currentPosition = position;
189   }
190 
191   private void setCurrentPath(Path path) {
192     this.currentPath = path;
193   }
194 
195   private void tryAdvanceEntry() throws IOException {
196     if (checkReader()) {
197       readNextEntryAndSetPosition();
198       if (currentEntry == null) { // no more entries in this log file - see if log was rolled
199         if (logQueue.size() > 1) { // log was rolled
200           // Before dequeueing, we should always get one more attempt at reading.
201           // This is in case more entries came in after we opened the reader,
202           // and a new log was enqueued while we were reading. See HBASE-6758
203           resetReader();
204           readNextEntryAndSetPosition();
205           if (currentEntry == null) {
206             if (checkAllBytesParsed()) { // now we're certain we're done with this log file
207               dequeueCurrentLog();
208               if (openNextLog()) {
209                 readNextEntryAndSetPosition();
210               }
211             }
212           }
213         } // no other logs, we've simply hit the end of the current open log. Do nothing
214       }
215     }
216     // do nothing if we don't have a WAL Reader (e.g. if there's no logs in queue)
217   }
218 
219   // HBASE-15984 check to see we have in fact parsed all data in a cleanly closed file
220   private boolean checkAllBytesParsed() throws IOException {
221     // -1 means the wal wasn't closed cleanly.
222     final long trailerSize = currentTrailerSize();
223     FileStatus stat = null;
224     try {
225       stat = fs.getFileStatus(this.currentPath);
226     } catch (IOException exception) {
227       LOG.warn("Couldn't get file length information about log " + this.currentPath + ", it "
228           + (trailerSize < 0 ? "was not" : "was") + " closed cleanly " + getCurrentPathStat());
229       metrics.incrUnknownFileLengthForClosedWAL();
230     }
231     if (stat != null) {
232       if (trailerSize < 0) {
233         if (currentPosition < stat.getLen()) {
234           final long skippedBytes = stat.getLen() - currentPosition;
235           if (LOG.isDebugEnabled()) {
236             LOG.debug("Reached the end of WAL file '" + currentPath
237                 + "'. It was not closed cleanly, so we did not parse " + skippedBytes
238                 + " bytes of data. This is normally ok.");
239           }
240           metrics.incrUncleanlyClosedWALs();
241           metrics.incrBytesSkippedInUncleanlyClosedWALs(skippedBytes);
242         }
243       } else if (currentPosition + trailerSize < stat.getLen()) {
244         LOG.warn("Processing end of WAL file '" + currentPath + "'. At position " + currentPosition
245             + ", which is too far away from reported file length " + stat.getLen()
246             + ". Restarting WAL reading (see HBASE-15983 for details). " + getCurrentPathStat());
247         setPosition(0);
248         resetReader();
249         metrics.incrRestartedWALReading();
250         metrics.incrRepeatedFileBytes(currentPosition);
251         return false;
252       }
253     }
254     if (LOG.isTraceEnabled()) {
255       LOG.trace("Reached the end of log " + this.currentPath + ", and the length of the file is "
256           + (stat == null ? "N/A" : stat.getLen()));
257     }
258     metrics.incrCompletedWAL();
259     return true;
260   }
261 
262   private void dequeueCurrentLog() throws IOException {
263     if (LOG.isDebugEnabled()) {
264       LOG.debug("Reached the end of log " + currentPath);
265     }
266     closeReader();
267     logQueue.remove();
268     setPosition(0);
269     metrics.decrSizeOfLogQueue();
270   }
271 
272   private void readNextEntryAndSetPosition() throws IOException {
273     Entry readEntry = reader.next();
274     long readerPos = reader.getPosition();
275     if (readEntry != null) {
276       metrics.incrLogEditsRead();
277       metrics.incrLogReadInBytes(readerPos - currentPosition);
278     }
279     currentEntry = readEntry; // could be null
280     setPosition(readerPos);
281   }
282 
283   private void closeReader() throws IOException {
284     if (reader != null) {
285       reader.close();
286       reader = null;
287     }
288   }
289 
290   // if we don't have a reader, open a reader on the next log
291   private boolean checkReader() throws IOException {
292     if (reader == null) {
293       return openNextLog();
294     }
295     return true;
296   }
297 
298   // open a reader on the next log in queue
299   private boolean openNextLog() throws IOException {
300     Path nextPath = logQueue.peek();
301     if (nextPath != null) {
302       openReader(nextPath);
303       if (reader != null) return true;
304     }
305     return false;
306   }
307 
308   private Path getArchivedLog(Path path) throws IOException {
309     Path rootDir = FSUtils.getRootDir(conf);
310     Path oldLogDir = new Path(rootDir, HConstants.HREGION_OLDLOGDIR_NAME);
311     Path archivedLogLocation = new Path(oldLogDir, path.getName());
312     if (fs.exists(archivedLogLocation)) {
313       LOG.info("Log " + path + " was moved to " + archivedLogLocation);
314       return archivedLogLocation;
315     } else {
316       LOG.error("Couldn't locate log: " + path);
317       return path;
318     }
319   }
320 
321   private void handleFileNotFound(Path path, FileNotFoundException fnfe) throws IOException {
322     // If the log was archived, continue reading from there
323     Path archivedLog = getArchivedLog(path);
324     if (!path.equals(archivedLog)) {
325       openReader(archivedLog);
326     } else {
327       throw fnfe;
328     }
329   }
330   private void openReader(Path path) throws IOException {
331     try {
332       // Detect if this is a new file, if so get a new reader else
333       // reset the current reader so that we see the new data
334       if (reader == null || !getCurrentPath().equals(path)) {
335         closeReader();
336         reader = WALFactory.createReader(fs, path, conf);
337         seek();
338         setCurrentPath(path);
339       } else {
340         resetReader();
341       }
342     } catch (FileNotFoundException fnfe) {
343       handleFileNotFound(path, fnfe);
344     }  catch (RemoteException re) {
345       IOException ioe = re.unwrapRemoteException(FileNotFoundException.class);
346       if (!(ioe instanceof FileNotFoundException)) throw ioe;
347       handleFileNotFound(path, (FileNotFoundException)ioe);
348     } catch (LeaseNotRecoveredException lnre) {
349       // HBASE-15019 the WAL was not closed due to some hiccup.
350       LOG.warn("Try to recover the WAL lease " + currentPath, lnre);
351       recoverLease(conf, currentPath);
352       reader = null;
353     } catch (NullPointerException npe) {
354       // Workaround for race condition in HDFS-4380
355       // which throws a NPE if we open a file before any data node has the most recent block
356       // Just sleep and retry. Will require re-reading compressed WALs for compressionContext.
357       LOG.warn("Got NPE opening reader, will retry.");
358       reader = null;
359     }
360   }
361 
362   // For HBASE-15019
363   private void recoverLease(final Configuration conf, final Path path) {
364     try {
365       final FileSystem dfs = FSUtils.getCurrentFileSystem(conf);
366       FSUtils fsUtils = FSUtils.getInstance(dfs, conf);
367       fsUtils.recoverFileLease(dfs, path, conf, new CancelableProgressable() {
368         @Override
369         public boolean progress() {
370           LOG.debug("recover WAL lease: " + path);
371           return true;
372         }
373       });
374     } catch (IOException e) {
375       LOG.warn("unable to recover lease for WAL: " + path, e);
376     }
377   }
378 
379   private void resetReader() throws IOException {
380     try {
381       reader.reset();
382       seek();
383     } catch (FileNotFoundException fnfe) {
384       // If the log was archived, continue reading from there
385       Path archivedLog = getArchivedLog(currentPath);
386       if (!currentPath.equals(archivedLog)) {
387         openReader(archivedLog);
388       } else {
389         throw fnfe;
390       }
391     } catch (NullPointerException npe) {
392       throw new IOException("NPE resetting reader, likely HDFS-4380", npe);
393     }
394   }
395 
396   private void seek() throws IOException {
397     if (currentPosition != 0) {
398       reader.seek(currentPosition);
399     }
400   }
401 
402   private long currentTrailerSize() {
403     long size = -1L;
404     if (reader instanceof ProtobufLogReader) {
405       final ProtobufLogReader pblr = (ProtobufLogReader) reader;
406       size = pblr.trailerSize();
407     }
408     return size;
409   }
410 
411   @InterfaceAudience.Private
412   public static class WALEntryStreamRuntimeException extends RuntimeException {
413     private static final long serialVersionUID = -6298201811259982568L;
414 
415     public WALEntryStreamRuntimeException(Exception e) {
416       super(e);
417     }
418   }
419 
420 }