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.regionserver.wal;
21  
22  import java.io.EOFException;
23  import java.io.IOException;
24  import java.nio.ByteBuffer;
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.List;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.fs.FileSystem;
35  import org.apache.hadoop.fs.FSDataInputStream;
36  import org.apache.hadoop.hbase.codec.Codec;
37  import org.apache.hadoop.hbase.io.LimitInputStream;
38  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
39  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
40  import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
41  import org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader.Builder;
42  import org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey;
43  import org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALTrailer;
44  import org.apache.hadoop.hbase.util.Bytes;
45  import org.apache.hadoop.hbase.wal.WAL.Entry;
46  
47  import com.google.protobuf.CodedInputStream;
48  import com.google.protobuf.InvalidProtocolBufferException;
49  
50  /**
51   * A Protobuf based WAL has the following structure:
52   * <p>
53   * &lt;PB_WAL_MAGIC&gt;&lt;WALHeader&gt;&lt;WALEdits&gt;...&lt;WALEdits&gt;&lt;Trailer&gt;
54   * &lt;TrailerSize&gt; &lt;PB_WAL_COMPLETE_MAGIC&gt;
55   * </p>
56   * The Reader reads meta information (WAL Compression state, WALTrailer, etc) in
57   * ProtobufLogReader#initReader(FSDataInputStream). A WALTrailer is an extensible structure
58   * which is appended at the end of the WAL. This is empty for now; it can contain some meta
59   * information such as Region level stats, etc in future.
60   */
61  @InterfaceAudience.LimitedPrivate({HBaseInterfaceAudience.COPROC, HBaseInterfaceAudience.PHOENIX,
62    HBaseInterfaceAudience.CONFIG})
63  public class ProtobufLogReader extends ReaderBase {
64    private static final Log LOG = LogFactory.getLog(ProtobufLogReader.class);
65    // public for WALFactory until we move everything to o.a.h.h.wal
66    @InterfaceAudience.Private
67    public static final byte[] PB_WAL_MAGIC = Bytes.toBytes("PWAL");
68    // public for TestWALSplit
69    @InterfaceAudience.Private
70    public static final byte[] PB_WAL_COMPLETE_MAGIC = Bytes.toBytes("LAWP");
71    /**
72     * Configuration name of WAL Trailer's warning size. If a waltrailer's size is greater than the
73     * configured size, providers should log a warning. e.g. this is used with Protobuf reader/writer.
74     */
75    static final String WAL_TRAILER_WARN_SIZE = "hbase.regionserver.waltrailer.warn.size";
76    static final int DEFAULT_WAL_TRAILER_WARN_SIZE = 1024 * 1024; // 1MB
77  
78    protected FSDataInputStream inputStream;
79    protected Codec.Decoder cellDecoder;
80    protected WALCellCodec.ByteStringUncompressor byteStringUncompressor;
81    protected boolean hasCompression = false;
82    protected boolean hasTagCompression = false;
83    // walEditsStopOffset is the position of the last byte to read. After reading the last WALEdit
84    // entry in the wal, the inputstream's position is equal to walEditsStopOffset.
85    private long walEditsStopOffset;
86    private boolean trailerPresent;
87    protected WALTrailer trailer;
88    // maximum size of the wal Trailer in bytes. If a user writes/reads a trailer with size larger
89    // than this size, it is written/read respectively, with a WARN message in the log.
90    protected int trailerWarnSize;
91    private static List<String> writerClsNames = new ArrayList<String>();
92    static {
93      writerClsNames.add(ProtobufLogWriter.class.getSimpleName());
94    }
95    
96    // cell codec classname
97    private String codecClsName = null;
98  
99    @InterfaceAudience.Private
100   public long trailerSize() {
101     if (trailerPresent) {
102       // sizeof PB_WAL_COMPLETE_MAGIC + sizof trailerSize + trailer
103       final long calculatedSize = (long) PB_WAL_COMPLETE_MAGIC.length + Bytes.SIZEOF_INT +
104         trailer.getSerializedSize();
105       final long expectedSize = fileLength - walEditsStopOffset;
106       if (expectedSize != calculatedSize) {
107         LOG.warn("After parsing the trailer, we expect the total footer to be "+ expectedSize
108           + " bytes, but we calculate it as being " + calculatedSize);
109       }
110       return expectedSize;
111     } else {
112       return -1L;
113     }
114   }
115 
116   enum WALHdrResult {
117     EOF,                   // stream is at EOF when method starts
118     SUCCESS,
119     UNKNOWN_WRITER_CLS     // name of writer class isn't recognized
120   }
121   
122   // context for WALHdr carrying information such as Cell Codec classname
123   static class WALHdrContext {
124     WALHdrResult result;
125     String cellCodecClsName;
126     
127     WALHdrContext(WALHdrResult result, String cellCodecClsName) {
128       this.result = result;
129       this.cellCodecClsName = cellCodecClsName;
130     }
131     WALHdrResult getResult() {
132       return result;
133     }
134     String getCellCodecClsName() {
135       return cellCodecClsName;
136     }
137   }
138 
139   public ProtobufLogReader() {
140     super();
141   }
142 
143   @Override
144   public void close() throws IOException {
145     if (this.inputStream != null) {
146       this.inputStream.close();
147       this.inputStream = null;
148     }
149   }
150 
151   @Override
152   public long getPosition() throws IOException {
153     return inputStream.getPos();
154   }
155 
156   @Override
157   public void reset() throws IOException {
158     String clsName = initInternal(null, false);
159     initAfterCompression(clsName); // We need a new decoder (at least).
160   }
161 
162   @Override
163   public void init(FileSystem fs, Path path, Configuration conf, FSDataInputStream stream)
164       throws IOException {
165     this.trailerWarnSize = conf.getInt(WAL_TRAILER_WARN_SIZE, DEFAULT_WAL_TRAILER_WARN_SIZE);
166     super.init(fs, path, conf, stream);
167   }
168 
169   @Override
170   protected String initReader(FSDataInputStream stream) throws IOException {
171     return initInternal(stream, true);
172   }
173 
174   /*
175    * Returns names of the accepted writer classes
176    */
177   public List<String> getWriterClsNames() {
178     return writerClsNames;
179   }
180   
181   /*
182    * Returns the cell codec classname
183    */
184   public String getCodecClsName() {
185       return codecClsName;
186   }
187 
188   protected WALHdrContext readHeader(Builder builder, FSDataInputStream stream)
189       throws IOException {
190      boolean res = builder.mergeDelimitedFrom(stream);
191      if (!res) return new WALHdrContext(WALHdrResult.EOF, null);
192      if (builder.hasWriterClsName() &&
193          !getWriterClsNames().contains(builder.getWriterClsName())) {
194        return new WALHdrContext(WALHdrResult.UNKNOWN_WRITER_CLS, null);
195      }
196      String clsName = null;
197      if (builder.hasCellCodecClsName()) {
198        clsName = builder.getCellCodecClsName();
199      }
200      return new WALHdrContext(WALHdrResult.SUCCESS, clsName);
201   }
202 
203   private String initInternal(FSDataInputStream stream, boolean isFirst)
204       throws IOException {
205     close();
206     long expectedPos = PB_WAL_MAGIC.length;
207     if (stream == null) {
208       stream = fs.open(path);
209       stream.seek(expectedPos);
210     }
211     if (stream.getPos() != expectedPos) {
212       throw new IOException("The stream is at invalid position: " + stream.getPos());
213     }
214     // Initialize metadata or, when we reset, just skip the header.
215     WALProtos.WALHeader.Builder builder = WALProtos.WALHeader.newBuilder();
216     WALHdrContext hdrCtxt = readHeader(builder, stream);
217     WALHdrResult walHdrRes = hdrCtxt.getResult();
218     if (walHdrRes == WALHdrResult.EOF) {
219       throw new EOFException("Couldn't read WAL PB header");
220     }
221     if (walHdrRes == WALHdrResult.UNKNOWN_WRITER_CLS) {
222       throw new IOException("Got unknown writer class: " + builder.getWriterClsName());
223     }
224     if (isFirst) {
225       WALProtos.WALHeader header = builder.build();
226       this.hasCompression = header.hasHasCompression() && header.getHasCompression();
227       this.hasTagCompression = header.hasHasTagCompression() && header.getHasTagCompression();
228     }
229     this.inputStream = stream;
230     this.walEditsStopOffset = this.fileLength;
231     long currentPosition = stream.getPos();
232     trailerPresent = setTrailerIfPresent();
233     this.seekOnFs(currentPosition);
234     if (LOG.isTraceEnabled()) {
235       LOG.trace("After reading the trailer: walEditsStopOffset: " + this.walEditsStopOffset
236           + ", fileLength: " + this.fileLength + ", " + "trailerPresent: " + (trailerPresent ? "true, size: " + trailer.getSerializedSize() : "false") + ", currentPosition: " + currentPosition);
237     }
238     
239     codecClsName = hdrCtxt.getCellCodecClsName();
240     
241     return hdrCtxt.getCellCodecClsName();
242   }
243 
244   /**
245    * To check whether a trailer is present in a WAL, it seeks to position (fileLength -
246    * PB_WAL_COMPLETE_MAGIC.size() - Bytes.SIZEOF_INT). It reads the int value to know the size of
247    * the trailer, and checks whether the trailer is present at the end or not by comparing the last
248    * PB_WAL_COMPLETE_MAGIC.size() bytes. In case trailer is not present, it returns false;
249    * otherwise, sets the trailer and sets this.walEditsStopOffset variable up to the point just
250    * before the trailer.
251    * <ul>
252    * The trailer is ignored in case:
253    * <li>fileLength is 0 or not correct (when file is under recovery, etc).
254    * <li>the trailer size is negative.
255    * </ul>
256    * <p>
257    * In case the trailer size > this.trailerMaxSize, it is read after a WARN message.
258    * @return true if a valid trailer is present
259    * @throws IOException
260    */
261   private boolean setTrailerIfPresent() {
262     try {
263       long trailerSizeOffset = this.fileLength - (PB_WAL_COMPLETE_MAGIC.length + Bytes.SIZEOF_INT);
264       if (trailerSizeOffset <= 0) return false;// no trailer possible.
265       this.seekOnFs(trailerSizeOffset);
266       // read the int as trailer size.
267       int trailerSize = this.inputStream.readInt();
268       ByteBuffer buf = ByteBuffer.allocate(ProtobufLogReader.PB_WAL_COMPLETE_MAGIC.length);
269       this.inputStream.readFully(buf.array(), buf.arrayOffset(), buf.capacity());
270       if (!Arrays.equals(buf.array(), PB_WAL_COMPLETE_MAGIC)) {
271         LOG.trace("No trailer found.");
272         return false;
273       }
274       if (trailerSize < 0) {
275         LOG.warn("Invalid trailer Size " + trailerSize + ", ignoring the trailer");
276         return false;
277       } else if (trailerSize > this.trailerWarnSize) {
278         // continue reading after warning the user.
279         LOG.warn("Please investigate WALTrailer usage. Trailer size > maximum configured size : "
280           + trailerSize + " > " + this.trailerWarnSize);
281       }
282       // seek to the position where trailer starts.
283       long positionOfTrailer = trailerSizeOffset - trailerSize;
284       this.seekOnFs(positionOfTrailer);
285       // read the trailer.
286       buf = ByteBuffer.allocate(trailerSize);// for trailer.
287       this.inputStream.readFully(buf.array(), buf.arrayOffset(), buf.capacity());
288       trailer = WALTrailer.parseFrom(buf.array());
289       this.walEditsStopOffset = positionOfTrailer;
290       return true;
291     } catch (IOException ioe) {
292       LOG.warn("Got IOE while reading the trailer. Continuing as if no trailer is present.", ioe);
293     }
294     return false;
295   }
296 
297   protected WALCellCodec getCodec(Configuration conf, String cellCodecClsName,
298       CompressionContext compressionContext) throws IOException {
299     return WALCellCodec.create(conf, cellCodecClsName, compressionContext);
300   }
301 
302   @Override
303   protected void initAfterCompression() throws IOException {
304     initAfterCompression(null);
305   }
306   
307   @Override
308   protected void initAfterCompression(String cellCodecClsName) throws IOException {
309     WALCellCodec codec = getCodec(this.conf, cellCodecClsName, this.compressionContext);
310     this.cellDecoder = codec.getDecoder(this.inputStream);
311     if (this.hasCompression) {
312       this.byteStringUncompressor = codec.getByteStringUncompressor();
313     }
314   }
315 
316   @Override
317   protected boolean hasCompression() {
318     return this.hasCompression;
319   }
320 
321   @Override
322   protected boolean hasTagCompression() {
323     return this.hasTagCompression;
324   }
325 
326   @Override
327   protected boolean readNext(Entry entry) throws IOException {
328     while (true) {
329       // OriginalPosition might be < 0 on local fs; if so, it is useless to us.
330       long originalPosition = this.inputStream.getPos();
331       if (trailerPresent && originalPosition > 0 && originalPosition == this.walEditsStopOffset) {
332         if (LOG.isTraceEnabled()) {
333           LOG.trace("Reached end of expected edits area at offset " + originalPosition);
334         }
335         return false;
336       }
337       WALKey.Builder builder = WALKey.newBuilder();
338       long size = 0;
339       boolean resetPosition = false;
340       try {
341         long available = -1;
342         try {
343           int firstByte = this.inputStream.read();
344           if (firstByte == -1) {
345             throw new EOFException("First byte is negative at offset " + originalPosition);
346           }
347           size = CodedInputStream.readRawVarint32(firstByte, this.inputStream);
348           // available may be < 0 on local fs for instance.  If so, can't depend on it.
349           available = this.inputStream.available();
350           if (available > 0 && available < size) {
351             throw new EOFException("Available stream not enough for edit, " +
352                 "inputStream.available()= " + this.inputStream.available() + ", " +
353                 "entry size= " + size + " at offset = " + this.inputStream.getPos());
354           }
355           ProtobufUtil.mergeFrom(builder, new LimitInputStream(this.inputStream, size),
356             (int)size);
357         } catch (InvalidProtocolBufferException ipbe) {
358           resetPosition = true;
359           throw (EOFException) new EOFException("Invalid PB, EOF? Ignoring; originalPosition=" +
360             originalPosition + ", currentPosition=" + this.inputStream.getPos() +
361             ", messageSize=" + size + ", currentAvailable=" + available).initCause(ipbe);
362         }
363         if (!builder.isInitialized()) {
364           // TODO: not clear if we should try to recover from corrupt PB that looks semi-legit.
365           //       If we can get the KV count, we could, theoretically, try to get next record.
366           throw new EOFException("Partial PB while reading WAL, " +
367               "probably an unexpected EOF, ignoring. current offset=" + this.inputStream.getPos());
368         }
369         WALKey walKey = builder.build();
370         entry.getKey().readFieldsFromPb(walKey, this.byteStringUncompressor);
371         if (!walKey.hasFollowingKvCount() || 0 == walKey.getFollowingKvCount()) {
372           if (LOG.isTraceEnabled()) {
373             LOG.trace("WALKey has no KVs that follow it; trying the next one. current offset=" + this.inputStream.getPos());
374           }
375           seekOnFs(originalPosition);
376           return false;
377         }
378         int expectedCells = walKey.getFollowingKvCount();
379         long posBefore = this.inputStream.getPos();
380         try {
381           int actualCells = entry.getEdit().readFromCells(cellDecoder, expectedCells);
382           if (expectedCells != actualCells) {
383             resetPosition = true;
384             throw new EOFException("Only read " + actualCells); // other info added in catch
385           }
386         } catch (Exception ex) {
387           String posAfterStr = "<unknown>";
388           try {
389             posAfterStr = this.inputStream.getPos() + "";
390           } catch (Throwable t) {
391             if (LOG.isTraceEnabled()) {
392               LOG.trace("Error getting pos for error message - ignoring", t);
393             }
394           }
395           String message = " while reading " + expectedCells + " WAL KVs; started reading at "
396               + posBefore + " and read up to " + posAfterStr;
397           IOException realEofEx = extractHiddenEof(ex);
398           throw (EOFException) new EOFException("EOF " + message).
399               initCause(realEofEx != null ? realEofEx : ex);
400         }
401         if (trailerPresent && this.inputStream.getPos() > this.walEditsStopOffset) {
402           LOG.error("Read WALTrailer while reading WALEdits. wal: " + this.path
403               + ", inputStream.getPos(): " + this.inputStream.getPos() + ", walEditsStopOffset: "
404               + this.walEditsStopOffset);
405           throw new EOFException("Read WALTrailer while reading WALEdits");
406         }
407       } catch (EOFException eof) {
408         // If originalPosition is < 0, it is rubbish and we cannot use it (probably local fs)
409         if (originalPosition < 0) {
410           if (LOG.isTraceEnabled()) {
411             LOG.trace("Encountered a malformed edit, but can't seek back to last good position "
412                 + "because originalPosition is negative. last offset="
413                 + this.inputStream.getPos(), eof);
414           }
415           throw eof;
416         }
417         // If stuck at the same place and we got and exception, lets go back at the beginning.
418         if (inputStream.getPos() == originalPosition && resetPosition) {
419           if (LOG.isTraceEnabled()) {
420             LOG.trace("Encountered a malformed edit, seeking to the beginning of the WAL since "
421                 + "current position and original position match at " + originalPosition);
422           }
423           seekOnFs(0);
424         } else {
425           // Else restore our position to original location in hope that next time through we will
426           // read successfully.
427           if (LOG.isTraceEnabled()) {
428             LOG.trace("Encountered a malformed edit, seeking back to last good position in file, "
429                 + "from " + inputStream.getPos()+" to " + originalPosition, eof);
430           }
431           seekOnFs(originalPosition);
432         }
433         return false;
434       }
435       return true;
436     }
437   }
438 
439   private IOException extractHiddenEof(Exception ex) {
440     // There are two problems we are dealing with here. Hadoop stream throws generic exception
441     // for EOF, not EOFException; and scanner further hides it inside RuntimeException.
442     IOException ioEx = null;
443     if (ex instanceof EOFException) {
444       return (EOFException)ex;
445     } else if (ex instanceof IOException) {
446       ioEx = (IOException)ex;
447     } else if (ex instanceof RuntimeException
448         && ex.getCause() != null && ex.getCause() instanceof IOException) {
449       ioEx = (IOException)ex.getCause();
450     }
451     if (ioEx != null) {
452       if (ioEx.getMessage().contains("EOF")) return ioEx;
453       return null;
454     }
455     return null;
456   }
457 
458   @Override
459   protected void seekOnFs(long pos) throws IOException {
460     this.inputStream.seek(pos);
461   }
462 }