View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.mapreduce;
20  
21  import java.io.IOException;
22  import java.util.HashMap;
23  import java.util.Map;
24  import java.util.Random;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.conf.Configured;
30  import org.apache.hadoop.fs.FileSystem;
31  import org.apache.hadoop.fs.Path;
32  import org.apache.hadoop.hbase.HBaseConfiguration;
33  import org.apache.hadoop.hbase.HConstants;
34  import org.apache.hadoop.hbase.TableName;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.classification.InterfaceStability;
37  import org.apache.hadoop.hbase.client.Connection;
38  import org.apache.hadoop.hbase.client.ConnectionFactory;
39  import org.apache.hadoop.hbase.client.Scan;
40  import org.apache.hadoop.hbase.client.Table;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.mapreduce.Job;
43  import org.apache.hadoop.util.GenericOptionsParser;
44  import org.apache.hadoop.util.Tool;
45  import org.apache.hadoop.util.ToolRunner;
46  
47  /**
48   * Tool used to copy a table to another one which can be on a different setup.
49   * It is also configurable with a start and time as well as a specification
50   * of the region server implementation if different from the local cluster.
51   */
52  @InterfaceAudience.Public
53  @InterfaceStability.Stable
54  public class CopyTable extends Configured implements Tool {
55    private static final Log LOG = LogFactory.getLog(CopyTable.class);
56  
57    final static String NAME = "copytable";
58    long startTime = 0;
59    long endTime = 0;
60    int versions = -1;
61    String tableName = null;
62    String startRow = null;
63    String stopRow = null;
64    String dstTableName = null;
65    String peerAddress = null;
66    String families = null;
67    boolean allCells = false;
68    static boolean shuffle = false;
69  
70    boolean bulkload = false;
71    Path bulkloadDir = null;
72  
73    private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
74  
75    public CopyTable(Configuration conf) {
76      super(conf);
77    }
78    /**
79     * Sets up the actual job.
80     *
81     * @param args  The command line parameters.
82     * @return The newly created job.
83     * @throws IOException When setting up the job fails.
84     */
85    public Job createSubmittableJob(String[] args)
86    throws IOException {
87      if (!doCommandLine(args)) {
88        return null;
89      }
90  
91      Job job = Job.getInstance(getConf(), getConf().get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
92      job.setJarByClass(CopyTable.class);
93      Scan scan = new Scan();
94      scan.setCacheBlocks(false);
95      if (startTime != 0) {
96        scan.setTimeRange(startTime,
97            endTime == 0 ? HConstants.LATEST_TIMESTAMP : endTime);
98      }
99      if (allCells) {
100       scan.setRaw(true);
101     }
102     if (shuffle) {
103       job.getConfiguration().set(TableInputFormat.SHUFFLE_MAPS, "true");
104     }
105     if (versions >= 0) {
106       scan.setMaxVersions(versions);
107     }
108 
109     if (startRow != null) {
110       scan.setStartRow(Bytes.toBytes(startRow));
111     }
112 
113     if (stopRow != null) {
114       scan.setStopRow(Bytes.toBytes(stopRow));
115     }
116 
117     if(families != null) {
118       String[] fams = families.split(",");
119       Map<String,String> cfRenameMap = new HashMap<String,String>();
120       for(String fam : fams) {
121         String sourceCf;
122         if(fam.contains(":")) {
123             // fam looks like "sourceCfName:destCfName"
124             String[] srcAndDest = fam.split(":", 2);
125             sourceCf = srcAndDest[0];
126             String destCf = srcAndDest[1];
127             cfRenameMap.put(sourceCf, destCf);
128         } else {
129             // fam is just "sourceCf"
130             sourceCf = fam;
131         }
132         scan.addFamily(Bytes.toBytes(sourceCf));
133       }
134       Import.configureCfRenaming(job.getConfiguration(), cfRenameMap);
135     }
136     job.setNumReduceTasks(0);
137 
138     if (bulkload) {
139       TableMapReduceUtil.initTableMapperJob(tableName, scan, Import.KeyValueImporter.class, null,
140         null, job);
141 
142       // We need to split the inputs by destination tables so that output of Map can be bulk-loaded.
143       TableInputFormat.configureSplitTable(job, TableName.valueOf(dstTableName));
144 
145       FileSystem fs = FileSystem.get(getConf());
146       Random rand = new Random();
147       Path root = new Path(fs.getWorkingDirectory(), "copytable");
148       fs.mkdirs(root);
149       while (true) {
150         bulkloadDir = new Path(root, "" + rand.nextLong());
151         if (!fs.exists(bulkloadDir)) {
152           break;
153         }
154       }
155 
156       System.out.println("HFiles will be stored at " + this.bulkloadDir);
157       HFileOutputFormat2.setOutputPath(job, bulkloadDir);
158       try (Connection conn = ConnectionFactory.createConnection(getConf());
159           Table htable = conn.getTable(TableName.valueOf(dstTableName))) {
160         HFileOutputFormat2.configureIncrementalLoadMap(job, htable);
161       }
162     } else {
163       TableMapReduceUtil.initTableMapperJob(tableName, scan,
164         Import.Importer.class, null, null, job);
165 
166       TableMapReduceUtil.initTableReducerJob(dstTableName, null, job, null, peerAddress, null,
167         null);
168     }
169 
170     return job;
171   }
172 
173   /*
174    * @param errorMsg Error message.  Can be null.
175    */
176   private static void printUsage(final String errorMsg) {
177     if (errorMsg != null && errorMsg.length() > 0) {
178       System.err.println("ERROR: " + errorMsg);
179     }
180     System.err.println("Usage: CopyTable [general options] [--starttime=X] [--endtime=Y] " +
181         "[--new.name=NEW] [--peer.adr=ADR] <tablename>");
182     System.err.println();
183     System.err.println("Options:");
184     System.err.println(" rs.class     hbase.regionserver.class of the peer cluster");
185     System.err.println("              specify if different from current cluster");
186     System.err.println(" rs.impl      hbase.regionserver.impl of the peer cluster");
187     System.err.println(" startrow     the start row");
188     System.err.println(" stoprow      the stop row");
189     System.err.println(" starttime    beginning of the time range (unixtime in millis)");
190     System.err.println("              without endtime means from starttime to forever");
191     System.err.println(" endtime      end of the time range.  Ignored if no starttime specified.");
192     System.err.println(" versions     number of cell versions to copy");
193     System.err.println(" new.name     new table's name");
194     System.err.println(" peer.adr     Address of the peer cluster given in the format");
195     System.err.println("              hbase.zookeeer.quorum:hbase.zookeeper.client.port:zookeeper.znode.parent");
196     System.err.println(" families     comma-separated list of families to copy");
197     System.err.println("              To copy from cf1 to cf2, give sourceCfName:destCfName. ");
198     System.err.println("              To keep the same name, just give \"cfName\"");
199     System.err.println(" all.cells    also copy delete markers and deleted cells");
200     System.err.println(" bulkload     Write input into HFiles and bulk load to the destination "
201         + "table");
202     System.err.println();
203     System.err.println("Args:");
204     System.err.println(" tablename    Name of the table to copy");
205     System.err.println();
206     System.err.println("Examples:");
207     System.err.println(" To copy 'TestTable' to a cluster that uses replication for a 1 hour window:");
208     System.err.println(" $ bin/hbase " +
209         "org.apache.hadoop.hbase.mapreduce.CopyTable --starttime=1265875194289 --endtime=1265878794289 " +
210         "--peer.adr=server1,server2,server3:2181:/hbase --families=myOldCf:myNewCf,cf2,cf3 TestTable ");
211     System.err.println("For performance consider the following general option:\n"
212         + "  It is recommended that you set the following to >=100. A higher value uses more memory but\n"
213         + "  decreases the round trip time to the server and may increase performance.\n"
214         + "    -Dhbase.client.scanner.caching=100\n"
215         + "  The following should always be set to false, to prevent writing data twice, which may produce \n"
216         + "  inaccurate results.\n"
217         + "    -Dmapreduce.map.speculative=false");
218   }
219 
220   private boolean doCommandLine(final String[] args) {
221     // Process command-line args. TODO: Better cmd-line processing
222     // (but hopefully something not as painful as cli options).
223     if (args.length < 1) {
224       printUsage(null);
225       return false;
226     }
227     try {
228       for (int i = 0; i < args.length; i++) {
229         String cmd = args[i];
230         if (cmd.equals("-h") || cmd.startsWith("--h")) {
231           printUsage(null);
232           return false;
233         }
234 
235         final String startRowArgKey = "--startrow=";
236         if (cmd.startsWith(startRowArgKey)) {
237           startRow = cmd.substring(startRowArgKey.length());
238           continue;
239         }
240 
241         final String stopRowArgKey = "--stoprow=";
242         if (cmd.startsWith(stopRowArgKey)) {
243           stopRow = cmd.substring(stopRowArgKey.length());
244           continue;
245         }
246 
247         final String startTimeArgKey = "--starttime=";
248         if (cmd.startsWith(startTimeArgKey)) {
249           startTime = Long.parseLong(cmd.substring(startTimeArgKey.length()));
250           continue;
251         }
252 
253         final String endTimeArgKey = "--endtime=";
254         if (cmd.startsWith(endTimeArgKey)) {
255           endTime = Long.parseLong(cmd.substring(endTimeArgKey.length()));
256           continue;
257         }
258 
259         final String versionsArgKey = "--versions=";
260         if (cmd.startsWith(versionsArgKey)) {
261           versions = Integer.parseInt(cmd.substring(versionsArgKey.length()));
262           continue;
263         }
264 
265         final String newNameArgKey = "--new.name=";
266         if (cmd.startsWith(newNameArgKey)) {
267           dstTableName = cmd.substring(newNameArgKey.length());
268           continue;
269         }
270 
271         final String peerAdrArgKey = "--peer.adr=";
272         if (cmd.startsWith(peerAdrArgKey)) {
273           peerAddress = cmd.substring(peerAdrArgKey.length());
274           continue;
275         }
276 
277         final String familiesArgKey = "--families=";
278         if (cmd.startsWith(familiesArgKey)) {
279           families = cmd.substring(familiesArgKey.length());
280           continue;
281         }
282 
283         if (cmd.startsWith("--all.cells")) {
284           allCells = true;
285           continue;
286         }
287 
288         if (cmd.startsWith("--bulkload")) {
289           bulkload = true;
290           continue;
291         }
292 
293         if (cmd.startsWith("--shuffle")) {
294           shuffle = true;
295           continue;
296         }
297 
298         if (i == args.length-1) {
299           tableName = cmd;
300         } else {
301           printUsage("Invalid argument '" + cmd + "'" );
302           return false;
303         }
304       }
305       if (dstTableName == null && peerAddress == null) {
306         printUsage("At least a new table name or a " +
307             "peer address must be specified");
308         return false;
309       }
310       if ((endTime != 0) && (startTime > endTime)) {
311         printUsage("Invalid time range filter: starttime=" + startTime + " >  endtime=" + endTime);
312         return false;
313       }
314 
315       if (bulkload && peerAddress != null) {
316         printUsage("Remote bulkload is not supported!");
317         return false;
318       }
319 
320       // set dstTableName if necessary
321       if (dstTableName == null) {
322         dstTableName = tableName;
323       }
324     } catch (Exception e) {
325       e.printStackTrace();
326       printUsage("Can't start because " + e.getMessage());
327       return false;
328     }
329     return true;
330   }
331 
332   /**
333    * Main entry point.
334    *
335    * @param args  The command line parameters.
336    * @throws Exception When running the job fails.
337    */
338   public static void main(String[] args) throws Exception {
339     int ret = ToolRunner.run(new CopyTable(HBaseConfiguration.create()), args);
340     System.exit(ret);
341   }
342 
343   @Override
344   public int run(String[] args) throws Exception {
345     String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs();
346     Job job = createSubmittableJob(otherArgs);
347     if (job == null) return 1;
348     if (!job.waitForCompletion(true)) {
349       LOG.info("Map-reduce job failed!");
350       if (bulkload) {
351         LOG.info("Files are not bulkloaded!");
352       }
353       return 1;
354     }
355     int code = 0;
356     if (bulkload) {
357       code = new LoadIncrementalHFiles(this.getConf()).run(new String[]{this.bulkloadDir.toString(),
358           this.dstTableName});
359       if (code == 0) {
360         // bulkloadDir is deleted only LoadIncrementalHFiles was successful so that one can rerun
361         // LoadIncrementalHFiles.
362         FileSystem fs = FileSystem.get(this.getConf());
363         if (!fs.delete(this.bulkloadDir, true)) {
364           LOG.error("Deleting folder " + bulkloadDir + " failed!");
365           code = 1;
366         }
367       }
368     }
369     return code;
370   }
371 }