1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.mapreduce;
20
21 import com.google.common.collect.Lists;
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.hadoop.conf.Configuration;
25 import org.apache.hadoop.fs.FileSystem;
26 import org.apache.hadoop.fs.Path;
27 import org.apache.hadoop.hbase.CellUtil;
28 import org.apache.hadoop.hbase.HDFSBlocksDistribution;
29 import org.apache.hadoop.hbase.HDFSBlocksDistribution.HostAndWeight;
30 import org.apache.hadoop.hbase.HRegionInfo;
31 import org.apache.hadoop.hbase.HTableDescriptor;
32 import org.apache.hadoop.hbase.classification.InterfaceAudience;
33 import org.apache.hadoop.hbase.classification.InterfaceStability;
34 import org.apache.hadoop.hbase.client.ClientSideRegionScanner;
35 import org.apache.hadoop.hbase.client.IsolationLevel;
36 import org.apache.hadoop.hbase.client.Result;
37 import org.apache.hadoop.hbase.client.Scan;
38 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
39 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
40 import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos.TableSnapshotRegionSplit;
41 import org.apache.hadoop.hbase.protobuf.generated.SnapshotProtos.SnapshotRegionManifest;
42 import org.apache.hadoop.hbase.regionserver.HRegion;
43 import org.apache.hadoop.hbase.snapshot.RestoreSnapshotHelper;
44 import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
45 import org.apache.hadoop.hbase.snapshot.SnapshotManifest;
46 import org.apache.hadoop.hbase.util.Bytes;
47 import org.apache.hadoop.hbase.util.FSUtils;
48 import org.apache.hadoop.hbase.util.RegionSplitter;
49 import org.apache.hadoop.io.Writable;
50
51 import java.io.ByteArrayOutputStream;
52 import java.io.DataInput;
53 import java.io.DataOutput;
54 import java.io.IOException;
55 import java.util.ArrayList;
56 import java.util.List;
57 import java.util.UUID;
58
59
60
61
62 @InterfaceAudience.Private
63 @InterfaceStability.Evolving
64 public class TableSnapshotInputFormatImpl {
65
66
67
68 public static final Log LOG = LogFactory.getLog(TableSnapshotInputFormatImpl.class);
69
70 private static final String SNAPSHOT_NAME_KEY = "hbase.TableSnapshotInputFormat.snapshot.name";
71
72 protected static final String RESTORE_DIR_KEY = "hbase.TableSnapshotInputFormat.restore.dir";
73
74
75 private static final String LOCALITY_CUTOFF_MULTIPLIER =
76 "hbase.tablesnapshotinputformat.locality.cutoff.multiplier";
77 private static final float DEFAULT_LOCALITY_CUTOFF_MULTIPLIER = 0.8f;
78
79
80
81
82
83 public static final String SPLIT_ALGO = "hbase.mapreduce.split.algorithm";
84
85
86
87
88 public static final String NUM_SPLITS_PER_REGION = "hbase.mapreduce.splits.per.region";
89
90
91
92
93 public static class InputSplit implements Writable {
94
95 private HTableDescriptor htd;
96 private HRegionInfo regionInfo;
97 private String[] locations;
98 private String scan;
99 private String restoreDir;
100
101
102 public InputSplit() {}
103
104 public InputSplit(HTableDescriptor htd, HRegionInfo regionInfo, List<String> locations,
105 Scan scan, Path restoreDir) {
106 this.htd = htd;
107 this.regionInfo = regionInfo;
108 if (locations == null || locations.isEmpty()) {
109 this.locations = new String[0];
110 } else {
111 this.locations = locations.toArray(new String[locations.size()]);
112 }
113 try {
114 this.scan = scan != null ? TableMapReduceUtil.convertScanToString(scan) : "";
115 } catch (IOException e) {
116 LOG.warn("Failed to convert Scan to String", e);
117 }
118
119 this.restoreDir = restoreDir.toString();
120 }
121
122 public HTableDescriptor getHtd() {
123 return htd;
124 }
125
126 public String getScan() {
127 return scan;
128 }
129
130 public String getRestoreDir() {
131 return restoreDir;
132 }
133
134 public long getLength() {
135
136 return 0;
137 }
138
139 public String[] getLocations() {
140 return locations;
141 }
142
143 public HTableDescriptor getTableDescriptor() {
144 return htd;
145 }
146
147 public HRegionInfo getRegionInfo() {
148 return regionInfo;
149 }
150
151
152
153 @Override
154 public void write(DataOutput out) throws IOException {
155 TableSnapshotRegionSplit.Builder builder = TableSnapshotRegionSplit.newBuilder()
156 .setTable(htd.convert())
157 .setRegion(HRegionInfo.convert(regionInfo));
158
159 for (String location : locations) {
160 builder.addLocations(location);
161 }
162
163 TableSnapshotRegionSplit split = builder.build();
164
165 ByteArrayOutputStream baos = new ByteArrayOutputStream();
166 split.writeTo(baos);
167 baos.close();
168 byte[] buf = baos.toByteArray();
169 out.writeInt(buf.length);
170 out.write(buf);
171
172 Bytes.writeByteArray(out, Bytes.toBytes(scan));
173 Bytes.writeByteArray(out, Bytes.toBytes(restoreDir));
174
175 }
176
177 @Override
178 public void readFields(DataInput in) throws IOException {
179 int len = in.readInt();
180 byte[] buf = new byte[len];
181 in.readFully(buf);
182 TableSnapshotRegionSplit split = TableSnapshotRegionSplit.PARSER.parseFrom(buf);
183 this.htd = HTableDescriptor.convert(split.getTable());
184 this.regionInfo = HRegionInfo.convert(split.getRegion());
185 List<String> locationsList = split.getLocationsList();
186 this.locations = locationsList.toArray(new String[locationsList.size()]);
187
188 this.scan = Bytes.toString(Bytes.readByteArray(in));
189 this.restoreDir = Bytes.toString(Bytes.readByteArray(in));
190 }
191 }
192
193
194
195
196 public static class RecordReader {
197 private InputSplit split;
198 private Scan scan;
199 private Result result = null;
200 private ImmutableBytesWritable row = null;
201 private ClientSideRegionScanner scanner;
202
203 public ClientSideRegionScanner getScanner() {
204 return scanner;
205 }
206
207 public void initialize(InputSplit split, Configuration conf) throws IOException {
208 this.scan = TableMapReduceUtil.convertStringToScan(split.getScan());
209 this.split = split;
210 HTableDescriptor htd = split.htd;
211 HRegionInfo hri = this.split.getRegionInfo();
212 FileSystem fs = FSUtils.getCurrentFileSystem(conf);
213
214
215
216
217 scan.setIsolationLevel(IsolationLevel.READ_UNCOMMITTED);
218
219 scan.setCacheBlocks(false);
220
221 scanner =
222 new ClientSideRegionScanner(conf, fs, new Path(split.restoreDir), htd, hri, scan, null);
223 }
224
225 public boolean nextKeyValue() throws IOException {
226 result = scanner.next();
227 if (result == null) {
228
229 return false;
230 }
231
232 if (this.row == null) {
233 this.row = new ImmutableBytesWritable();
234 }
235 this.row.set(result.getRow());
236 return true;
237 }
238
239 public ImmutableBytesWritable getCurrentKey() {
240 return row;
241 }
242
243 public Result getCurrentValue() {
244 return result;
245 }
246
247 public long getPos() {
248 return 0;
249 }
250
251 public float getProgress() {
252 return 0;
253 }
254
255 public void close() {
256 if (this.scanner != null) {
257 this.scanner.close();
258 }
259 }
260 }
261
262 public static List<InputSplit> getSplits(Configuration conf) throws IOException {
263 String snapshotName = getSnapshotName(conf);
264
265 Path rootDir = FSUtils.getRootDir(conf);
266 FileSystem fs = rootDir.getFileSystem(conf);
267
268 SnapshotManifest manifest = getSnapshotManifest(conf, snapshotName, rootDir, fs);
269
270 List<HRegionInfo> regionInfos = getRegionInfosFromManifest(manifest);
271
272
273 Scan scan = extractScanFromConf(conf);
274
275 Path restoreDir = new Path(conf.get(RESTORE_DIR_KEY));
276
277 RegionSplitter.SplitAlgorithm splitAlgo = getSplitAlgo(conf);
278
279 int numSplits = conf.getInt(NUM_SPLITS_PER_REGION, 1);
280
281 return getSplits(scan, manifest, regionInfos, restoreDir, conf, splitAlgo, numSplits);
282 }
283
284 public static RegionSplitter.SplitAlgorithm getSplitAlgo(Configuration conf) throws IOException{
285 String splitAlgoClassName = conf.get(SPLIT_ALGO);
286 if (splitAlgoClassName == null)
287 return null;
288 try {
289 return ((Class<? extends RegionSplitter.SplitAlgorithm>)
290 Class.forName(splitAlgoClassName)).newInstance();
291 } catch (ClassNotFoundException e) {
292 throw new IOException("SplitAlgo class " + splitAlgoClassName +
293 " is not found", e);
294 } catch (InstantiationException e) {
295 throw new IOException("SplitAlgo class " + splitAlgoClassName +
296 " is not instantiable", e);
297 } catch (IllegalAccessException e) {
298 throw new IOException("SplitAlgo class " + splitAlgoClassName +
299 " is not instantiable", e);
300 }
301 }
302
303 public static List<HRegionInfo> getRegionInfosFromManifest(SnapshotManifest manifest) {
304 List<SnapshotRegionManifest> regionManifests = manifest.getRegionManifests();
305 if (regionManifests == null) {
306 throw new IllegalArgumentException("Snapshot seems empty");
307 }
308
309 List<HRegionInfo> regionInfos = Lists.newArrayListWithCapacity(regionManifests.size());
310
311 for (SnapshotRegionManifest regionManifest : regionManifests) {
312 regionInfos.add(HRegionInfo.convert(regionManifest.getRegionInfo()));
313 }
314 return regionInfos;
315 }
316
317 public static SnapshotManifest getSnapshotManifest(Configuration conf, String snapshotName,
318 Path rootDir, FileSystem fs) throws IOException {
319 Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
320 SnapshotDescription snapshotDesc = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
321 return SnapshotManifest.open(conf, fs, snapshotDir, snapshotDesc);
322 }
323
324 public static Scan extractScanFromConf(Configuration conf) throws IOException {
325 Scan scan = null;
326 if (conf.get(TableInputFormat.SCAN) != null) {
327 scan = TableMapReduceUtil.convertStringToScan(conf.get(TableInputFormat.SCAN));
328 } else if (conf.get(org.apache.hadoop.hbase.mapred.TableInputFormat.COLUMN_LIST) != null) {
329 String[] columns =
330 conf.get(org.apache.hadoop.hbase.mapred.TableInputFormat.COLUMN_LIST).split(" ");
331 scan = new Scan();
332 for (String col : columns) {
333 scan.addFamily(Bytes.toBytes(col));
334 }
335 } else {
336 throw new IllegalArgumentException("Unable to create scan");
337 }
338 return scan;
339 }
340
341 public static List<InputSplit> getSplits(Scan scan, SnapshotManifest manifest,
342 List<HRegionInfo> regionManifests, Path restoreDir, Configuration conf) throws IOException {
343 return getSplits(scan, manifest, regionManifests, restoreDir, conf, null, 1);
344 }
345
346 public static List<InputSplit> getSplits(Scan scan, SnapshotManifest manifest,
347 List<HRegionInfo> regionManifests, Path restoreDir,
348 Configuration conf, RegionSplitter.SplitAlgorithm sa, int numSplits) throws IOException {
349
350 HTableDescriptor htd = manifest.getTableDescriptor();
351
352 Path tableDir = FSUtils.getTableDir(restoreDir, htd.getTableName());
353
354 List<InputSplit> splits = new ArrayList<InputSplit>();
355 for (HRegionInfo hri : regionManifests) {
356
357 if (hri.isOffline() && (hri.isSplit() || hri.isSplitParent())) {
358 continue;
359 }
360
361 if (numSplits > 1) {
362 byte[][] sp = sa.split(hri.getStartKey(), hri.getEndKey(), numSplits, true);
363 for (int i = 0; i < sp.length - 1; i++) {
364 if (CellUtil.overlappingKeys(scan.getStartRow(), scan.getStopRow(), sp[i],
365 sp[i + 1])) {
366
367
368 List<String> hosts = getBestLocations(conf,
369 HRegion.computeHDFSBlocksDistribution(conf, htd, hri, tableDir));
370
371 int len = Math.min(3, hosts.size());
372 hosts = hosts.subList(0, len);
373 Scan boundedScan = new Scan(scan);
374 if (scan.getStartRow().length == 0) {
375 boundedScan.setStartRow(sp[i]);
376 } else {
377 boundedScan.setStartRow(
378 Bytes.compareTo(scan.getStartRow(), sp[i]) > 0 ? scan.getStartRow() : sp[i]);
379 }
380
381 if (scan.getStopRow().length == 0) {
382 boundedScan.setStopRow(sp[i + 1]);
383 } else {
384 boundedScan.setStopRow(
385 Bytes.compareTo(scan.getStopRow(), sp[i + 1]) < 0 ? scan.getStopRow() : sp[i + 1]);
386 }
387 splits.add(new InputSplit(htd, hri, hosts, boundedScan, restoreDir));
388 }
389 }
390 } else {
391 if (CellUtil.overlappingKeys(scan.getStartRow(), scan.getStopRow(), hri.getStartKey(),
392 hri.getEndKey())) {
393
394
395 List<String> hosts = getBestLocations(conf,
396 HRegion.computeHDFSBlocksDistribution(conf, htd, hri, tableDir));
397
398 int len = Math.min(3, hosts.size());
399 hosts = hosts.subList(0, len);
400 splits.add(new InputSplit(htd, hri, hosts, scan, restoreDir));
401 }
402 }
403 }
404
405 return splits;
406
407 }
408
409
410
411
412
413
414
415
416
417
418
419
420
421 public static List<String> getBestLocations(
422 Configuration conf, HDFSBlocksDistribution blockDistribution) {
423 List<String> locations = new ArrayList<String>(3);
424
425 HostAndWeight[] hostAndWeights = blockDistribution.getTopHostsWithWeights();
426
427 if (hostAndWeights.length == 0) {
428 return locations;
429 }
430
431 HostAndWeight topHost = hostAndWeights[0];
432 locations.add(topHost.getHost());
433
434
435 double cutoffMultiplier
436 = conf.getFloat(LOCALITY_CUTOFF_MULTIPLIER, DEFAULT_LOCALITY_CUTOFF_MULTIPLIER);
437
438 double filterWeight = topHost.getWeight() * cutoffMultiplier;
439
440 for (int i = 1; i < hostAndWeights.length; i++) {
441 if (hostAndWeights[i].getWeight() >= filterWeight) {
442 locations.add(hostAndWeights[i].getHost());
443 } else {
444 break;
445 }
446 }
447
448 return locations;
449 }
450
451 private static String getSnapshotName(Configuration conf) {
452 String snapshotName = conf.get(SNAPSHOT_NAME_KEY);
453 if (snapshotName == null) {
454 throw new IllegalArgumentException("Snapshot name must be provided");
455 }
456 return snapshotName;
457 }
458
459
460
461
462
463
464
465
466
467
468 public static void setInput(Configuration conf, String snapshotName, Path restoreDir)
469 throws IOException {
470 setInput(conf, snapshotName, restoreDir, null, 1);
471 }
472
473
474
475
476
477
478
479
480
481
482
483
484 public static void setInput(Configuration conf, String snapshotName, Path restoreDir,
485 RegionSplitter.SplitAlgorithm splitAlgo, int numSplitsPerRegion)
486 throws IOException {
487 conf.set(SNAPSHOT_NAME_KEY, snapshotName);
488 if (numSplitsPerRegion < 1) {
489 throw new IllegalArgumentException("numSplits must be >= 1, " +
490 "illegal numSplits : " + numSplitsPerRegion);
491 }
492 if (splitAlgo == null && numSplitsPerRegion > 1) {
493 throw new IllegalArgumentException("Split algo can't be null when numSplits > 1");
494 }
495 if (splitAlgo != null) {
496 conf.set(SPLIT_ALGO, splitAlgo.getClass().getName());
497 }
498 conf.setInt(NUM_SPLITS_PER_REGION, numSplitsPerRegion);
499 conf.set(SNAPSHOT_NAME_KEY, snapshotName);
500
501 Path rootDir = FSUtils.getRootDir(conf);
502 FileSystem fs = rootDir.getFileSystem(conf);
503
504 restoreDir = new Path(restoreDir, UUID.randomUUID().toString());
505
506
507 RestoreSnapshotHelper.copySnapshotForScanner(conf, fs, rootDir, restoreDir, snapshotName);
508
509 conf.set(RESTORE_DIR_KEY, restoreDir.toString());
510 }
511 }