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,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.hadoop.hbase.coprocessor;
020
021import java.io.Closeable;
022import java.io.IOException;
023import java.security.PrivilegedExceptionAction;
024import java.util.ArrayList;
025import java.util.Collections;
026import java.util.LinkedList;
027import java.util.List;
028import java.util.Map;
029import java.util.TreeMap;
030
031import org.apache.commons.lang3.ArrayUtils;
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.fs.FileSystem;
034import org.apache.hadoop.fs.Path;
035import org.apache.hadoop.hbase.Cell;
036import org.apache.hadoop.hbase.CoprocessorEnvironment;
037import org.apache.hadoop.hbase.HBaseConfiguration;
038import org.apache.hadoop.hbase.HBaseInterfaceAudience;
039import org.apache.hadoop.hbase.TableName;
040import org.apache.hadoop.hbase.client.Connection;
041import org.apache.hadoop.hbase.client.ConnectionFactory;
042import org.apache.hadoop.hbase.client.RegionInfo;
043import org.apache.hadoop.hbase.client.Result;
044import org.apache.hadoop.hbase.client.Scan;
045import org.apache.hadoop.hbase.client.Table;
046import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
047import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils;
048import org.apache.hadoop.hbase.ipc.RpcServer;
049import org.apache.hadoop.hbase.ipc.ServerRpcController;
050import org.apache.hadoop.hbase.mapreduce.ExportUtils;
051import org.apache.hadoop.hbase.mapreduce.Import;
052import org.apache.hadoop.hbase.mapreduce.ResultSerialization;
053import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
054import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.DelegationToken;
055import org.apache.hadoop.hbase.protobuf.generated.ExportProtos;
056import org.apache.hadoop.hbase.regionserver.HRegion;
057import org.apache.hadoop.hbase.regionserver.InternalScanner;
058import org.apache.hadoop.hbase.regionserver.Region;
059import org.apache.hadoop.hbase.regionserver.RegionScanner;
060import org.apache.hadoop.hbase.security.User;
061import org.apache.hadoop.hbase.security.UserProvider;
062import org.apache.hadoop.hbase.security.token.FsDelegationToken;
063import org.apache.hadoop.hbase.util.ByteStringer;
064import org.apache.hadoop.hbase.util.Bytes;
065import org.apache.hadoop.hbase.util.Triple;
066import org.apache.hadoop.io.SequenceFile;
067import org.apache.hadoop.io.Text;
068import org.apache.hadoop.io.compress.CompressionCodec;
069import org.apache.hadoop.io.compress.DefaultCodec;
070import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
071import org.apache.hadoop.security.token.Token;
072import org.apache.hadoop.util.GenericOptionsParser;
073import org.apache.hadoop.util.ReflectionUtils;
074import org.apache.yetus.audience.InterfaceAudience;
075import org.apache.yetus.audience.InterfaceStability;
076import org.slf4j.Logger;
077import org.slf4j.LoggerFactory;
078import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
079
080import com.google.protobuf.RpcCallback;
081import com.google.protobuf.RpcController;
082import com.google.protobuf.Service;
083
084/**
085 * Export an HBase table. Writes content to sequence files up in HDFS. Use
086 * {@link Import} to read it back in again. It is implemented by the endpoint
087 * technique.
088 *
089 * @see org.apache.hadoop.hbase.mapreduce.Export
090 */
091@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.COPROC)
092@InterfaceStability.Evolving
093public class Export extends ExportProtos.ExportService implements RegionCoprocessor {
094
095  private static final Logger LOG = LoggerFactory.getLogger(Export.class);
096  private static final Class<? extends CompressionCodec> DEFAULT_CODEC = DefaultCodec.class;
097  private static final SequenceFile.CompressionType DEFAULT_TYPE = SequenceFile.CompressionType.RECORD;
098  private RegionCoprocessorEnvironment env = null;
099  private UserProvider userProvider;
100
101  public static void main(String[] args) throws Throwable {
102    Map<byte[], Response> response = run(HBaseConfiguration.create(), args);
103    System.exit(response == null ? -1 : 0);
104  }
105
106  @VisibleForTesting
107  static Map<byte[], Response> run(final Configuration conf, final String[] args) throws Throwable {
108    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
109    if (!ExportUtils.isValidArguements(args)) {
110      ExportUtils.usage("Wrong number of arguments: " + ArrayUtils.getLength(otherArgs));
111      return null;
112    }
113    Triple<TableName, Scan, Path> arguments = ExportUtils.getArgumentsFromCommandLine(conf, otherArgs);
114    return run(conf, arguments.getFirst(), arguments.getSecond(), arguments.getThird());
115  }
116
117  public static Map<byte[], Response> run(final Configuration conf, TableName tableName, Scan scan, Path dir) throws Throwable {
118    FileSystem fs = dir.getFileSystem(conf);
119    UserProvider userProvider = UserProvider.instantiate(conf);
120    checkDir(fs, dir);
121    FsDelegationToken fsDelegationToken = new FsDelegationToken(userProvider, "renewer");
122    fsDelegationToken.acquireDelegationToken(fs);
123    try {
124      final ExportProtos.ExportRequest request = getConfiguredRequest(conf, dir,
125        scan, fsDelegationToken.getUserToken());
126      try (Connection con = ConnectionFactory.createConnection(conf);
127              Table table = con.getTable(tableName)) {
128        Map<byte[], Response> result = new TreeMap<>(Bytes.BYTES_COMPARATOR);
129        table.coprocessorService(ExportProtos.ExportService.class,
130          scan.getStartRow(),
131          scan.getStopRow(),
132          (ExportProtos.ExportService service) -> {
133            ServerRpcController controller = new ServerRpcController();
134            Map<byte[], ExportProtos.ExportResponse> rval = new TreeMap<>(Bytes.BYTES_COMPARATOR);
135            CoprocessorRpcUtils.BlockingRpcCallback<ExportProtos.ExportResponse>
136              rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>();
137            service.export(controller, request, rpcCallback);
138            if (controller.failedOnException()) {
139              throw controller.getFailedOn();
140            }
141            return rpcCallback.get();
142          }).forEach((k, v) -> result.put(k, new Response(v)));
143        return result;
144      } catch (Throwable e) {
145        fs.delete(dir, true);
146        throw e;
147      }
148    } finally {
149      fsDelegationToken.releaseDelegationToken();
150    }
151  }
152
153  private static boolean getCompression(final ExportProtos.ExportRequest request) {
154    if (request.hasCompressed()) {
155      return request.getCompressed();
156    } else {
157      return false;
158    }
159  }
160
161  private static SequenceFile.CompressionType getCompressionType(final ExportProtos.ExportRequest request) {
162    if (request.hasCompressType()) {
163      return SequenceFile.CompressionType.valueOf(request.getCompressType());
164    } else {
165      return DEFAULT_TYPE;
166    }
167  }
168
169  private static CompressionCodec getCompressionCodec(final Configuration conf, final ExportProtos.ExportRequest request) {
170    try {
171      Class<? extends CompressionCodec> codecClass;
172      if (request.hasCompressCodec()) {
173        codecClass = conf.getClassByName(request.getCompressCodec()).asSubclass(CompressionCodec.class);
174      } else {
175        codecClass = DEFAULT_CODEC;
176      }
177      return ReflectionUtils.newInstance(codecClass, conf);
178    } catch (ClassNotFoundException e) {
179      throw new IllegalArgumentException("Compression codec "
180              + request.getCompressCodec() + " was not found.", e);
181    }
182  }
183
184  private static SequenceFile.Writer.Option getOutputPath(final Configuration conf,
185          final RegionInfo info, final ExportProtos.ExportRequest request) throws IOException {
186    Path file = new Path(request.getOutputPath(), "export-" + info.getEncodedName());
187    FileSystem fs = file.getFileSystem(conf);
188    if (fs.exists(file)) {
189      throw new IOException(file + " exists");
190    }
191    return SequenceFile.Writer.file(file);
192  }
193
194  private static List<SequenceFile.Writer.Option> getWriterOptions(final Configuration conf,
195          final RegionInfo info, final ExportProtos.ExportRequest request) throws IOException {
196    List<SequenceFile.Writer.Option> rval = new LinkedList<>();
197    rval.add(SequenceFile.Writer.keyClass(ImmutableBytesWritable.class));
198    rval.add(SequenceFile.Writer.valueClass(Result.class));
199    rval.add(getOutputPath(conf, info, request));
200    if (getCompression(request)) {
201      rval.add(SequenceFile.Writer.compression(getCompressionType(request), getCompressionCodec(conf, request)));
202    } else {
203      rval.add(SequenceFile.Writer.compression(SequenceFile.CompressionType.NONE));
204    }
205    return rval;
206  }
207
208  private static ExportProtos.ExportResponse processData(final Region region, final Configuration conf,
209    final UserProvider userProvider, final Scan scan, final Token userToken,
210    final List<SequenceFile.Writer.Option> opts) throws IOException {
211    ScanCoprocessor cp = new ScanCoprocessor(region);
212    RegionScanner scanner = null;
213    try (RegionOp regionOp = new RegionOp(region);
214            SecureWriter out = new SecureWriter(conf, userProvider, userToken, opts)) {
215      scanner = cp.checkScannerOpen(scan);
216      ImmutableBytesWritable key = new ImmutableBytesWritable();
217      long rowCount = 0;
218      long cellCount = 0;
219      List<Result> results = new ArrayList<>();
220      List<Cell> cells = new ArrayList<>();
221      boolean hasMore;
222      do {
223        boolean bypass = cp.preScannerNext(scanner, results, scan.getBatch());
224        if (bypass) {
225          hasMore = false;
226        } else {
227          hasMore = scanner.nextRaw(cells);
228          if (cells.isEmpty()) {
229            continue;
230          }
231          Cell firstCell = cells.get(0);
232          for (Cell cell : cells) {
233            if (Bytes.compareTo(firstCell.getRowArray(), firstCell.getRowOffset(), firstCell.getRowLength(),
234                    cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()) != 0) {
235              throw new IOException("Why the RegionScanner#nextRaw returns the data of different rows??"
236                      + " first row=" + Bytes.toHex(firstCell.getRowArray(), firstCell.getRowOffset(), firstCell.getRowLength())
237                      + ", current row=" + Bytes.toHex(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
238            }
239          }
240          results.add(Result.create(cells));
241          cells.clear();
242          cp.postScannerNext(scanner, results, scan.getBatch(), hasMore);
243        }
244        for (Result r : results) {
245          key.set(r.getRow());
246          out.append(key, r);
247          ++rowCount;
248          cellCount += r.size();
249        }
250        results.clear();
251      } while (hasMore);
252      return ExportProtos.ExportResponse.newBuilder()
253              .setRowCount(rowCount)
254              .setCellCount(cellCount)
255              .build();
256    } finally {
257      cp.checkScannerClose(scanner);
258    }
259  }
260
261  private static void checkDir(final FileSystem fs, final Path dir) throws IOException {
262    if (fs.exists(dir)) {
263      throw new RuntimeException("The " + dir + " exists");
264    }
265    if (!fs.mkdirs(dir)) {
266      throw new IOException("Failed to create the " + dir);
267    }
268  }
269
270  private static ExportProtos.ExportRequest getConfiguredRequest(Configuration conf,
271          Path dir, final Scan scan, final Token<?> userToken) throws IOException {
272    boolean compressed = conf.getBoolean(FileOutputFormat.COMPRESS, false);
273    String compressionType = conf.get(FileOutputFormat.COMPRESS_TYPE,
274            DEFAULT_TYPE.toString());
275    String compressionCodec = conf.get(FileOutputFormat.COMPRESS_CODEC,
276            DEFAULT_CODEC.getName());
277    DelegationToken protoToken = null;
278    if (userToken != null) {
279      protoToken = DelegationToken.newBuilder()
280              .setIdentifier(ByteStringer.wrap(userToken.getIdentifier()))
281              .setPassword(ByteStringer.wrap(userToken.getPassword()))
282              .setKind(userToken.getKind().toString())
283              .setService(userToken.getService().toString()).build();
284    }
285    LOG.info("compressed=" + compressed
286            + ", compression type=" + compressionType
287            + ", compression codec=" + compressionCodec
288            + ", userToken=" + userToken);
289    ExportProtos.ExportRequest.Builder builder = ExportProtos.ExportRequest.newBuilder()
290            .setScan(ProtobufUtil.toScan(scan))
291            .setOutputPath(dir.toString())
292            .setCompressed(compressed)
293            .setCompressCodec(compressionCodec)
294            .setCompressType(compressionType);
295    if (protoToken != null) {
296      builder.setFsToken(protoToken);
297    }
298    return builder.build();
299  }
300
301
302  @Override
303  public void start(CoprocessorEnvironment environment) throws IOException {
304    if (environment instanceof RegionCoprocessorEnvironment) {
305      env = (RegionCoprocessorEnvironment) environment;
306      userProvider = UserProvider.instantiate(env.getConfiguration());
307    } else {
308      throw new CoprocessorException("Must be loaded on a table region!");
309    }
310  }
311
312  @Override
313  public void stop(CoprocessorEnvironment env) throws IOException {
314  }
315
316  @Override
317  public Iterable<Service> getServices() {
318    return Collections.singleton(this);
319  }
320
321  @Override
322  public void export(RpcController controller, ExportProtos.ExportRequest request,
323          RpcCallback<ExportProtos.ExportResponse> done) {
324    Region region = env.getRegion();
325    Configuration conf = HBaseConfiguration.create(env.getConfiguration());
326    conf.setStrings("io.serializations", conf.get("io.serializations"), ResultSerialization.class.getName());
327    try {
328      Scan scan = validateKey(region.getRegionInfo(), request);
329      Token userToken = null;
330      if (userProvider.isHadoopSecurityEnabled() && !request.hasFsToken()) {
331        LOG.warn("Hadoop security is enable, but no found of user token");
332      } else if (userProvider.isHadoopSecurityEnabled()) {
333        userToken = new Token(request.getFsToken().getIdentifier().toByteArray(),
334                request.getFsToken().getPassword().toByteArray(),
335                new Text(request.getFsToken().getKind()),
336                new Text(request.getFsToken().getService()));
337      }
338      ExportProtos.ExportResponse response = processData(region, conf, userProvider,
339        scan, userToken, getWriterOptions(conf, region.getRegionInfo(), request));
340      done.run(response);
341    } catch (IOException e) {
342      CoprocessorRpcUtils.setControllerException(controller, e);
343      LOG.error(e.toString(), e);
344    }
345  }
346
347  private Scan validateKey(final RegionInfo region, final ExportProtos.ExportRequest request) throws IOException {
348    Scan scan = ProtobufUtil.toScan(request.getScan());
349    byte[] regionStartKey = region.getStartKey();
350    byte[] originStartKey = scan.getStartRow();
351    if (originStartKey == null
352            || Bytes.compareTo(originStartKey, regionStartKey) < 0) {
353      scan.setStartRow(regionStartKey);
354    }
355    byte[] regionEndKey = region.getEndKey();
356    byte[] originEndKey = scan.getStopRow();
357    if (originEndKey == null
358            || Bytes.compareTo(originEndKey, regionEndKey) > 0) {
359      scan.setStartRow(regionEndKey);
360    }
361    return scan;
362  }
363
364  private static class RegionOp implements Closeable {
365
366    private final Region region;
367
368    RegionOp(final Region region) throws IOException {
369      this.region = region;
370      region.startRegionOperation();
371    }
372
373    @Override
374    public void close() throws IOException {
375      region.closeRegionOperation();
376    }
377  }
378
379  private static class ScanCoprocessor {
380
381    private final HRegion region;
382
383    ScanCoprocessor(final Region region) {
384      this.region = (HRegion) region;
385    }
386
387    RegionScanner checkScannerOpen(final Scan scan) throws IOException {
388      RegionScanner scanner;
389      if (region.getCoprocessorHost() == null) {
390        scanner = region.getScanner(scan);
391      } else {
392        region.getCoprocessorHost().preScannerOpen(scan);
393        scanner = region.getScanner(scan);
394        scanner = region.getCoprocessorHost().postScannerOpen(scan, scanner);
395      }
396      if (scanner == null) {
397        throw new IOException("Failed to open region scanner");
398      }
399      return scanner;
400    }
401
402    void checkScannerClose(final InternalScanner s) throws IOException {
403      if (s == null) {
404        return;
405      }
406      if (region.getCoprocessorHost() == null) {
407        s.close();
408        return;
409      }
410      region.getCoprocessorHost().preScannerClose(s);
411      try {
412        s.close();
413      } finally {
414        region.getCoprocessorHost().postScannerClose(s);
415      }
416    }
417
418    boolean preScannerNext(final InternalScanner s,
419            final List<Result> results, final int limit) throws IOException {
420      if (region.getCoprocessorHost() == null) {
421        return false;
422      } else {
423        Boolean bypass = region.getCoprocessorHost().preScannerNext(s, results, limit);
424        return bypass == null ? false : bypass;
425      }
426    }
427
428    boolean postScannerNext(final InternalScanner s,
429            final List<Result> results, final int limit, boolean hasMore)
430            throws IOException {
431      if (region.getCoprocessorHost() == null) {
432        return false;
433      } else {
434        return region.getCoprocessorHost().postScannerNext(s, results, limit, hasMore);
435      }
436    }
437  }
438
439  private static class SecureWriter implements Closeable {
440    private final PrivilegedWriter privilegedWriter;
441
442    SecureWriter(final Configuration conf, final UserProvider userProvider, final Token userToken,
443            final List<SequenceFile.Writer.Option> opts) throws IOException {
444      privilegedWriter = new PrivilegedWriter(getActiveUser(userProvider, userToken),
445        SequenceFile.createWriter(conf, opts.toArray(new SequenceFile.Writer.Option[opts.size()])));
446    }
447
448    void append(final Object key, final Object value) throws IOException {
449      privilegedWriter.append(key, value);
450    }
451
452    private static User getActiveUser(final UserProvider userProvider, final Token userToken) throws IOException {
453      User user = RpcServer.getRequestUser().orElse(userProvider.getCurrent());
454      if (user == null && userToken != null) {
455        LOG.warn("No found of user credentials, but a token was got from user request");
456      } else if (user != null && userToken != null) {
457        user.addToken(userToken);
458      }
459      return user;
460    }
461
462    @Override
463    public void close() throws IOException {
464      privilegedWriter.close();
465    }
466  }
467
468  private static class PrivilegedWriter implements PrivilegedExceptionAction<Boolean>, Closeable {
469    private final User user;
470    private final SequenceFile.Writer out;
471    private Object key;
472    private Object value;
473
474    PrivilegedWriter(final User user, final SequenceFile.Writer out) {
475      this.user = user;
476      this.out = out;
477    }
478
479    void append(final Object key, final Object value) throws IOException {
480      if (user == null) {
481        out.append(key, value);
482      } else {
483        this.key = key;
484        this.value = value;
485        try {
486          user.runAs(this);
487        } catch (InterruptedException ex) {
488          throw new IOException(ex);
489        }
490      }
491    }
492
493    @Override
494    public Boolean run() throws Exception {
495      out.append(key, value);
496      return true;
497    }
498
499    @Override
500    public void close() throws IOException {
501      out.close();
502    }
503  }
504
505  public static class Response {
506
507    private final long rowCount;
508    private final long cellCount;
509
510    private Response(ExportProtos.ExportResponse r) {
511      this.rowCount = r.getRowCount();
512      this.cellCount = r.getCellCount();
513    }
514
515    public long getRowCount() {
516      return rowCount;
517    }
518
519    public long getCellCount() {
520      return cellCount;
521    }
522
523    @Override
524    public String toString() {
525      StringBuilder builder = new StringBuilder(35);
526      return builder.append("rowCount=")
527             .append(rowCount)
528             .append(", cellCount=")
529             .append(cellCount)
530             .toString();
531    }
532  }
533}