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  
21  package org.apache.hadoop.hbase.regionserver.wal;
22  
23  import java.io.IOException;
24  import java.util.Arrays;
25  import java.io.InterruptedIOException;
26  import java.util.List;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.classification.InterfaceAudience;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.fs.FSDataInputStream;
33  import org.apache.hadoop.fs.FileSystem;
34  import org.apache.hadoop.fs.Path;
35  import org.apache.hadoop.hbase.HConstants;
36  import org.apache.hadoop.hbase.regionserver.wal.HLog.Reader;
37  import org.apache.hadoop.hbase.regionserver.wal.HLog.Writer;
38  import org.apache.hadoop.hbase.util.CancelableProgressable;
39  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
40  
41  @InterfaceAudience.Private
42  public class HLogFactory {
43      private static final Log LOG = LogFactory.getLog(HLogFactory.class);
44  
45      public static HLog createHLog(final FileSystem fs, final Path root, final String logName,
46          final Configuration conf) throws IOException {
47        return new FSHLog(fs, root, logName, conf);
48      }
49      
50      public static HLog createHLog(final FileSystem fs, final Path root, final String logName,
51          final String oldLogName, final Configuration conf) throws IOException {
52        return new FSHLog(fs, root, logName, oldLogName, conf, null, true, null, false);
53  }
54      
55      public static HLog createHLog(final FileSystem fs, final Path root, final String logName,
56          final Configuration conf, final List<WALActionsListener> listeners,
57          final String prefix) throws IOException {
58        return new FSHLog(fs, root, logName, HConstants.HREGION_OLDLOGDIR_NAME, conf, listeners,
59          true, prefix, false);
60      }
61  
62      public static HLog createMetaHLog(final FileSystem fs, final Path root, final String logName,
63          final Configuration conf, final List<WALActionsListener> listeners,
64          final String prefix) throws IOException {
65        return new FSHLog(fs, root, logName, HConstants.HREGION_OLDLOGDIR_NAME, conf, listeners,
66          false, prefix, true);
67      }
68  
69      /*
70       * WAL Reader
71       */
72      private static Class<? extends Reader> logReaderClass;
73  
74      static void resetLogReaderClass() {
75        logReaderClass = null;
76      }
77  
78      public static HLog.Reader createReader(final FileSystem fs,
79          final Path path, Configuration conf) throws IOException {
80        return createReader(fs, path, conf, null);
81      }
82  
83      /**
84       * Create a reader for the WAL. If you are reading from a file that's being written to
85       * and need to reopen it multiple times, use {@link HLog.Reader#reset()} instead of this method
86       * then just seek back to the last known good position.
87       * @return A WAL reader.  Close when done with it.
88       * @throws IOException
89       */
90      public static HLog.Reader createReader(final FileSystem fs, final Path path,
91          Configuration conf, CancelableProgressable reporter) throws IOException {
92        return createReader(fs, path, conf, reporter, true);
93      }
94  
95      public static HLog.Reader createReader(final FileSystem fs, final Path path,
96        Configuration conf, CancelableProgressable reporter, boolean allowCustom)
97          throws IOException {
98        if (allowCustom && (logReaderClass == null)) {
99          logReaderClass = conf.getClass("hbase.regionserver.hlog.reader.impl",
100           ProtobufLogReader.class, Reader.class);
101       }
102       Class<? extends Reader> lrClass = allowCustom ? logReaderClass : ProtobufLogReader.class;
103 
104       try {
105         // A hlog file could be under recovery, so it may take several
106         // tries to get it open. Instead of claiming it is corrupted, retry
107         // to open it up to 5 minutes by default.
108         long startWaiting = EnvironmentEdgeManager.currentTime();
109         long openTimeout = conf.getInt("hbase.hlog.open.timeout", 300000) + startWaiting;
110         int nbAttempt = 0;
111         while (true) {
112           try {
113             if (lrClass != ProtobufLogReader.class) {
114               // User is overriding the WAL reader, let them.
115               HLog.Reader reader = lrClass.newInstance();
116               reader.init(fs, path, conf, null);
117               return reader;
118             } else {
119               FSDataInputStream stream = fs.open(path);
120               // Note that zero-length file will fail to read PB magic, and attempt to create
121               // a non-PB reader and fail the same way existing code expects it to. If we get
122               // rid of the old reader entirely, we need to handle 0-size files differently from
123               // merely non-PB files.
124               byte[] magic = new byte[ProtobufLogReader.PB_WAL_MAGIC.length];
125               boolean isPbWal = (stream.read(magic) == magic.length)
126                   && Arrays.equals(magic, ProtobufLogReader.PB_WAL_MAGIC);
127               HLog.Reader reader =
128                   isPbWal ? new ProtobufLogReader() : new SequenceFileLogReader();
129               reader.init(fs, path, conf, stream);
130               return reader;
131             }
132           } catch (IOException e) {
133             String msg = e.getMessage();
134             if (msg != null && (msg.contains("Cannot obtain block length")
135                 || msg.contains("Could not obtain the last block")
136                 || msg.matches("Blocklist for [^ ]* has changed.*"))) {
137               if (++nbAttempt == 1) {
138                 LOG.warn("Lease should have recovered. This is not expected. Will retry", e);
139               }
140               if (reporter != null && !reporter.progress()) {
141                 throw new InterruptedIOException("Operation is cancelled");
142               }
143               if (nbAttempt > 2 && openTimeout < EnvironmentEdgeManager.currentTime()) {
144                 LOG.error("Can't open after " + nbAttempt + " attempts and "
145                   + (EnvironmentEdgeManager.currentTime() - startWaiting)
146                   + "ms " + " for " + path);
147               } else {
148                 try {
149                   Thread.sleep(nbAttempt < 3 ? 500 : 1000);
150                   continue; // retry
151                 } catch (InterruptedException ie) {
152                   InterruptedIOException iioe = new InterruptedIOException();
153                   iioe.initCause(ie);
154                   throw iioe;
155                 }
156               }
157             }
158             throw e;
159           }
160         }
161       } catch (IOException ie) {
162         throw ie;
163       } catch (Exception e) {
164         throw new IOException("Cannot get log reader", e);
165       }
166     }
167 
168     /*
169      * WAL writer
170      */
171     private static Class<? extends Writer> logWriterClass;
172 
173     static void resetLogWriterClass() {
174       logWriterClass = null;
175     }
176 
177     /**
178      * Create a writer for the WAL.
179      * @return A WAL writer.  Close when done with it.
180      * @throws IOException
181      */
182     public static HLog.Writer createWALWriter(final FileSystem fs,
183         final Path path, Configuration conf) throws IOException {
184       return createWriter(fs, path, conf, false);
185     }
186 
187     public static HLog.Writer createRecoveredEditsWriter(final FileSystem fs,
188         final Path path, Configuration conf) throws IOException {
189       return createWriter(fs, path, conf, true);
190     }
191 
192     private static HLog.Writer createWriter(final FileSystem fs,
193         final Path path, Configuration conf, boolean overwritable)
194     throws IOException {
195       try {
196         if (logWriterClass == null) {
197           logWriterClass = conf.getClass("hbase.regionserver.hlog.writer.impl",
198               ProtobufLogWriter.class, Writer.class);
199         }
200         HLog.Writer writer = (HLog.Writer)logWriterClass.newInstance();
201         writer.init(fs, path, conf, overwritable);
202         return writer;
203       } catch (Exception e) {
204         throw new IOException("cannot get log writer", e);
205       }
206     }
207 }