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 java.io.IOException;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.apache.hadoop.hbase.classification.InterfaceAudience;
26 import org.apache.hadoop.hbase.classification.InterfaceStability;
27 import org.apache.hadoop.conf.Configurable;
28 import org.apache.hadoop.conf.Configuration;
29 import org.apache.hadoop.hbase.HBaseConfiguration;
30 import org.apache.hadoop.hbase.TableName;
31 import org.apache.hadoop.hbase.client.Connection;
32 import org.apache.hadoop.hbase.client.ConnectionFactory;
33 import org.apache.hadoop.hbase.client.RegionLocator;
34 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
35 import org.apache.hadoop.hbase.mapred.TableOutputFormat;
36 import org.apache.hadoop.hbase.util.Bytes;
37 import org.apache.hadoop.mapreduce.Partitioner;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 @InterfaceAudience.Public
53 @InterfaceStability.Stable
54 public class HRegionPartitioner<KEY, VALUE>
55 extends Partitioner<ImmutableBytesWritable, VALUE>
56 implements Configurable {
57
58 private static final Log LOG = LogFactory.getLog(HRegionPartitioner.class);
59 private Configuration conf = null;
60
61 private Connection connection;
62 private RegionLocator locator;
63 private byte[][] startKeys;
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 @Override
79 public int getPartition(ImmutableBytesWritable key,
80 VALUE value, int numPartitions) {
81 byte[] region = null;
82
83 if (this.startKeys.length == 1){
84 return 0;
85 }
86 try {
87
88
89 region = this.locator.getRegionLocation(key.get()).getRegionInfo().getStartKey();
90 } catch (IOException e) {
91 LOG.error(e);
92 }
93 for (int i = 0; i < this.startKeys.length; i++){
94 if (Bytes.compareTo(region, this.startKeys[i]) == 0 ){
95 if (i >= numPartitions-1){
96
97 return (Integer.toString(i).hashCode()
98 & Integer.MAX_VALUE) % numPartitions;
99 }
100 return i;
101 }
102 }
103
104 return 0;
105 }
106
107
108
109
110
111
112
113 @Override
114 public Configuration getConf() {
115 return conf;
116 }
117
118
119
120
121
122
123
124
125
126 @Override
127 public void setConf(Configuration configuration) {
128 this.conf = HBaseConfiguration.create(configuration);
129 try {
130 this.connection = ConnectionFactory.createConnection(HBaseConfiguration.create(conf));
131 TableName tableName = TableName.valueOf(conf.get(TableOutputFormat.OUTPUT_TABLE));
132 this.locator = this.connection.getRegionLocator(tableName);
133 } catch (IOException e) {
134 LOG.error(e);
135 }
136 try {
137 this.startKeys = this.locator.getStartKeys();
138 } catch (IOException e) {
139 LOG.error(e);
140 }
141 }
142 }