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.mapreduce;
020
021import java.io.IOException;
022import java.util.Arrays;
023import java.util.List;
024
025import org.apache.hadoop.conf.Configuration;
026import org.apache.hadoop.fs.Path;
027import org.apache.hadoop.hbase.CompareOperator;
028import org.apache.hadoop.hbase.HConstants;
029import org.apache.hadoop.hbase.TableName;
030import org.apache.yetus.audience.InterfaceAudience;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033import org.apache.hadoop.hbase.client.Scan;
034import org.apache.hadoop.hbase.filter.CompareFilter;
035import org.apache.hadoop.hbase.filter.Filter;
036import org.apache.hadoop.hbase.filter.IncompatibleFilterException;
037import org.apache.hadoop.hbase.filter.PrefixFilter;
038import org.apache.hadoop.hbase.filter.RegexStringComparator;
039import org.apache.hadoop.hbase.filter.RowFilter;
040import org.apache.hadoop.hbase.security.visibility.Authorizations;
041import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
042import org.apache.hadoop.hbase.util.Bytes;
043import org.apache.hadoop.hbase.util.Triple;
044import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
045
046/**
047 * Some helper methods are used by {@link org.apache.hadoop.hbase.mapreduce.Export}
048 * and org.apache.hadoop.hbase.coprocessor.Export (in hbase-endpooint).
049 */
050@InterfaceAudience.Private
051public final class ExportUtils {
052  private static final Logger LOG = LoggerFactory.getLogger(ExportUtils.class);
053  public static final String RAW_SCAN = "hbase.mapreduce.include.deleted.rows";
054  public static final String EXPORT_BATCHING = "hbase.export.scanner.batch";
055  public static final String EXPORT_CACHING = "hbase.export.scanner.caching";
056  public static final String EXPORT_VISIBILITY_LABELS = "hbase.export.visibility.labels";
057  /**
058   * Common usage for other export tools.
059   * @param errorMsg Error message.  Can be null.
060   */
061  public static void usage(final String errorMsg) {
062    if (errorMsg != null && errorMsg.length() > 0) {
063      System.err.println("ERROR: " + errorMsg);
064    }
065    System.err.println("Usage: Export [-D <property=value>]* <tablename> <outputdir> [<versions> " +
066      "[<starttime> [<endtime>]] [^[regex pattern] or [Prefix] to filter]]\n");
067    System.err.println("  Note: -D properties will be applied to the conf used. ");
068    System.err.println("  For example: ");
069    System.err.println("   -D " + FileOutputFormat.COMPRESS + "=true");
070    System.err.println("   -D " + FileOutputFormat.COMPRESS_CODEC + "=org.apache.hadoop.io.compress.GzipCodec");
071    System.err.println("   -D " + FileOutputFormat.COMPRESS_TYPE + "=BLOCK");
072    System.err.println("  Additionally, the following SCAN properties can be specified");
073    System.err.println("  to control/limit what is exported..");
074    System.err.println("   -D " + TableInputFormat.SCAN_COLUMN_FAMILY + "=<family1>,<family2>, ...");
075    System.err.println("   -D " + RAW_SCAN + "=true");
076    System.err.println("   -D " + TableInputFormat.SCAN_ROW_START + "=<ROWSTART>");
077    System.err.println("   -D " + TableInputFormat.SCAN_ROW_STOP + "=<ROWSTOP>");
078    System.err.println("   -D " + HConstants.HBASE_CLIENT_SCANNER_CACHING + "=100");
079    System.err.println("   -D " + EXPORT_VISIBILITY_LABELS + "=<labels>");
080    System.err.println("For tables with very wide rows consider setting the batch size as below:\n"
081            + "   -D " + EXPORT_BATCHING + "=10\n"
082            + "   -D " + EXPORT_CACHING + "=100");
083  }
084
085  private static Filter getExportFilter(String[] args) {
086    Filter exportFilter;
087    String filterCriteria = (args.length > 5) ? args[5]: null;
088    if (filterCriteria == null) return null;
089    if (filterCriteria.startsWith("^")) {
090      String regexPattern = filterCriteria.substring(1, filterCriteria.length());
091      exportFilter = new RowFilter(CompareOperator.EQUAL, new RegexStringComparator(regexPattern));
092    } else {
093      exportFilter = new PrefixFilter(Bytes.toBytesBinary(filterCriteria));
094    }
095    return exportFilter;
096  }
097
098  public static boolean isValidArguements(String[] args) {
099    return args != null && args.length >= 2;
100  }
101
102  public static Triple<TableName, Scan, Path> getArgumentsFromCommandLine(
103          Configuration conf, String[] args) throws IOException {
104    if (!isValidArguements(args)) {
105      return null;
106    }
107    return new Triple<>(TableName.valueOf(args[0]), getScanFromCommandLine(conf, args), new Path(args[1]));
108  }
109
110  @VisibleForTesting
111  static Scan getScanFromCommandLine(Configuration conf, String[] args) throws IOException {
112    Scan s = new Scan();
113    // Optional arguments.
114    // Set Scan Versions
115    int versions = args.length > 2? Integer.parseInt(args[2]): 1;
116    s.setMaxVersions(versions);
117    // Set Scan Range
118    long startTime = args.length > 3? Long.parseLong(args[3]): 0L;
119    long endTime = args.length > 4? Long.parseLong(args[4]): Long.MAX_VALUE;
120    s.setTimeRange(startTime, endTime);
121    // Set cache blocks
122    s.setCacheBlocks(false);
123    // set Start and Stop row
124    if (conf.get(TableInputFormat.SCAN_ROW_START) != null) {
125      s.setStartRow(Bytes.toBytesBinary(conf.get(TableInputFormat.SCAN_ROW_START)));
126    }
127    if (conf.get(TableInputFormat.SCAN_ROW_STOP) != null) {
128      s.setStopRow(Bytes.toBytesBinary(conf.get(TableInputFormat.SCAN_ROW_STOP)));
129    }
130    // Set Scan Column Family
131    boolean raw = Boolean.parseBoolean(conf.get(RAW_SCAN));
132    if (raw) {
133      s.setRaw(raw);
134    }
135    for (String columnFamily : conf.getTrimmedStrings(TableInputFormat.SCAN_COLUMN_FAMILY)) {
136      s.addFamily(Bytes.toBytes(columnFamily));
137    }
138    // Set RowFilter or Prefix Filter if applicable.
139    Filter exportFilter = getExportFilter(args);
140    if (exportFilter!= null) {
141        LOG.info("Setting Scan Filter for Export.");
142      s.setFilter(exportFilter);
143    }
144    List<String> labels = null;
145    if (conf.get(EXPORT_VISIBILITY_LABELS) != null) {
146      labels = Arrays.asList(conf.getStrings(EXPORT_VISIBILITY_LABELS));
147      if (!labels.isEmpty()) {
148        s.setAuthorizations(new Authorizations(labels));
149      }
150    }
151
152    int batching = conf.getInt(EXPORT_BATCHING, -1);
153    if (batching != -1) {
154      try {
155        s.setBatch(batching);
156      } catch (IncompatibleFilterException e) {
157        LOG.error("Batching could not be set", e);
158      }
159    }
160
161    int caching = conf.getInt(EXPORT_CACHING, 100);
162    if (caching != -1) {
163      try {
164        s.setCaching(caching);
165      } catch (IncompatibleFilterException e) {
166        LOG.error("Caching could not be set", e);
167      }
168    }
169    LOG.info("versions=" + versions + ", starttime=" + startTime
170      + ", endtime=" + endTime + ", keepDeletedCells=" + raw
171      + ", visibility labels=" + labels);
172    return s;
173  }
174
175  private ExportUtils() {
176  }
177}