View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with this
4    * work for additional information regarding copyright ownership. The ASF
5    * licenses this file to you under the Apache License, Version 2.0 (the
6    * "License"); you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14   * License for the specific language governing permissions and limitations
15   * under the License.
16   */
17  package org.apache.hadoop.hbase.util;
18  
19  import java.util.Set;
20  import java.util.TreeSet;
21  
22  import org.apache.commons.cli.BasicParser;
23  import org.apache.commons.cli.CommandLine;
24  import org.apache.commons.cli.CommandLineParser;
25  import org.apache.commons.cli.HelpFormatter;
26  import org.apache.commons.cli.Options;
27  import org.apache.commons.cli.ParseException;
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.hbase.HBaseConfiguration;
32  import org.apache.hadoop.util.Tool;
33  import org.apache.hadoop.util.ToolRunner;
34  
35  /**
36   * Common base class used for HBase command-line tools. Simplifies workflow and
37   * command-line argument parsing.
38   */
39  public abstract class AbstractHBaseTool implements Tool {
40  
41    private static final int EXIT_SUCCESS = 0;
42    private static final int EXIT_FAILURE = 1;
43  
44    private static final String HELP_OPTION = "help";
45  
46    private static final Log LOG = LogFactory.getLog(AbstractHBaseTool.class);
47  
48    private final Options options = new Options();
49  
50    protected Configuration conf = null;
51  
52    private static final Set<String> requiredOptions = new TreeSet<String>();
53  
54    /**
55     * Override this to add command-line options using {@link #addOptWithArg}
56     * and similar methods.
57     */
58    protected abstract void addOptions();
59  
60    /**
61     * This method is called to process the options after they have been parsed.
62     */
63    protected abstract void processOptions(CommandLine cmd);
64  
65    /** The "main function" of the tool */
66    protected abstract int doWork() throws Exception;
67  
68    @Override
69    public Configuration getConf() {
70      return conf;
71    }
72  
73    @Override
74    public void setConf(Configuration conf) {
75      this.conf = conf;
76    }
77  
78    @Override
79    public final int run(String[] args) throws Exception {
80      if (conf == null) {
81        LOG.error("Tool configuration is not initialized");
82        throw new NullPointerException("conf");
83      }
84  
85      CommandLine cmd;
86      try {
87        // parse the command line arguments
88        cmd = parseArgs(args);
89      } catch (ParseException e) {
90        LOG.error("Error when parsing command-line arguemnts", e);
91        printUsage();
92        return EXIT_FAILURE;
93      }
94  
95      if (cmd.hasOption(HELP_OPTION) || !sanityCheckOptions(cmd)) {
96        printUsage();
97        return EXIT_FAILURE;
98      }
99  
100     processOptions(cmd);
101 
102     int ret = EXIT_FAILURE;
103     try {
104       ret = doWork();
105     } catch (Exception e) {
106       LOG.error("Error running command-line tool", e);
107       return EXIT_FAILURE;
108     }
109     return ret;
110   }
111 
112   private boolean sanityCheckOptions(CommandLine cmd) {
113     boolean success = true;
114     for (String reqOpt : requiredOptions) {
115       if (!cmd.hasOption(reqOpt)) {
116         LOG.error("Required option -" + reqOpt + " is missing");
117         success = false;
118       }
119     }
120     return success;
121   }
122 
123   private CommandLine parseArgs(String[] args) throws ParseException {
124     options.addOption(HELP_OPTION, false, "Show usage");
125     addOptions();
126     CommandLineParser parser = new BasicParser();
127     return parser.parse(options, args);
128   }
129 
130   private void printUsage() {
131     HelpFormatter helpFormatter = new HelpFormatter();
132     helpFormatter.setWidth(80);
133     String usageHeader = "Options:";
134     String usageFooter = "";
135     String usageStr = "bin/hbase " + getClass().getName() + " <options>";
136 
137     helpFormatter.printHelp(usageStr, usageHeader, options,
138         usageFooter);
139   }
140 
141   protected void addRequiredOptWithArg(String opt, String description) {
142     requiredOptions.add(opt);
143     addOptWithArg(opt, description);
144   }
145 
146   protected void addOptNoArg(String opt, String description) {
147     options.addOption(opt, false, description);
148   }
149 
150   protected void addOptWithArg(String opt, String description) {
151     options.addOption(opt, true, description);
152   }
153 
154   /**
155    * Parse a number and enforce a range.
156    */
157   public static long parseLong(String s, long minValue, long maxValue) {
158     long l = Long.parseLong(s);
159     if (l < minValue || l > maxValue) {
160       throw new IllegalArgumentException("The value " + l
161           + " is out of range [" + minValue + ", " + maxValue + "]");
162     }
163     return l;
164   }
165 
166   public static int parseInt(String s, int minValue, int maxValue) {
167     return (int) parseLong(s, minValue, maxValue);
168   }
169 
170   /** Call this from the concrete tool class's main function. */
171   protected void doStaticMain(String args[]) {
172     int ret;
173     try {
174       ret = ToolRunner.run(HBaseConfiguration.create(), this, args);
175     } catch (Exception ex) {
176       LOG.error("Error running command-line tool", ex);
177       ret = EXIT_FAILURE;
178     }
179     System.exit(ret);
180   }
181 
182 }