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.regionserver;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNull;
022import static org.junit.Assert.assertTrue;
023
024import com.google.protobuf.RpcCallback;
025import com.google.protobuf.RpcController;
026import com.google.protobuf.Service;
027import com.google.protobuf.ServiceException;
028import java.io.IOException;
029import java.util.Collections;
030import java.util.Map;
031import org.apache.hadoop.hbase.CoprocessorEnvironment;
032import org.apache.hadoop.hbase.HBaseClassTestRule;
033import org.apache.hadoop.hbase.HBaseTestingUtility;
034import org.apache.hadoop.hbase.HRegionLocation;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.client.Put;
037import org.apache.hadoop.hbase.client.RegionLocator;
038import org.apache.hadoop.hbase.client.Table;
039import org.apache.hadoop.hbase.client.coprocessor.Batch;
040import org.apache.hadoop.hbase.coprocessor.CoprocessorException;
041import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
042import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
043import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
044import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos;
045import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.CountRequest;
046import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.CountResponse;
047import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.HelloRequest;
048import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.HelloResponse;
049import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.IncrementCountRequest;
050import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.IncrementCountResponse;
051import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.NoopRequest;
052import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.NoopResponse;
053import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.PingRequest;
054import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.PingResponse;
055import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils;
056import org.apache.hadoop.hbase.testclassification.MediumTests;
057import org.apache.hadoop.hbase.testclassification.RegionServerTests;
058import org.apache.hadoop.hbase.util.Bytes;
059import org.junit.After;
060import org.junit.AfterClass;
061import org.junit.Before;
062import org.junit.BeforeClass;
063import org.junit.ClassRule;
064import org.junit.Test;
065import org.junit.experimental.categories.Category;
066import org.slf4j.Logger;
067import org.slf4j.LoggerFactory;
068
069@Category({RegionServerTests.class, MediumTests.class})
070public class TestServerCustomProtocol {
071
072  @ClassRule
073  public static final HBaseClassTestRule CLASS_RULE =
074      HBaseClassTestRule.forClass(TestServerCustomProtocol.class);
075
076  private static final Logger LOG = LoggerFactory.getLogger(TestServerCustomProtocol.class);
077  static final String WHOAREYOU = "Who are you?";
078  static final String NOBODY = "nobody";
079  static final String HELLO = "Hello, ";
080
081  /* Test protocol implementation */
082  public static class PingHandler extends PingProtos.PingService implements RegionCoprocessor {
083    private int counter = 0;
084
085    @Override
086    public void start(CoprocessorEnvironment env) throws IOException {
087      if (env instanceof RegionCoprocessorEnvironment) return;
088      throw new CoprocessorException("Must be loaded on a table region!");
089    }
090
091    @Override
092    public void stop(CoprocessorEnvironment env) throws IOException {
093      // Nothing to do.
094    }
095
096    @Override
097    public void ping(RpcController controller, PingRequest request,
098        RpcCallback<PingResponse> done) {
099      this.counter++;
100      done.run(PingResponse.newBuilder().setPong("pong").build());
101    }
102
103    @Override
104    public void count(RpcController controller, CountRequest request,
105        RpcCallback<CountResponse> done) {
106      done.run(CountResponse.newBuilder().setCount(this.counter).build());
107    }
108
109    @Override
110    public void increment(RpcController controller,
111        IncrementCountRequest request, RpcCallback<IncrementCountResponse> done) {
112      this.counter += request.getDiff();
113      done.run(IncrementCountResponse.newBuilder().setCount(this.counter).build());
114    }
115
116    @Override
117    public void hello(RpcController controller, HelloRequest request,
118        RpcCallback<HelloResponse> done) {
119      if (!request.hasName()) done.run(HelloResponse.newBuilder().setResponse(WHOAREYOU).build());
120      else if (request.getName().equals(NOBODY)) done.run(HelloResponse.newBuilder().build());
121      else done.run(HelloResponse.newBuilder().setResponse(HELLO + request.getName()).build());
122    }
123
124    @Override
125    public void noop(RpcController controller, NoopRequest request,
126        RpcCallback<NoopResponse> done) {
127      done.run(NoopResponse.newBuilder().build());
128    }
129
130    @Override
131    public Iterable<Service> getServices() {
132      return Collections.singleton(this);
133    }
134  }
135
136  private static final TableName TEST_TABLE = TableName.valueOf("test");
137  private static final byte[] TEST_FAMILY = Bytes.toBytes("f1");
138
139  private static final byte[] ROW_A = Bytes.toBytes("aaa");
140  private static final byte[] ROW_B = Bytes.toBytes("bbb");
141  private static final byte[] ROW_C = Bytes.toBytes("ccc");
142
143  private static final byte[] ROW_AB = Bytes.toBytes("abb");
144  private static final byte[] ROW_BC = Bytes.toBytes("bcc");
145
146  private static HBaseTestingUtility util = new HBaseTestingUtility();
147
148  @BeforeClass
149  public static void setupBeforeClass() throws Exception {
150    util.getConfiguration().set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
151      PingHandler.class.getName());
152    util.startMiniCluster();
153  }
154
155  @Before
156  public void before()  throws Exception {
157    final byte[][] SPLIT_KEYS = new byte[][] { ROW_B, ROW_C };
158    Table table = util.createTable(TEST_TABLE, TEST_FAMILY, SPLIT_KEYS);
159
160    Put puta = new Put( ROW_A );
161    puta.addColumn(TEST_FAMILY, Bytes.toBytes("col1"), Bytes.toBytes(1));
162    table.put(puta);
163
164    Put putb = new Put( ROW_B );
165    putb.addColumn(TEST_FAMILY, Bytes.toBytes("col1"), Bytes.toBytes(1));
166    table.put(putb);
167
168    Put putc = new Put( ROW_C );
169    putc.addColumn(TEST_FAMILY, Bytes.toBytes("col1"), Bytes.toBytes(1));
170    table.put(putc);
171  }
172
173  @After
174  public void after() throws Exception {
175    util.deleteTable(TEST_TABLE);
176  }
177
178  @AfterClass
179  public static void tearDownAfterClass() throws Exception {
180    util.shutdownMiniCluster();
181  }
182
183  @Test
184  public void testSingleProxy() throws Throwable {
185    Table table = util.getConnection().getTable(TEST_TABLE);
186    Map<byte [], String> results = ping(table, null, null);
187    // There are three regions so should get back three results.
188    assertEquals(3, results.size());
189    for (Map.Entry<byte [], String> e: results.entrySet()) {
190      assertEquals("Invalid custom protocol response", "pong", e.getValue());
191    }
192    hello(table, "George", HELLO + "George");
193    LOG.info("Did george");
194    hello(table, null, "Who are you?");
195    LOG.info("Who are you");
196    hello(table, NOBODY, null);
197    LOG.info(NOBODY);
198    Map<byte [], Integer> intResults = table.coprocessorService(PingProtos.PingService.class,
199      null, null,
200      new Batch.Call<PingProtos.PingService, Integer>() {
201        @Override
202        public Integer call(PingProtos.PingService instance) throws IOException {
203          CoprocessorRpcUtils.BlockingRpcCallback<PingProtos.CountResponse> rpcCallback =
204            new CoprocessorRpcUtils.BlockingRpcCallback<>();
205          instance.count(null, PingProtos.CountRequest.newBuilder().build(), rpcCallback);
206          return rpcCallback.get().getCount();
207        }
208      });
209    int count = -1;
210    for (Map.Entry<byte [], Integer> e: intResults.entrySet()) {
211      assertTrue(e.getValue() > 0);
212      count = e.getValue();
213    }
214    final int diff = 5;
215    intResults = table.coprocessorService(PingProtos.PingService.class,
216      null, null,
217      new Batch.Call<PingProtos.PingService, Integer>() {
218        @Override
219        public Integer call(PingProtos.PingService instance) throws IOException {
220          CoprocessorRpcUtils.BlockingRpcCallback<PingProtos.IncrementCountResponse> rpcCallback =
221            new CoprocessorRpcUtils.BlockingRpcCallback<>();
222          instance.increment(null,
223              PingProtos.IncrementCountRequest.newBuilder().setDiff(diff).build(),
224            rpcCallback);
225          return rpcCallback.get().getCount();
226        }
227      });
228    // There are three regions so should get back three results.
229    assertEquals(3, results.size());
230    for (Map.Entry<byte [], Integer> e: intResults.entrySet()) {
231      assertEquals(e.getValue().intValue(), count + diff);
232    }
233    table.close();
234  }
235
236  private Map<byte [], String> hello(final Table table, final String send, final String response)
237  throws ServiceException, Throwable {
238    Map<byte [], String> results = hello(table, send);
239    for (Map.Entry<byte [], String> e: results.entrySet()) {
240      assertEquals("Invalid custom protocol response", response, e.getValue());
241    }
242    return results;
243  }
244
245  private Map<byte [], String> hello(final Table table, final String send)
246  throws ServiceException, Throwable {
247    return hello(table, send, null, null);
248  }
249
250  private Map<byte [], String> hello(final Table table, final String send, final byte [] start,
251      final byte [] end)
252  throws ServiceException, Throwable {
253    return table.coprocessorService(PingProtos.PingService.class,
254        start, end,
255        new Batch.Call<PingProtos.PingService, String>() {
256          @Override
257          public String call(PingProtos.PingService instance) throws IOException {
258            CoprocessorRpcUtils.BlockingRpcCallback<PingProtos.HelloResponse> rpcCallback =
259              new CoprocessorRpcUtils.BlockingRpcCallback<>();
260            PingProtos.HelloRequest.Builder builder = PingProtos.HelloRequest.newBuilder();
261            if (send != null) builder.setName(send);
262            instance.hello(null, builder.build(), rpcCallback);
263            PingProtos.HelloResponse r = rpcCallback.get();
264            return r != null && r.hasResponse()? r.getResponse(): null;
265          }
266        });
267  }
268
269  private Map<byte [], String> compoundOfHelloAndPing(final Table table, final byte [] start,
270      final byte [] end)
271  throws ServiceException, Throwable {
272    return table.coprocessorService(PingProtos.PingService.class,
273        start, end,
274        new Batch.Call<PingProtos.PingService, String>() {
275          @Override
276          public String call(PingProtos.PingService instance) throws IOException {
277            CoprocessorRpcUtils.BlockingRpcCallback<PingProtos.HelloResponse> rpcCallback =
278              new CoprocessorRpcUtils.BlockingRpcCallback<>();
279            PingProtos.HelloRequest.Builder builder = PingProtos.HelloRequest.newBuilder();
280            // Call ping on same instance.  Use result calling hello on same instance.
281            builder.setName(doPing(instance));
282            instance.hello(null, builder.build(), rpcCallback);
283            PingProtos.HelloResponse r = rpcCallback.get();
284            return r != null && r.hasResponse()? r.getResponse(): null;
285          }
286        });
287  }
288
289  private Map<byte [], String> noop(final Table table, final byte [] start,
290      final byte [] end)
291  throws ServiceException, Throwable {
292    return table.coprocessorService(PingProtos.PingService.class, start, end,
293        new Batch.Call<PingProtos.PingService, String>() {
294          @Override
295          public String call(PingProtos.PingService instance) throws IOException {
296            CoprocessorRpcUtils.BlockingRpcCallback<PingProtos.NoopResponse> rpcCallback =
297              new CoprocessorRpcUtils.BlockingRpcCallback<>();
298            PingProtos.NoopRequest.Builder builder = PingProtos.NoopRequest.newBuilder();
299            instance.noop(null, builder.build(), rpcCallback);
300            rpcCallback.get();
301            // Looks like null is expected when void.  That is what the test below is looking for
302            return null;
303          }
304        });
305  }
306
307  @Test
308  public void testSingleMethod() throws Throwable {
309    try (Table table = util.getConnection().getTable(TEST_TABLE);
310        RegionLocator locator = util.getConnection().getRegionLocator(TEST_TABLE)) {
311      Map<byte [], String> results = table.coprocessorService(PingProtos.PingService.class,
312        null, ROW_A,
313        new Batch.Call<PingProtos.PingService, String>() {
314          @Override
315          public String call(PingProtos.PingService instance) throws IOException {
316            CoprocessorRpcUtils.BlockingRpcCallback<PingProtos.PingResponse> rpcCallback =
317              new CoprocessorRpcUtils.BlockingRpcCallback<>();
318            instance.ping(null, PingProtos.PingRequest.newBuilder().build(), rpcCallback);
319            return rpcCallback.get().getPong();
320          }
321        });
322      // Should have gotten results for 1 of the three regions only since we specified
323      // rows from 1 region
324      assertEquals(1, results.size());
325      verifyRegionResults(locator, results, ROW_A);
326
327      final String name = "NAME";
328      results = hello(table, name, null, ROW_A);
329      // Should have gotten results for 1 of the three regions only since we specified
330      // rows from 1 region
331      assertEquals(1, results.size());
332      verifyRegionResults(locator, results, "Hello, NAME", ROW_A);
333    }
334  }
335
336  @Test
337  public void testRowRange() throws Throwable {
338    try (Table table = util.getConnection().getTable(TEST_TABLE);
339        RegionLocator locator = util.getConnection().getRegionLocator(TEST_TABLE)) {
340      for (HRegionLocation e: locator.getAllRegionLocations()) {
341        LOG.info("Region " + e.getRegionInfo().getRegionNameAsString()
342            + ", servername=" + e.getServerName());
343      }
344      // Here are what regions looked like on a run:
345      //
346      // test,,1355943549657.c65d4822d8bdecc033a96451f3a0f55d.
347      // test,bbb,1355943549661.110393b070dd1ed93441e0bc9b3ffb7e.
348      // test,ccc,1355943549665.c3d6d125141359cbbd2a43eaff3cdf74.
349
350      Map<byte [], String> results = ping(table, null, ROW_A);
351      // Should contain first region only.
352      assertEquals(1, results.size());
353      verifyRegionResults(locator, results, ROW_A);
354
355      // Test start row + empty end
356      results = ping(table, ROW_BC, null);
357      assertEquals(2, results.size());
358      // should contain last 2 regions
359      HRegionLocation loc = locator.getRegionLocation(ROW_A, true);
360      assertNull("Should be missing region for row aaa (prior to start row)",
361        results.get(loc.getRegionInfo().getRegionName()));
362      verifyRegionResults(locator, results, ROW_B);
363      verifyRegionResults(locator, results, ROW_C);
364
365      // test empty start + end
366      results = ping(table, null, ROW_BC);
367      // should contain the first 2 regions
368      assertEquals(2, results.size());
369      verifyRegionResults(locator, results, ROW_A);
370      verifyRegionResults(locator, results, ROW_B);
371      loc = locator.getRegionLocation(ROW_C, true);
372      assertNull("Should be missing region for row ccc (past stop row)",
373          results.get(loc.getRegionInfo().getRegionName()));
374
375      // test explicit start + end
376      results = ping(table, ROW_AB, ROW_BC);
377      // should contain first 2 regions
378      assertEquals(2, results.size());
379      verifyRegionResults(locator, results, ROW_A);
380      verifyRegionResults(locator, results, ROW_B);
381      loc = locator.getRegionLocation(ROW_C, true);
382      assertNull("Should be missing region for row ccc (past stop row)",
383          results.get(loc.getRegionInfo().getRegionName()));
384
385      // test single region
386      results = ping(table, ROW_B, ROW_BC);
387      // should only contain region bbb
388      assertEquals(1, results.size());
389      verifyRegionResults(locator, results, ROW_B);
390      loc = locator.getRegionLocation(ROW_A, true);
391      assertNull("Should be missing region for row aaa (prior to start)",
392          results.get(loc.getRegionInfo().getRegionName()));
393      loc = locator.getRegionLocation(ROW_C, true);
394      assertNull("Should be missing region for row ccc (past stop row)",
395          results.get(loc.getRegionInfo().getRegionName()));
396    }
397  }
398
399  private Map<byte [], String> ping(final Table table, final byte [] start, final byte [] end)
400  throws ServiceException, Throwable {
401    return table.coprocessorService(PingProtos.PingService.class, start, end,
402      new Batch.Call<PingProtos.PingService, String>() {
403        @Override
404        public String call(PingProtos.PingService instance) throws IOException {
405          return doPing(instance);
406        }
407      });
408  }
409
410  private static String doPing(PingProtos.PingService instance) throws IOException {
411    CoprocessorRpcUtils.BlockingRpcCallback<PingProtos.PingResponse> rpcCallback =
412        new CoprocessorRpcUtils.BlockingRpcCallback<>();
413      instance.ping(null, PingProtos.PingRequest.newBuilder().build(), rpcCallback);
414      return rpcCallback.get().getPong();
415  }
416
417  @Test
418  public void testCompoundCall() throws Throwable {
419    try (Table table = util.getConnection().getTable(TEST_TABLE);
420        RegionLocator locator = util.getConnection().getRegionLocator(TEST_TABLE)) {
421      Map<byte [], String> results = compoundOfHelloAndPing(table, ROW_A, ROW_C);
422      verifyRegionResults(locator, results, "Hello, pong", ROW_A);
423      verifyRegionResults(locator, results, "Hello, pong", ROW_B);
424      verifyRegionResults(locator, results, "Hello, pong", ROW_C);
425    }
426  }
427
428  @Test
429  public void testNullCall() throws Throwable {
430    try (Table table = util.getConnection().getTable(TEST_TABLE);
431        RegionLocator locator = util.getConnection().getRegionLocator(TEST_TABLE)) {
432      Map<byte[],String> results = hello(table, null, ROW_A, ROW_C);
433      verifyRegionResults(locator, results, "Who are you?", ROW_A);
434      verifyRegionResults(locator, results, "Who are you?", ROW_B);
435      verifyRegionResults(locator, results, "Who are you?", ROW_C);
436    }
437  }
438
439  @Test
440  public void testNullReturn() throws Throwable {
441    try (Table table = util.getConnection().getTable(TEST_TABLE);
442        RegionLocator locator = util.getConnection().getRegionLocator(TEST_TABLE)) {
443      Map<byte[],String> results = hello(table, "nobody", ROW_A, ROW_C);
444      verifyRegionResults(locator, results, null, ROW_A);
445      verifyRegionResults(locator, results, null, ROW_B);
446      verifyRegionResults(locator, results, null, ROW_C);
447    }
448  }
449
450  @Test
451  public void testEmptyReturnType() throws Throwable {
452    try (Table table = util.getConnection().getTable(TEST_TABLE)) {
453      Map<byte[],String> results = noop(table, ROW_A, ROW_C);
454      assertEquals("Should have results from three regions", 3, results.size());
455      // all results should be null
456      for (Object v : results.values()) {
457        assertNull(v);
458      }
459    }
460  }
461
462  private void verifyRegionResults(RegionLocator table,
463      Map<byte[],String> results, byte[] row) throws Exception {
464    verifyRegionResults(table, results, "pong", row);
465  }
466
467  private void verifyRegionResults(RegionLocator regionLocator,
468      Map<byte[], String> results, String expected, byte[] row)
469  throws Exception {
470    for (Map.Entry<byte [], String> e: results.entrySet()) {
471      LOG.info("row=" + Bytes.toString(row) + ", expected=" + expected +
472       ", result key=" + Bytes.toString(e.getKey()) +
473       ", value=" + e.getValue());
474    }
475    HRegionLocation loc = regionLocator.getRegionLocation(row, true);
476    byte[] region = loc.getRegionInfo().getRegionName();
477    assertTrue("Results should contain region " +
478      Bytes.toStringBinary(region) + " for row '" + Bytes.toStringBinary(row)+ "'",
479      results.containsKey(region));
480    assertEquals("Invalid result for row '"+Bytes.toStringBinary(row)+"'",
481      expected, results.get(region));
482  }
483}