001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.wal;
020
021import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.DEFAULT_PROVIDER_ID;
022import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.META_WAL_PROVIDER_ID;
023import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.WAL_FILE_NAME_DELIMITER;
024
025import java.io.IOException;
026import java.util.ArrayList;
027import java.util.Collection;
028import java.util.Collections;
029import java.util.List;
030import java.util.concurrent.atomic.AtomicBoolean;
031
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.fs.FileSystem;
034import org.apache.hadoop.fs.Path;
035import org.apache.hadoop.hbase.Abortable;
036import org.apache.hadoop.hbase.HConstants;
037import org.apache.hadoop.hbase.client.RegionInfo;
038// imports for things that haven't moved from regionserver.wal yet.
039import org.apache.hadoop.hbase.io.asyncfs.monitor.StreamSlowMonitor;
040import org.apache.hadoop.hbase.regionserver.wal.FSHLog;
041import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter;
042import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
043import org.apache.hadoop.hbase.util.CommonFSUtils;
044import org.apache.hadoop.hbase.wal.WAL.Entry;
045import org.apache.yetus.audience.InterfaceAudience;
046import org.slf4j.Logger;
047import org.slf4j.LoggerFactory;
048
049/**
050 * A WAL Provider that returns a single thread safe WAL that optionally can skip parts of our normal
051 * interactions with HDFS.
052 * <p>
053 * This implementation picks a directory in HDFS based on the same mechanisms as the
054 * {@link FSHLogProvider}. Users can configure how much interaction we have with HDFS with the
055 * configuration property "hbase.wal.iotestprovider.operations". The value should be a comma
056 * separated list of allowed operations:
057 * <ul>
058 * <li><em>append</em> : edits will be written to the underlying filesystem</li>
059 * <li><em>sync</em> : wal syncs will result in hflush calls</li>
060 * <li><em>fileroll</em> : roll requests will result in creating a new file on the underlying
061 * filesystem.</li>
062 * </ul>
063 * Additionally, the special cases "all" and "none" are recognized. If ommited, the value defaults
064 * to "all." Behavior is undefined if "all" or "none" are paired with additional values. Behavior is
065 * also undefined if values not listed above are included.
066 * <p>
067 * Only those operations listed will occur between the returned WAL and HDFS. All others will be
068 * no-ops.
069 * <p>
070 * Note that in the case of allowing "append" operations but not allowing "fileroll", the returned
071 * WAL will just keep writing to the same file. This won't avoid all costs associated with file
072 * management over time, becaue the data set size may result in additional HDFS block allocations.
073 */
074@InterfaceAudience.Private
075public class IOTestProvider implements WALProvider {
076  private static final Logger LOG = LoggerFactory.getLogger(IOTestProvider.class);
077
078  private static final String ALLOWED_OPERATIONS = "hbase.wal.iotestprovider.operations";
079  private enum AllowedOperations {
080    all,
081    append,
082    sync,
083    fileroll,
084    none
085  }
086
087  private WALFactory factory;
088
089  private Configuration conf;
090
091  private volatile FSHLog log;
092
093  private String providerId;
094  protected AtomicBoolean initialized = new AtomicBoolean(false);
095
096  private List<WALActionsListener> listeners = new ArrayList<>();
097  /**
098   * @param factory factory that made us, identity used for FS layout. may not be null
099   * @param conf may not be null
100   * @param providerId differentiate between providers from one facotry, used for FS layout. may be
101   *                   null
102   */
103  @Override
104  public void init(WALFactory factory, Configuration conf, String providerId, Abortable abortable)
105      throws IOException {
106    if (!initialized.compareAndSet(false, true)) {
107      throw new IllegalStateException("WALProvider.init should only be called once.");
108    }
109    this.factory = factory;
110    this.conf = conf;
111    this.providerId = providerId != null ? providerId : DEFAULT_PROVIDER_ID;
112  }
113
114  @Override
115  public List<WAL> getWALs() {
116    return Collections.singletonList(log);
117  }
118
119  private FSHLog createWAL() throws IOException {
120    String logPrefix = factory.factoryId + WAL_FILE_NAME_DELIMITER + providerId;
121    return new IOTestWAL(CommonFSUtils.getWALFileSystem(conf), CommonFSUtils.getWALRootDir(conf),
122        AbstractFSWALProvider.getWALDirectoryName(factory.factoryId),
123        HConstants.HREGION_OLDLOGDIR_NAME, conf, listeners, true, logPrefix,
124        META_WAL_PROVIDER_ID.equals(providerId) ? META_WAL_PROVIDER_ID : null);
125  }
126
127  @Override
128  public WAL getWAL(RegionInfo region) throws IOException {
129    FSHLog log = this.log;
130    if (log != null) {
131      return log;
132    }
133    synchronized (this) {
134      log = this.log;
135      if (log == null) {
136        log = createWAL();
137        this.log = log;
138      }
139    }
140    return log;
141  }
142
143  @Override
144  public void close() throws IOException {
145    FSHLog log = this.log;
146    if (log != null) {
147      log.close();
148    }
149  }
150
151  @Override
152  public void shutdown() throws IOException {
153    FSHLog log = this.log;
154    if (log != null) {
155      log.shutdown();
156    }
157  }
158
159  private static class IOTestWAL extends FSHLog {
160
161    private final boolean doFileRolls;
162
163    // Used to differntiate between roll calls before and after we finish construction.
164    private final boolean initialized;
165
166    /**
167     * Create an edit log at the given <code>dir</code> location.
168     *
169     * You should never have to load an existing log. If there is a log at
170     * startup, it should have already been processed and deleted by the time the
171     * WAL object is started up.
172     *
173     * @param fs filesystem handle
174     * @param rootDir path to where logs and oldlogs
175     * @param logDir dir where wals are stored
176     * @param archiveDir dir where wals are archived
177     * @param conf configuration to use
178     * @param listeners Listeners on WAL events. Listeners passed here will
179     * be registered before we do anything else; e.g. the
180     * Constructor {@link #rollWriter()}.
181     * @param failIfWALExists If true IOException will be thrown if files related to this wal
182     *        already exist.
183     * @param prefix should always be hostname and port in distributed env and
184     *        it will be URL encoded before being used.
185     *        If prefix is null, "wal" will be used
186     * @param suffix will be url encoded. null is treated as empty. non-empty must start with
187     *        {@link AbstractFSWALProvider#WAL_FILE_NAME_DELIMITER}
188     * @throws IOException
189     */
190    public IOTestWAL(final FileSystem fs, final Path rootDir, final String logDir,
191        final String archiveDir, final Configuration conf,
192        final List<WALActionsListener> listeners,
193        final boolean failIfWALExists, final String prefix, final String suffix)
194        throws IOException {
195      super(fs, rootDir, logDir, archiveDir, conf, listeners, failIfWALExists, prefix, suffix);
196      Collection<String> operations = conf.getStringCollection(ALLOWED_OPERATIONS);
197      doFileRolls = operations.isEmpty() || operations.contains(AllowedOperations.all.name()) ||
198          operations.contains(AllowedOperations.fileroll.name());
199      initialized = true;
200      LOG.info("Initialized with file rolling " + (doFileRolls ? "enabled" : "disabled"));
201    }
202
203    private Writer noRollsWriter;
204
205    // creatWriterInstance is where the new pipeline is set up for doing file rolls
206    // if we are skipping it, just keep returning the same writer.
207    @Override
208    protected Writer createWriterInstance(final Path path) throws IOException {
209      // we get called from the FSHLog constructor (!); always roll in this case since
210      // we don't know yet if we're supposed to generally roll and
211      // we need an initial file in the case of doing appends but no rolls.
212      if (!initialized || doFileRolls) {
213        LOG.info("creating new writer instance.");
214        final ProtobufLogWriter writer = new IOTestWriter();
215        try {
216          writer.init(fs, path, conf, false, this.blocksize,
217              StreamSlowMonitor.create(conf, path.getName()));
218        } catch (CommonFSUtils.StreamLacksCapabilityException exception) {
219          throw new IOException("Can't create writer instance because underlying FileSystem " +
220              "doesn't support needed stream capabilities.", exception);
221        }
222        if (!initialized) {
223          LOG.info("storing initial writer instance in case file rolling isn't allowed.");
224          noRollsWriter = writer;
225        }
226        return writer;
227      } else {
228        LOG.info("WAL rolling disabled, returning the first writer.");
229        // Initial assignment happens during the constructor call, so there ought not be
230        // a race for first assignment.
231        return noRollsWriter;
232      }
233    }
234  }
235
236  /**
237   * Presumes init will be called by a single thread prior to any access of other methods.
238   */
239  private static class IOTestWriter extends ProtobufLogWriter {
240    private boolean doAppends;
241    private boolean doSyncs;
242
243    @Override
244    public void init(FileSystem fs, Path path, Configuration conf, boolean overwritable,
245        long blocksize, StreamSlowMonitor monitor) throws IOException,
246        CommonFSUtils.StreamLacksCapabilityException {
247      Collection<String> operations = conf.getStringCollection(ALLOWED_OPERATIONS);
248      if (operations.isEmpty() || operations.contains(AllowedOperations.all.name())) {
249        doAppends = doSyncs = true;
250      } else if (operations.contains(AllowedOperations.none.name())) {
251        doAppends = doSyncs = false;
252      } else {
253        doAppends = operations.contains(AllowedOperations.append.name());
254        doSyncs = operations.contains(AllowedOperations.sync.name());
255      }
256      LOG.info("IOTestWriter initialized with appends " + (doAppends ? "enabled" : "disabled") +
257          " and syncs " + (doSyncs ? "enabled" : "disabled"));
258      super.init(fs, path, conf, overwritable, blocksize, monitor);
259    }
260
261    @Override
262    protected String getWriterClassName() {
263      return ProtobufLogWriter.class.getSimpleName();
264    }
265
266    @Override
267    public void append(Entry entry) throws IOException {
268      if (doAppends) {
269        super.append(entry);
270      }
271    }
272
273    @Override
274    public void sync(boolean forceSync) throws IOException {
275      if (doSyncs) {
276        super.sync(forceSync);
277      }
278    }
279  }
280
281  @Override
282  public long getNumLogFiles() {
283    return this.log.getNumLogFiles();
284  }
285
286  @Override
287  public long getLogFileSize() {
288    return this.log.getLogFileSize();
289  }
290
291  @Override
292  public void addWALActionsListener(WALActionsListener listener) {
293    // TODO Implement WALProvider.addWALActionLister
294
295  }
296}