001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.wal;
019
020import java.io.IOException;
021import java.io.InterruptedIOException;
022import java.util.List;
023import java.util.concurrent.atomic.AtomicReference;
024import org.apache.hadoop.conf.Configuration;
025import org.apache.hadoop.fs.FileSystem;
026import org.apache.hadoop.fs.Path;
027import org.apache.hadoop.hbase.client.RegionInfo;
028import org.apache.hadoop.hbase.regionserver.wal.MetricsWAL;
029import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
030import org.apache.hadoop.hbase.util.CancelableProgressable;
031import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
032import org.apache.hadoop.hbase.util.LeaseNotRecoveredException;
033import org.apache.hadoop.hbase.wal.WAL.Reader;
034import org.apache.hadoop.hbase.wal.WALProvider.Writer;
035import org.apache.yetus.audience.InterfaceAudience;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038
039import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
040
041/**
042 * Entry point for users of the Write Ahead Log.
043 * Acts as the shim between internal use and the particular WALProvider we use to handle wal
044 * requests.
045 *
046 * Configure which provider gets used with the configuration setting "hbase.wal.provider". Available
047 * implementations:
048 * <ul>
049 *   <li><em>defaultProvider</em> : whatever provider is standard for the hbase version. Currently
050 *                                  "asyncfs"</li>
051 *   <li><em>asyncfs</em> : a provider that will run on top of an implementation of the Hadoop
052 *                             FileSystem interface via an asynchronous client.</li>
053 *   <li><em>filesystem</em> : a provider that will run on top of an implementation of the Hadoop
054 *                             FileSystem interface via HDFS's synchronous DFSClient.</li>
055 *   <li><em>multiwal</em> : a provider that will use multiple "filesystem" wal instances per region
056 *                           server.</li>
057 * </ul>
058 *
059 * Alternatively, you may provide a custom implementation of {@link WALProvider} by class name.
060 */
061@InterfaceAudience.Private
062public class WALFactory {
063
064  private static final Logger LOG = LoggerFactory.getLogger(WALFactory.class);
065
066  /**
067   * Maps between configuration names for providers and implementation classes.
068   */
069  static enum Providers {
070    defaultProvider(AsyncFSWALProvider.class),
071    filesystem(FSHLogProvider.class),
072    multiwal(RegionGroupingProvider.class),
073    asyncfs(AsyncFSWALProvider.class);
074
075    final Class<? extends WALProvider> clazz;
076    Providers(Class<? extends WALProvider> clazz) {
077      this.clazz = clazz;
078    }
079  }
080
081  public static final String WAL_PROVIDER = "hbase.wal.provider";
082  static final String DEFAULT_WAL_PROVIDER = Providers.defaultProvider.name();
083
084  public static final String META_WAL_PROVIDER = "hbase.wal.meta_provider";
085  static final String DEFAULT_META_WAL_PROVIDER = Providers.defaultProvider.name();
086
087  final String factoryId;
088  private final WALProvider provider;
089  // The meta updates are written to a different wal. If this
090  // regionserver holds meta regions, then this ref will be non-null.
091  // lazily intialized; most RegionServers don't deal with META
092  private final AtomicReference<WALProvider> metaProvider = new AtomicReference<>();
093
094  /**
095   * Configuration-specified WAL Reader used when a custom reader is requested
096   */
097  private final Class<? extends AbstractFSWALProvider.Reader> logReaderClass;
098
099  /**
100   * How long to attempt opening in-recovery wals
101   */
102  private final int timeoutMillis;
103
104  private final Configuration conf;
105
106  // Used for the singleton WALFactory, see below.
107  private WALFactory(Configuration conf) {
108    // this code is duplicated here so we can keep our members final.
109    // until we've moved reader/writer construction down into providers, this initialization must
110    // happen prior to provider initialization, in case they need to instantiate a reader/writer.
111    timeoutMillis = conf.getInt("hbase.hlog.open.timeout", 300000);
112    /* TODO Both of these are probably specific to the fs wal provider */
113    logReaderClass = conf.getClass("hbase.regionserver.hlog.reader.impl", ProtobufLogReader.class,
114      AbstractFSWALProvider.Reader.class);
115    this.conf = conf;
116    // end required early initialization
117
118    // this instance can't create wals, just reader/writers.
119    provider = null;
120    factoryId = SINGLETON_ID;
121  }
122
123  @VisibleForTesting
124  public Class<? extends WALProvider> getProviderClass(String key, String defaultValue) {
125    try {
126      return Providers.valueOf(conf.get(key, defaultValue)).clazz;
127    } catch (IllegalArgumentException exception) {
128      // Fall back to them specifying a class name
129      // Note that the passed default class shouldn't actually be used, since the above only fails
130      // when there is a config value present.
131      return conf.getClass(key, Providers.defaultProvider.clazz, WALProvider.class);
132    }
133  }
134
135  WALProvider createProvider(Class<? extends WALProvider> clazz, String providerId)
136      throws IOException {
137    LOG.info("Instantiating WALProvider of type " + clazz);
138    try {
139      final WALProvider result = clazz.getDeclaredConstructor().newInstance();
140      result.init(this, conf, providerId);
141      return result;
142    } catch (Exception e) {
143      LOG.error("couldn't set up WALProvider, the configured class is " + clazz);
144      LOG.debug("Exception details for failure to load WALProvider.", e);
145      throw new IOException("couldn't set up WALProvider", e);
146    }
147  }
148
149  /**
150   * instantiate a provider from a config property. requires conf to have already been set (as well
151   * as anything the provider might need to read).
152   */
153  WALProvider getProvider(String key, String defaultValue, String providerId) throws IOException {
154    Class<? extends WALProvider> clazz = getProviderClass(key, defaultValue);
155    WALProvider provider = createProvider(clazz, providerId);
156    provider.addWALActionsListener(new MetricsWAL());
157    return provider;
158  }
159
160  /**
161   * @param conf must not be null, will keep a reference to read params in later reader/writer
162   *          instances.
163   * @param factoryId a unique identifier for this factory. used i.e. by filesystem implementations
164   *          to make a directory
165   */
166  public WALFactory(Configuration conf, String factoryId) throws IOException {
167    // until we've moved reader/writer construction down into providers, this initialization must
168    // happen prior to provider initialization, in case they need to instantiate a reader/writer.
169    timeoutMillis = conf.getInt("hbase.hlog.open.timeout", 300000);
170    /* TODO Both of these are probably specific to the fs wal provider */
171    logReaderClass = conf.getClass("hbase.regionserver.hlog.reader.impl", ProtobufLogReader.class,
172      AbstractFSWALProvider.Reader.class);
173    this.conf = conf;
174    this.factoryId = factoryId;
175    // end required early initialization
176    if (conf.getBoolean("hbase.regionserver.hlog.enabled", true)) {
177      provider = getProvider(WAL_PROVIDER, DEFAULT_WAL_PROVIDER, null);
178    } else {
179      // special handling of existing configuration behavior.
180      LOG.warn("Running with WAL disabled.");
181      provider = new DisabledWALProvider();
182      provider.init(this, conf, factoryId);
183    }
184  }
185
186  /**
187   * Shutdown all WALs and clean up any underlying storage.
188   * Use only when you will not need to replay and edits that have gone to any wals from this
189   * factory.
190   */
191  public void close() throws IOException {
192    final WALProvider metaProvider = this.metaProvider.get();
193    if (null != metaProvider) {
194      metaProvider.close();
195    }
196    // close is called on a WALFactory with null provider in the case of contention handling
197    // within the getInstance method.
198    if (null != provider) {
199      provider.close();
200    }
201  }
202
203  /**
204   * Tell the underlying WAL providers to shut down, but do not clean up underlying storage.
205   * If you are not ending cleanly and will need to replay edits from this factory's wals,
206   * use this method if you can as it will try to leave things as tidy as possible.
207   */
208  public void shutdown() throws IOException {
209    IOException exception = null;
210    final WALProvider metaProvider = this.metaProvider.get();
211    if (null != metaProvider) {
212      try {
213        metaProvider.shutdown();
214      } catch(IOException ioe) {
215        exception = ioe;
216      }
217    }
218    provider.shutdown();
219    if (null != exception) {
220      throw exception;
221    }
222  }
223
224  public List<WAL> getWALs() {
225    return provider.getWALs();
226  }
227
228  private WALProvider getMetaProvider() throws IOException {
229    for (;;) {
230      WALProvider provider = this.metaProvider.get();
231      if (provider != null) {
232        return provider;
233      }
234      provider = getProvider(META_WAL_PROVIDER, DEFAULT_META_WAL_PROVIDER,
235        AbstractFSWALProvider.META_WAL_PROVIDER_ID);
236      if (metaProvider.compareAndSet(null, provider)) {
237        return provider;
238      } else {
239        // someone is ahead of us, close and try again.
240        provider.close();
241      }
242    }
243  }
244
245  /**
246   * @param region the region which we want to get a WAL for it. Could be null.
247   */
248  public WAL getWAL(RegionInfo region) throws IOException {
249    // use different WAL for hbase:meta
250    if (region != null && region.isMetaRegion() &&
251      region.getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID) {
252      return getMetaProvider().getWAL(region);
253    } else {
254      return provider.getWAL(region);
255    }
256  }
257
258  public Reader createReader(final FileSystem fs, final Path path) throws IOException {
259    return createReader(fs, path, (CancelableProgressable)null);
260  }
261
262  /**
263   * Create a reader for the WAL. If you are reading from a file that's being written to and need
264   * to reopen it multiple times, use {@link WAL.Reader#reset()} instead of this method
265   * then just seek back to the last known good position.
266   * @return A WAL reader.  Close when done with it.
267   * @throws IOException
268   */
269  public Reader createReader(final FileSystem fs, final Path path,
270      CancelableProgressable reporter) throws IOException {
271    return createReader(fs, path, reporter, true);
272  }
273
274  public Reader createReader(final FileSystem fs, final Path path, CancelableProgressable reporter,
275      boolean allowCustom) throws IOException {
276    Class<? extends AbstractFSWALProvider.Reader> lrClass =
277        allowCustom ? logReaderClass : ProtobufLogReader.class;
278    try {
279      // A wal file could be under recovery, so it may take several
280      // tries to get it open. Instead of claiming it is corrupted, retry
281      // to open it up to 5 minutes by default.
282      long startWaiting = EnvironmentEdgeManager.currentTime();
283      long openTimeout = timeoutMillis + startWaiting;
284      int nbAttempt = 0;
285      AbstractFSWALProvider.Reader reader = null;
286      while (true) {
287        try {
288          reader = lrClass.getDeclaredConstructor().newInstance();
289          reader.init(fs, path, conf, null);
290          return reader;
291        } catch (IOException e) {
292          if (reader != null) {
293            try {
294              reader.close();
295            } catch (IOException exception) {
296              LOG.warn("Could not close FSDataInputStream" + exception.getMessage());
297              LOG.debug("exception details", exception);
298            }
299          }
300
301          String msg = e.getMessage();
302          if (msg != null
303              && (msg.contains("Cannot obtain block length")
304                  || msg.contains("Could not obtain the last block") || msg
305                    .matches("Blocklist for [^ ]* has changed.*"))) {
306            if (++nbAttempt == 1) {
307              LOG.warn("Lease should have recovered. This is not expected. Will retry", e);
308            }
309            if (reporter != null && !reporter.progress()) {
310              throw new InterruptedIOException("Operation is cancelled");
311            }
312            if (nbAttempt > 2 && openTimeout < EnvironmentEdgeManager.currentTime()) {
313              LOG.error("Can't open after " + nbAttempt + " attempts and "
314                  + (EnvironmentEdgeManager.currentTime() - startWaiting) + "ms " + " for " + path);
315            } else {
316              try {
317                Thread.sleep(nbAttempt < 3 ? 500 : 1000);
318                continue; // retry
319              } catch (InterruptedException ie) {
320                InterruptedIOException iioe = new InterruptedIOException();
321                iioe.initCause(ie);
322                throw iioe;
323              }
324            }
325            throw new LeaseNotRecoveredException(e);
326          } else {
327            throw e;
328          }
329        }
330      }
331    } catch (IOException ie) {
332      throw ie;
333    } catch (Exception e) {
334      throw new IOException("Cannot get log reader", e);
335    }
336  }
337
338  /**
339   * Create a writer for the WAL.
340   * Uses defaults.
341   * <p>
342   * Should be package-private. public only for tests and
343   * {@link org.apache.hadoop.hbase.regionserver.wal.Compressor}
344   * @return A WAL writer. Close when done with it.
345   */
346  public Writer createWALWriter(final FileSystem fs, final Path path) throws IOException {
347    return FSHLogProvider.createWriter(conf, fs, path, false);
348  }
349
350  /**
351   * Should be package-private, visible for recovery testing.
352   * Uses defaults.
353   * @return an overwritable writer for recovered edits. caller should close.
354   */
355  @VisibleForTesting
356  public Writer createRecoveredEditsWriter(final FileSystem fs, final Path path)
357      throws IOException {
358    return FSHLogProvider.createWriter(conf, fs, path, true);
359  }
360
361  // These static methods are currently used where it's impractical to
362  // untangle the reliance on state in the filesystem. They rely on singleton
363  // WALFactory that just provides Reader / Writers.
364  // For now, first Configuration object wins. Practically this just impacts the reader/writer class
365  private static final AtomicReference<WALFactory> singleton = new AtomicReference<>();
366  private static final String SINGLETON_ID = WALFactory.class.getName();
367  
368  // Public only for FSHLog
369  public static WALFactory getInstance(Configuration configuration) {
370    WALFactory factory = singleton.get();
371    if (null == factory) {
372      WALFactory temp = new WALFactory(configuration);
373      if (singleton.compareAndSet(null, temp)) {
374        factory = temp;
375      } else {
376        // someone else beat us to initializing
377        try {
378          temp.close();
379        } catch (IOException exception) {
380          LOG.debug("failed to close temporary singleton. ignoring.", exception);
381        }
382        factory = singleton.get();
383      }
384    }
385    return factory;
386  }
387
388  /**
389   * Create a reader for the given path, accept custom reader classes from conf.
390   * If you already have a WALFactory, you should favor the instance method.
391   * @return a WAL Reader, caller must close.
392   */
393  public static Reader createReader(final FileSystem fs, final Path path,
394      final Configuration configuration) throws IOException {
395    return getInstance(configuration).createReader(fs, path);
396  }
397
398  /**
399   * Create a reader for the given path, accept custom reader classes from conf.
400   * If you already have a WALFactory, you should favor the instance method.
401   * @return a WAL Reader, caller must close.
402   */
403  static Reader createReader(final FileSystem fs, final Path path,
404      final Configuration configuration, final CancelableProgressable reporter) throws IOException {
405    return getInstance(configuration).createReader(fs, path, reporter);
406  }
407
408  /**
409   * Create a reader for the given path, ignore custom reader classes from conf.
410   * If you already have a WALFactory, you should favor the instance method.
411   * only public pending move of {@link org.apache.hadoop.hbase.regionserver.wal.Compressor}
412   * @return a WAL Reader, caller must close.
413   */
414  public static Reader createReaderIgnoreCustomClass(final FileSystem fs, final Path path,
415      final Configuration configuration) throws IOException {
416    return getInstance(configuration).createReader(fs, path, null, false);
417  }
418
419  /**
420   * If you already have a WALFactory, you should favor the instance method.
421   * Uses defaults.
422   * @return a Writer that will overwrite files. Caller must close.
423   */
424  static Writer createRecoveredEditsWriter(final FileSystem fs, final Path path,
425      final Configuration configuration)
426      throws IOException {
427    return FSHLogProvider.createWriter(configuration, fs, path, true);
428  }
429
430  /**
431   * If you already have a WALFactory, you should favor the instance method.
432   * Uses defaults.
433   * @return a writer that won't overwrite files. Caller must close.
434   */
435  @VisibleForTesting
436  public static Writer createWALWriter(final FileSystem fs, final Path path,
437      final Configuration configuration)
438      throws IOException {
439    return FSHLogProvider.createWriter(configuration, fs, path, false);
440  }
441
442  public final WALProvider getWALProvider() {
443    return this.provider;
444  }
445
446  public final WALProvider getMetaWALProvider() {
447    return this.metaProvider.get();
448  }
449}