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.rest;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertTrue;
022
023import java.io.ByteArrayInputStream;
024import java.io.IOException;
025import java.net.InetSocketAddress;
026import java.util.ArrayList;
027import java.util.Iterator;
028import java.util.List;
029import javax.xml.bind.JAXBContext;
030import javax.xml.bind.JAXBException;
031import org.apache.hadoop.hbase.CellUtil;
032import org.apache.hadoop.hbase.HBaseClassTestRule;
033import org.apache.hadoop.hbase.HBaseTestingUtility;
034import org.apache.hadoop.hbase.HColumnDescriptor;
035import org.apache.hadoop.hbase.HRegionInfo;
036import org.apache.hadoop.hbase.HRegionLocation;
037import org.apache.hadoop.hbase.HTableDescriptor;
038import org.apache.hadoop.hbase.ServerName;
039import org.apache.hadoop.hbase.TableName;
040import org.apache.hadoop.hbase.client.Admin;
041import org.apache.hadoop.hbase.client.Connection;
042import org.apache.hadoop.hbase.client.Durability;
043import org.apache.hadoop.hbase.client.Put;
044import org.apache.hadoop.hbase.client.RegionLocator;
045import org.apache.hadoop.hbase.client.Table;
046import org.apache.hadoop.hbase.regionserver.TestEndToEndSplitTransaction;
047import org.apache.hadoop.hbase.rest.client.Client;
048import org.apache.hadoop.hbase.rest.client.Cluster;
049import org.apache.hadoop.hbase.rest.client.Response;
050import org.apache.hadoop.hbase.rest.model.TableInfoModel;
051import org.apache.hadoop.hbase.rest.model.TableListModel;
052import org.apache.hadoop.hbase.rest.model.TableModel;
053import org.apache.hadoop.hbase.rest.model.TableRegionModel;
054import org.apache.hadoop.hbase.testclassification.MediumTests;
055import org.apache.hadoop.hbase.testclassification.RestTests;
056import org.apache.hadoop.hbase.util.Bytes;
057import org.apache.hadoop.util.StringUtils;
058import org.junit.AfterClass;
059import org.junit.BeforeClass;
060import org.junit.ClassRule;
061import org.junit.Test;
062import org.junit.experimental.categories.Category;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066@Category({RestTests.class, MediumTests.class})
067public class TestTableResource {
068
069  @ClassRule
070  public static final HBaseClassTestRule CLASS_RULE =
071      HBaseClassTestRule.forClass(TestTableResource.class);
072
073  private static final Logger LOG = LoggerFactory.getLogger(TestTableResource.class);
074
075  private static TableName TABLE = TableName.valueOf("TestTableResource");
076  private static String COLUMN_FAMILY = "test";
077  private static String COLUMN = COLUMN_FAMILY + ":qualifier";
078  private static List<HRegionLocation> regionMap;
079
080  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
081  private static final HBaseRESTTestingUtility REST_TEST_UTIL =
082    new HBaseRESTTestingUtility();
083  private static Client client;
084  private static JAXBContext context;
085
086  @BeforeClass
087  public static void setUpBeforeClass() throws Exception {
088    TEST_UTIL.startMiniCluster(3);
089    REST_TEST_UTIL.startServletContainer(TEST_UTIL.getConfiguration());
090    client = new Client(new Cluster().add("localhost",
091      REST_TEST_UTIL.getServletPort()));
092    context = JAXBContext.newInstance(
093        TableModel.class,
094        TableInfoModel.class,
095        TableListModel.class,
096        TableRegionModel.class);
097    Admin admin = TEST_UTIL.getAdmin();
098    if (admin.tableExists(TABLE)) {
099      return;
100    }
101    HTableDescriptor htd = new HTableDescriptor(TABLE);
102    htd.addFamily(new HColumnDescriptor(COLUMN_FAMILY));
103    admin.createTable(htd);
104    byte[] k = new byte[3];
105    byte [][] famAndQf = CellUtil.parseColumn(Bytes.toBytes(COLUMN));
106    List<Put> puts = new ArrayList<>();
107    for (byte b1 = 'a'; b1 < 'z'; b1++) {
108      for (byte b2 = 'a'; b2 < 'z'; b2++) {
109        for (byte b3 = 'a'; b3 < 'z'; b3++) {
110          k[0] = b1;
111          k[1] = b2;
112          k[2] = b3;
113          Put put = new Put(k);
114          put.setDurability(Durability.SKIP_WAL);
115          put.addColumn(famAndQf[0], famAndQf[1], k);
116          puts.add(put);
117        }
118      }
119    }
120    Connection connection = TEST_UTIL.getConnection();
121
122    Table table =  connection.getTable(TABLE);
123    table.put(puts);
124    table.close();
125    // get the initial layout (should just be one region)
126
127    RegionLocator regionLocator = connection.getRegionLocator(TABLE);
128    List<HRegionLocation> m = regionLocator.getAllRegionLocations();
129    assertEquals(1, m.size());
130    // tell the master to split the table
131    admin.split(TABLE);
132    // give some time for the split to happen
133
134    TestEndToEndSplitTransaction.blockUntilRegionSplit(TEST_UTIL.getConfiguration(), 60000,
135      m.get(0).getRegionInfo().getRegionName(), true);
136    long timeout = System.currentTimeMillis() + (15 * 1000);
137    while (System.currentTimeMillis() < timeout && m.size()!=2){
138      try {
139        Thread.sleep(250);
140      } catch (InterruptedException e) {
141        LOG.warn(StringUtils.stringifyException(e));
142      }
143      // check again
144      m = regionLocator.getAllRegionLocations();
145    }
146
147    // should have two regions now
148    assertEquals(2, m.size());
149    regionMap = m;
150    LOG.info("regions: " + regionMap);
151    regionLocator.close();
152  }
153
154  @AfterClass
155  public static void tearDownAfterClass() throws Exception {
156    REST_TEST_UTIL.shutdownServletContainer();
157    TEST_UTIL.shutdownMiniCluster();
158  }
159
160  private static void checkTableList(TableListModel model) {
161    boolean found = false;
162    Iterator<TableModel> tables = model.getTables().iterator();
163    assertTrue(tables.hasNext());
164    while (tables.hasNext()) {
165      TableModel table = tables.next();
166      if (table.getName().equals(TABLE.getNameAsString())) {
167        found = true;
168        break;
169      }
170    }
171    assertTrue(found);
172  }
173
174  void checkTableInfo(TableInfoModel model) {
175    assertEquals(model.getName(), TABLE.getNameAsString());
176    Iterator<TableRegionModel> regions = model.getRegions().iterator();
177    assertTrue(regions.hasNext());
178    while (regions.hasNext()) {
179      TableRegionModel region = regions.next();
180      boolean found = false;
181      for (HRegionLocation e: regionMap) {
182        HRegionInfo hri = e.getRegionInfo();
183        String hriRegionName = hri.getRegionNameAsString();
184        String regionName = region.getName();
185        if (hriRegionName.equals(regionName)) {
186          found = true;
187          byte[] startKey = hri.getStartKey();
188          byte[] endKey = hri.getEndKey();
189          ServerName serverName = e.getServerName();
190          InetSocketAddress sa =
191              new InetSocketAddress(serverName.getHostname(), serverName.getPort());
192          String location = sa.getHostName() + ":" +
193            Integer.valueOf(sa.getPort());
194          assertEquals(hri.getRegionId(), region.getId());
195          assertTrue(Bytes.equals(startKey, region.getStartKey()));
196          assertTrue(Bytes.equals(endKey, region.getEndKey()));
197          assertEquals(location, region.getLocation());
198          break;
199        }
200      }
201      assertTrue(found);
202    }
203  }
204
205  @Test
206  public void testTableListText() throws IOException {
207    Response response = client.get("/", Constants.MIMETYPE_TEXT);
208    assertEquals(200, response.getCode());
209    assertEquals(Constants.MIMETYPE_TEXT, response.getHeader("content-type"));
210  }
211
212  @Test
213  public void testTableListXML() throws IOException, JAXBException {
214    Response response = client.get("/", Constants.MIMETYPE_XML);
215    assertEquals(200, response.getCode());
216    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
217    TableListModel model = (TableListModel)
218      context.createUnmarshaller()
219        .unmarshal(new ByteArrayInputStream(response.getBody()));
220    checkTableList(model);
221  }
222
223  @Test
224  public void testTableListJSON() throws IOException {
225    Response response = client.get("/", Constants.MIMETYPE_JSON);
226    assertEquals(200, response.getCode());
227    assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
228  }
229
230  @Test
231  public void testTableListPB() throws IOException, JAXBException {
232    Response response = client.get("/", Constants.MIMETYPE_PROTOBUF);
233    assertEquals(200, response.getCode());
234    assertEquals(Constants.MIMETYPE_PROTOBUF, response.getHeader("content-type"));
235    TableListModel model = new TableListModel();
236    model.getObjectFromMessage(response.getBody());
237    checkTableList(model);
238    response = client.get("/", Constants.MIMETYPE_PROTOBUF_IETF);
239    assertEquals(200, response.getCode());
240    assertEquals(Constants.MIMETYPE_PROTOBUF_IETF, response.getHeader("content-type"));
241    model = new TableListModel();
242    model.getObjectFromMessage(response.getBody());
243    checkTableList(model);
244  }
245
246  @Test
247  public void testTableInfoText() throws IOException {
248    Response response = client.get("/" + TABLE + "/regions", Constants.MIMETYPE_TEXT);
249    assertEquals(200, response.getCode());
250    assertEquals(Constants.MIMETYPE_TEXT, response.getHeader("content-type"));
251  }
252
253  @Test
254  public void testTableInfoXML() throws IOException, JAXBException {
255    Response response = client.get("/" + TABLE + "/regions",  Constants.MIMETYPE_XML);
256    assertEquals(200, response.getCode());
257    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
258    TableInfoModel model = (TableInfoModel)
259      context.createUnmarshaller()
260        .unmarshal(new ByteArrayInputStream(response.getBody()));
261    checkTableInfo(model);
262  }
263
264  @Test
265  public void testTableInfoJSON() throws IOException {
266    Response response = client.get("/" + TABLE + "/regions", Constants.MIMETYPE_JSON);
267    assertEquals(200, response.getCode());
268    assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
269  }
270
271  @Test
272  public void testTableInfoPB() throws IOException, JAXBException {
273    Response response = client.get("/" + TABLE + "/regions", Constants.MIMETYPE_PROTOBUF);
274    assertEquals(200, response.getCode());
275    assertEquals(Constants.MIMETYPE_PROTOBUF, response.getHeader("content-type"));
276    TableInfoModel model = new TableInfoModel();
277    model.getObjectFromMessage(response.getBody());
278    checkTableInfo(model);
279    response = client.get("/" + TABLE + "/regions", Constants.MIMETYPE_PROTOBUF_IETF);
280    assertEquals(200, response.getCode());
281    assertEquals(Constants.MIMETYPE_PROTOBUF_IETF, response.getHeader("content-type"));
282    model = new TableInfoModel();
283    model.getObjectFromMessage(response.getBody());
284    checkTableInfo(model);
285  }
286
287}
288