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 */
018
019package org.apache.hadoop.hbase.mapreduce;
020
021import java.io.DataInput;
022import java.io.DataOutput;
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.List;
026import org.apache.hadoop.fs.Path;
027import org.apache.hadoop.hbase.client.RegionInfo;
028import org.apache.hadoop.hbase.client.Result;
029import org.apache.hadoop.hbase.client.Scan;
030import org.apache.hadoop.hbase.client.TableDescriptor;
031import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
032import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
033import org.apache.hadoop.hbase.util.RegionSplitter;
034import org.apache.hadoop.io.Writable;
035import org.apache.hadoop.mapreduce.InputFormat;
036import org.apache.hadoop.mapreduce.InputSplit;
037import org.apache.hadoop.mapreduce.Job;
038import org.apache.hadoop.mapreduce.JobContext;
039import org.apache.hadoop.mapreduce.RecordReader;
040import org.apache.hadoop.mapreduce.TaskAttemptContext;
041import org.apache.yetus.audience.InterfaceAudience;
042
043/**
044 * TableSnapshotInputFormat allows a MapReduce job to run over a table snapshot. The job
045 * bypasses HBase servers, and directly accesses the underlying files (hfile, recovered edits,
046 * wals, etc) directly to provide maximum performance. The snapshot is not required to be
047 * restored to the live cluster or cloned. This also allows to run the mapreduce job from an
048 * online or offline hbase cluster. The snapshot files can be exported by using the
049 * {@link org.apache.hadoop.hbase.snapshot.ExportSnapshot} tool, to a pure-hdfs cluster,
050 * and this InputFormat can be used to run the mapreduce job directly over the snapshot files.
051 * The snapshot should not be deleted while there are jobs reading from snapshot files.
052 * <p>
053 * Usage is similar to TableInputFormat, and
054 * {@link TableMapReduceUtil#initTableSnapshotMapperJob(String, Scan, Class, Class, Class, Job, boolean, Path)}
055 * can be used to configure the job.
056 * <pre>{@code
057 * Job job = new Job(conf);
058 * Scan scan = new Scan();
059 * TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName,
060 *      scan, MyTableMapper.class, MyMapKeyOutput.class,
061 *      MyMapOutputValueWritable.class, job, true);
062 * }
063 * </pre>
064 * <p>
065 * Internally, this input format restores the snapshot into the given tmp directory. By default,
066 * and similar to {@link TableInputFormat} an InputSplit is created per region, but optionally you
067 * can run N mapper tasks per every region, in which case the region key range will be split to
068 * N sub-ranges and an InputSplit will be created per sub-range. The region is opened for reading
069 * from each RecordReader. An internal RegionScanner is used to execute the
070 * {@link org.apache.hadoop.hbase.CellScanner} obtained from the user.
071 * <p>
072 * HBase owns all the data and snapshot files on the filesystem. Only the 'hbase' user can read from
073 * snapshot files and data files.
074 * To read from snapshot files directly from the file system, the user who is running the MR job
075 * must have sufficient permissions to access snapshot and reference files.
076 * This means that to run mapreduce over snapshot files, the MR job has to be run as the HBase
077 * user or the user must have group or other privileges in the filesystem (See HBASE-8369).
078 * Note that, given other users access to read from snapshot/data files will completely circumvent
079 * the access control enforced by HBase.
080 * @see org.apache.hadoop.hbase.client.TableSnapshotScanner
081 */
082@InterfaceAudience.Public
083public class TableSnapshotInputFormat extends InputFormat<ImmutableBytesWritable, Result> {
084
085  public static class TableSnapshotRegionSplit extends InputSplit implements Writable {
086    private TableSnapshotInputFormatImpl.InputSplit delegate;
087
088    // constructor for mapreduce framework / Writable
089    public TableSnapshotRegionSplit() {
090      this.delegate = new TableSnapshotInputFormatImpl.InputSplit();
091    }
092
093    public TableSnapshotRegionSplit(TableSnapshotInputFormatImpl.InputSplit delegate) {
094      this.delegate = delegate;
095    }
096
097    public TableSnapshotRegionSplit(TableDescriptor htd, RegionInfo regionInfo,
098        List<String> locations, Scan scan, Path restoreDir) {
099      this.delegate =
100          new TableSnapshotInputFormatImpl.InputSplit(htd, regionInfo, locations, scan, restoreDir);
101    }
102
103    @Override
104    public long getLength() throws IOException, InterruptedException {
105      return delegate.getLength();
106    }
107
108    @Override
109    public String[] getLocations() throws IOException, InterruptedException {
110      return delegate.getLocations();
111    }
112
113    @Override
114    public void write(DataOutput out) throws IOException {
115      delegate.write(out);
116    }
117
118    @Override
119    public void readFields(DataInput in) throws IOException {
120      delegate.readFields(in);
121    }
122
123    public RegionInfo getRegion() {
124      return delegate.getRegionInfo();
125    }
126
127    TableSnapshotInputFormatImpl.InputSplit getDelegate() {
128      return this.delegate;
129    }
130  }
131
132  @InterfaceAudience.Private
133  static class TableSnapshotRegionRecordReader extends
134      RecordReader<ImmutableBytesWritable, Result> {
135    private TableSnapshotInputFormatImpl.RecordReader delegate =
136      new TableSnapshotInputFormatImpl.RecordReader();
137    private TaskAttemptContext context;
138
139    @Override
140    public void initialize(InputSplit split, TaskAttemptContext context) throws IOException,
141        InterruptedException {
142      this.context = context;
143      delegate.initialize(
144        ((TableSnapshotRegionSplit) split).delegate,
145        context.getConfiguration());
146    }
147
148    @Override
149    public boolean nextKeyValue() throws IOException, InterruptedException {
150      boolean result = delegate.nextKeyValue();
151      if (result) {
152        ScanMetrics scanMetrics = delegate.getScanner().getScanMetrics();
153        if (scanMetrics != null && context != null) {
154          TableRecordReaderImpl.updateCounters(scanMetrics, 0, context, 0);
155        }
156      }
157      return result;
158    }
159
160    @Override
161    public ImmutableBytesWritable getCurrentKey() throws IOException, InterruptedException {
162      return delegate.getCurrentKey();
163    }
164
165    @Override
166    public Result getCurrentValue() throws IOException, InterruptedException {
167      return delegate.getCurrentValue();
168    }
169
170    @Override
171    public float getProgress() throws IOException, InterruptedException {
172      return delegate.getProgress();
173    }
174
175    @Override
176    public void close() throws IOException {
177      delegate.close();
178    }
179  }
180
181  @Override
182  public RecordReader<ImmutableBytesWritable, Result> createRecordReader(
183      InputSplit split, TaskAttemptContext context) throws IOException {
184    return new TableSnapshotRegionRecordReader();
185  }
186
187  @Override
188  public List<InputSplit> getSplits(JobContext job) throws IOException, InterruptedException {
189    List<InputSplit> results = new ArrayList<>();
190    for (TableSnapshotInputFormatImpl.InputSplit split :
191        TableSnapshotInputFormatImpl.getSplits(job.getConfiguration())) {
192      results.add(new TableSnapshotRegionSplit(split));
193    }
194    return results;
195  }
196
197  /**
198   * Configures the job to use TableSnapshotInputFormat to read from a snapshot.
199   * @param job the job to configure
200   * @param snapshotName the name of the snapshot to read from
201   * @param restoreDir a temporary directory to restore the snapshot into. Current user should
202   * have write permissions to this directory, and this should not be a subdirectory of rootdir.
203   * After the job is finished, restoreDir can be deleted.
204   * @throws IOException if an error occurs
205   */
206  public static void setInput(Job job, String snapshotName, Path restoreDir)
207      throws IOException {
208    TableSnapshotInputFormatImpl.setInput(job.getConfiguration(), snapshotName, restoreDir);
209  }
210
211  /**
212   * Configures the job to use TableSnapshotInputFormat to read from a snapshot.
213   * @param job the job to configure
214   * @param snapshotName the name of the snapshot to read from
215   * @param restoreDir a temporary directory to restore the snapshot into. Current user should
216   * have write permissions to this directory, and this should not be a subdirectory of rootdir.
217   * After the job is finished, restoreDir can be deleted.
218   * @param splitAlgo split algorithm to generate splits from region
219   * @param numSplitsPerRegion how many input splits to generate per one region
220   * @throws IOException if an error occurs
221   */
222   public static void setInput(Job job, String snapshotName, Path restoreDir,
223                               RegionSplitter.SplitAlgorithm splitAlgo, int numSplitsPerRegion) throws IOException {
224     TableSnapshotInputFormatImpl.setInput(job.getConfiguration(), snapshotName, restoreDir,
225             splitAlgo, numSplitsPerRegion);
226   }
227
228  /**
229   *  clean restore directory after snapshot scan job
230   * @param job the snapshot scan job
231   * @param snapshotName the name of the snapshot to read from
232   * @throws IOException if an error occurs
233   */
234  public static void cleanRestoreDir(Job job, String snapshotName) throws IOException {
235    TableSnapshotInputFormatImpl.cleanRestoreDir(job, snapshotName);
236  }
237}