001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.mapreduce;
019
020import static org.apache.hadoop.hbase.client.Scan.SCAN_ATTRIBUTES_TABLE_NAME;
021
022import java.io.IOException;
023import java.util.ArrayList;
024import java.util.List;
025import java.util.Map;
026import java.util.TreeMap;
027import java.util.concurrent.ExecutorService;
028import java.util.concurrent.atomic.AtomicInteger;
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.hbase.HBaseClassTestRule;
031import org.apache.hadoop.hbase.HBaseConfiguration;
032import org.apache.hadoop.hbase.HConstants;
033import org.apache.hadoop.hbase.HRegionLocation;
034import org.apache.hadoop.hbase.ServerName;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.client.Admin;
037import org.apache.hadoop.hbase.client.BufferedMutator;
038import org.apache.hadoop.hbase.client.BufferedMutatorParams;
039import org.apache.hadoop.hbase.client.ClusterConnection;
040import org.apache.hadoop.hbase.client.Connection;
041import org.apache.hadoop.hbase.client.RegionInfoBuilder;
042import org.apache.hadoop.hbase.client.RegionLocator;
043import org.apache.hadoop.hbase.client.Result;
044import org.apache.hadoop.hbase.client.Scan;
045import org.apache.hadoop.hbase.client.Table;
046import org.apache.hadoop.hbase.client.TableBuilder;
047import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
048import org.apache.hadoop.hbase.security.User;
049import org.apache.hadoop.hbase.testclassification.SmallTests;
050import org.apache.hadoop.hbase.util.Bytes;
051import org.apache.hadoop.hbase.util.Pair;
052import org.apache.hadoop.mapreduce.InputSplit;
053import org.apache.hadoop.mapreduce.JobContext;
054import org.apache.hadoop.mapreduce.RecordReader;
055import org.apache.hadoop.mapreduce.TaskAttemptContext;
056import org.junit.Assert;
057import org.junit.ClassRule;
058import org.junit.Rule;
059import org.junit.Test;
060import org.junit.experimental.categories.Category;
061import org.junit.rules.TestName;
062import org.mockito.Mockito;
063import org.mockito.invocation.InvocationOnMock;
064import org.mockito.stubbing.Answer;
065
066/**
067 * Tests of MultiTableInputFormatBase.
068 */
069@Category({ SmallTests.class })
070public class TestMultiTableInputFormatBase {
071
072  @ClassRule
073  public static final HBaseClassTestRule CLASS_RULE =
074    HBaseClassTestRule.forClass(TestMultiTableInputFormatBase.class);
075
076  @Rule
077  public final TestName name = new TestName();
078
079  /**
080   * Test getSplits only puts up one Connection. In past it has put up many Connections. Each
081   * Connection setup comes with a fresh new cache so we have to do fresh hit on hbase:meta. Should
082   * only do one Connection when doing getSplits even if a MultiTableInputFormat. n
083   */
084  @Test
085  public void testMRSplitsConnectionCount() throws IOException {
086    // Make instance of MTIFB.
087    MultiTableInputFormatBase mtif = new MultiTableInputFormatBase() {
088      @Override
089      public RecordReader<ImmutableBytesWritable, Result> createRecordReader(InputSplit split,
090        TaskAttemptContext context) throws IOException, InterruptedException {
091        return super.createRecordReader(split, context);
092      }
093    };
094    // Pass it a mocked JobContext. Make the JC return our Configuration.
095    // Load the Configuration so it returns our special Connection so we can interpolate
096    // canned responses.
097    JobContext mockedJobContext = Mockito.mock(JobContext.class);
098    Configuration c = HBaseConfiguration.create();
099    c.set(ClusterConnection.HBASE_CLIENT_CONNECTION_IMPL, MRSplitsConnection.class.getName());
100    Mockito.when(mockedJobContext.getConfiguration()).thenReturn(c);
101    // Invent a bunch of scans. Have each Scan go against a different table so a good spread.
102    List<Scan> scans = new ArrayList<>();
103    for (int i = 0; i < 10; i++) {
104      Scan scan = new Scan();
105      String tableName = this.name.getMethodName() + i;
106      scan.setAttribute(SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName));
107      scans.add(scan);
108    }
109    mtif.setScans(scans);
110    // Get splits. Assert that that more than one.
111    List<InputSplit> splits = mtif.getSplits(mockedJobContext);
112    Assert.assertTrue(splits.size() > 0);
113    // Assert only one Connection was made (see the static counter we have in the mocked
114    // Connection MRSplitsConnection Constructor.
115    Assert.assertEquals(1, MRSplitsConnection.creations.get());
116  }
117
118  /**
119   * Connection to use above in Test.
120   */
121  public static class MRSplitsConnection implements Connection {
122    private final Configuration configuration;
123    static final AtomicInteger creations = new AtomicInteger(0);
124
125    MRSplitsConnection(Configuration conf, ExecutorService pool, User user) throws IOException {
126      this.configuration = conf;
127      creations.incrementAndGet();
128    }
129
130    @Override
131    public void abort(String why, Throwable e) {
132
133    }
134
135    @Override
136    public boolean isAborted() {
137      return false;
138    }
139
140    @Override
141    public Configuration getConfiguration() {
142      return this.configuration;
143    }
144
145    @Override
146    public BufferedMutator getBufferedMutator(TableName tableName) throws IOException {
147      return null;
148    }
149
150    @Override
151    public BufferedMutator getBufferedMutator(BufferedMutatorParams params) throws IOException {
152      return null;
153    }
154
155    @Override
156    public RegionLocator getRegionLocator(final TableName tableName) throws IOException {
157      // Make up array of start keys. We start off w/ empty byte array.
158      final byte[][] startKeys = new byte[][] { HConstants.EMPTY_BYTE_ARRAY, Bytes.toBytes("aaaa"),
159        Bytes.toBytes("bbb"), Bytes.toBytes("ccc"), Bytes.toBytes("ddd"), Bytes.toBytes("eee"),
160        Bytes.toBytes("fff"), Bytes.toBytes("ggg"), Bytes.toBytes("hhh"), Bytes.toBytes("iii"),
161        Bytes.toBytes("lll"), Bytes.toBytes("mmm"), Bytes.toBytes("nnn"), Bytes.toBytes("ooo"),
162        Bytes.toBytes("ppp"), Bytes.toBytes("qqq"), Bytes.toBytes("rrr"), Bytes.toBytes("sss"),
163        Bytes.toBytes("ttt"), Bytes.toBytes("uuu"), Bytes.toBytes("vvv"), Bytes.toBytes("zzz") };
164      // Make an array of end keys. We end with the empty byte array.
165      final byte[][] endKeys =
166        new byte[][] { Bytes.toBytes("aaaa"), Bytes.toBytes("bbb"), Bytes.toBytes("ccc"),
167          Bytes.toBytes("ddd"), Bytes.toBytes("eee"), Bytes.toBytes("fff"), Bytes.toBytes("ggg"),
168          Bytes.toBytes("hhh"), Bytes.toBytes("iii"), Bytes.toBytes("lll"), Bytes.toBytes("mmm"),
169          Bytes.toBytes("nnn"), Bytes.toBytes("ooo"), Bytes.toBytes("ppp"), Bytes.toBytes("qqq"),
170          Bytes.toBytes("rrr"), Bytes.toBytes("sss"), Bytes.toBytes("ttt"), Bytes.toBytes("uuu"),
171          Bytes.toBytes("vvv"), Bytes.toBytes("zzz"), HConstants.EMPTY_BYTE_ARRAY };
172      // Now make a map of start keys to HRegionLocations. Let the server namber derive from
173      // the start key.
174      final Map<byte[], HRegionLocation> map =
175        new TreeMap<byte[], HRegionLocation>(Bytes.BYTES_COMPARATOR);
176      for (byte[] startKey : startKeys) {
177        HRegionLocation hrl =
178          new HRegionLocation(RegionInfoBuilder.newBuilder(tableName).setStartKey(startKey).build(),
179            ServerName.valueOf(Bytes.toString(startKey), 0, 0));
180        map.put(startKey, hrl);
181      }
182      // Get a list of the locations.
183      final List<HRegionLocation> locations = new ArrayList<HRegionLocation>(map.values());
184      // Now make a RegionLocator mock backed by the abpve map and list of locations.
185      RegionLocator mockedRegionLocator = Mockito.mock(RegionLocator.class);
186      Mockito
187        .when(
188          mockedRegionLocator.getRegionLocation(Mockito.any(byte[].class), Mockito.anyBoolean()))
189        .thenAnswer(new Answer<HRegionLocation>() {
190          @Override
191          public HRegionLocation answer(InvocationOnMock invocationOnMock) throws Throwable {
192            Object[] args = invocationOnMock.getArguments();
193            byte[] key = (byte[]) args[0];
194            return map.get(key);
195          }
196        });
197      Mockito.when(mockedRegionLocator.getAllRegionLocations()).thenReturn(locations);
198      Mockito.when(mockedRegionLocator.getStartEndKeys())
199        .thenReturn(new Pair<byte[][], byte[][]>(startKeys, endKeys));
200      Mockito.when(mockedRegionLocator.getName()).thenReturn(tableName);
201      return mockedRegionLocator;
202    }
203
204    @Override
205    public Admin getAdmin() throws IOException {
206      Admin admin = Mockito.mock(Admin.class);
207      Mockito.when(admin.getConfiguration()).thenReturn(getConfiguration());
208      return admin;
209    }
210
211    @Override
212    public Table getTable(TableName tableName) throws IOException {
213      Table table = Mockito.mock(Table.class);
214      Mockito.when(table.getName()).thenReturn(tableName);
215      return table;
216    }
217
218    @Override
219    public void close() throws IOException {
220
221    }
222
223    @Override
224    public boolean isClosed() {
225      return false;
226    }
227
228    @Override
229    public TableBuilder getTableBuilder(TableName tableName, ExecutorService pool) {
230      return Mockito.mock(TableBuilder.class);
231    }
232
233    @Override
234    public void clearRegionLocationCache() {
235    }
236
237    @Override
238    public String getClusterId() {
239      return null;
240    }
241  }
242}