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.coprocessor;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertTrue;
022
023import com.google.protobuf.Message;
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.Arrays;
027import java.util.Collection;
028import java.util.Collections;
029import java.util.HashSet;
030import java.util.List;
031import java.util.Set;
032import java.util.concurrent.CountDownLatch;
033import java.util.concurrent.atomic.AtomicInteger;
034import java.util.concurrent.atomic.AtomicLong;
035import org.apache.hadoop.conf.Configuration;
036import org.apache.hadoop.hbase.Cell;
037import org.apache.hadoop.hbase.CellUtil;
038import org.apache.hadoop.hbase.HBaseClassTestRule;
039import org.apache.hadoop.hbase.HBaseTestingUtility;
040import org.apache.hadoop.hbase.HConstants;
041import org.apache.hadoop.hbase.KeyValue;
042import org.apache.hadoop.hbase.TableName;
043import org.apache.hadoop.hbase.client.Delete;
044import org.apache.hadoop.hbase.client.Get;
045import org.apache.hadoop.hbase.client.IsolationLevel;
046import org.apache.hadoop.hbase.client.Mutation;
047import org.apache.hadoop.hbase.client.Put;
048import org.apache.hadoop.hbase.client.Scan;
049import org.apache.hadoop.hbase.client.Table;
050import org.apache.hadoop.hbase.client.coprocessor.RowProcessorClient;
051import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos;
052import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.FriendsOfFriendsProcessorRequest;
053import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.FriendsOfFriendsProcessorResponse;
054import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.IncCounterProcessorRequest;
055import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.IncCounterProcessorResponse;
056import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.RowSwapProcessorRequest;
057import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.RowSwapProcessorResponse;
058import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.TimeoutProcessorRequest;
059import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.TimeoutProcessorResponse;
060import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
061import org.apache.hadoop.hbase.ipc.RpcScheduler;
062import org.apache.hadoop.hbase.protobuf.generated.RowProcessorProtos.ProcessRequest;
063import org.apache.hadoop.hbase.protobuf.generated.RowProcessorProtos.ProcessResponse;
064import org.apache.hadoop.hbase.protobuf.generated.RowProcessorProtos.RowProcessorService;
065import org.apache.hadoop.hbase.regionserver.BaseRowProcessor;
066import org.apache.hadoop.hbase.regionserver.HRegion;
067import org.apache.hadoop.hbase.regionserver.InternalScanner;
068import org.apache.hadoop.hbase.testclassification.CoprocessorTests;
069import org.apache.hadoop.hbase.testclassification.MediumTests;
070import org.apache.hadoop.hbase.util.ByteStringer;
071import org.apache.hadoop.hbase.util.Bytes;
072import org.apache.hadoop.hbase.wal.WALEdit;
073import org.junit.AfterClass;
074import org.junit.BeforeClass;
075import org.junit.ClassRule;
076import org.junit.Test;
077import org.junit.experimental.categories.Category;
078import org.slf4j.Logger;
079import org.slf4j.LoggerFactory;
080
081/**
082 * Verifies ProcessEndpoint works.
083 * The tested RowProcessor performs two scans and a read-modify-write.
084 */
085@Category({CoprocessorTests.class, MediumTests.class})
086public class TestRowProcessorEndpoint {
087
088  @ClassRule
089  public static final HBaseClassTestRule CLASS_RULE =
090      HBaseClassTestRule.forClass(TestRowProcessorEndpoint.class);
091
092  private static final Logger LOG = LoggerFactory.getLogger(TestRowProcessorEndpoint.class);
093
094  private static final TableName TABLE = TableName.valueOf("testtable");
095  private final static byte[] ROW = Bytes.toBytes("testrow");
096  private final static byte[] ROW2 = Bytes.toBytes("testrow2");
097  private final static byte[] FAM = Bytes.toBytes("friendlist");
098
099  // Column names
100  private final static byte[] A = Bytes.toBytes("a");
101  private final static byte[] B = Bytes.toBytes("b");
102  private final static byte[] C = Bytes.toBytes("c");
103  private final static byte[] D = Bytes.toBytes("d");
104  private final static byte[] E = Bytes.toBytes("e");
105  private final static byte[] F = Bytes.toBytes("f");
106  private final static byte[] G = Bytes.toBytes("g");
107  private final static byte[] COUNTER = Bytes.toBytes("counter");
108  private final static AtomicLong myTimer = new AtomicLong(0);
109  private final AtomicInteger failures = new AtomicInteger(0);
110
111  private static HBaseTestingUtility util = new HBaseTestingUtility();
112  private static volatile int expectedCounter = 0;
113  private static int rowSize, row2Size;
114
115  private volatile static Table table = null;
116  private volatile static boolean swapped = false;
117  private volatile CountDownLatch startSignal;
118  private volatile CountDownLatch doneSignal;
119
120  @BeforeClass
121  public static void setupBeforeClass() throws Exception {
122    Configuration conf = util.getConfiguration();
123    conf.setStrings(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
124        RowProcessorEndpoint.class.getName());
125    conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2);
126    conf.setLong("hbase.hregion.row.processor.timeout", 1000L);
127    conf.setLong(RpcScheduler.IPC_SERVER_MAX_CALLQUEUE_LENGTH, 2048);
128    util.startMiniCluster();
129  }
130
131  @AfterClass
132  public static void tearDownAfterClass() throws Exception {
133    util.shutdownMiniCluster();
134  }
135
136  public void prepareTestData() throws Exception {
137    try {
138      util.getAdmin().disableTable(TABLE);
139      util.getAdmin().deleteTable(TABLE);
140    } catch (Exception e) {
141      // ignore table not found
142    }
143    table = util.createTable(TABLE, FAM);
144    {
145      Put put = new Put(ROW);
146      put.addColumn(FAM, A, Bytes.add(B, C));    // B, C are friends of A
147      put.addColumn(FAM, B, Bytes.add(D, E, F)); // D, E, F are friends of B
148      put.addColumn(FAM, C, G);                  // G is a friend of C
149      table.put(put);
150      rowSize = put.size();
151    }
152    Put put = new Put(ROW2);
153    put.addColumn(FAM, D, E);
154    put.addColumn(FAM, F, G);
155    table.put(put);
156    row2Size = put.size();
157  }
158
159  @Test
160  public void testDoubleScan() throws Throwable {
161    prepareTestData();
162
163    CoprocessorRpcChannel channel = table.coprocessorService(ROW);
164    RowProcessorEndpoint.FriendsOfFriendsProcessor processor =
165        new RowProcessorEndpoint.FriendsOfFriendsProcessor(ROW, A);
166    RowProcessorService.BlockingInterface service =
167        RowProcessorService.newBlockingStub(channel);
168    ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
169    ProcessResponse protoResult = service.process(null, request);
170    FriendsOfFriendsProcessorResponse response =
171        FriendsOfFriendsProcessorResponse.parseFrom(protoResult.getRowProcessorResult());
172    Set<String> result = new HashSet<>();
173    result.addAll(response.getResultList());
174    Set<String> expected = new HashSet<>(Arrays.asList(new String[]{"d", "e", "f", "g"}));
175    Get get = new Get(ROW);
176    LOG.debug("row keyvalues:" + stringifyKvs(table.get(get).listCells()));
177    assertEquals(expected, result);
178  }
179
180  @Test
181  public void testReadModifyWrite() throws Throwable {
182    prepareTestData();
183    failures.set(0);
184    int numThreads = 100;
185    concurrentExec(new IncrementRunner(), numThreads);
186    Get get = new Get(ROW);
187    LOG.debug("row keyvalues:" + stringifyKvs(table.get(get).listCells()));
188    int finalCounter = incrementCounter(table);
189    int failureNumber = failures.get();
190    if (failureNumber > 0) {
191      LOG.debug("We failed " + failureNumber + " times during test");
192    }
193    assertEquals(numThreads + 1 - failureNumber, finalCounter);
194  }
195
196  class IncrementRunner implements Runnable {
197    @Override
198    public void run() {
199      try {
200        incrementCounter(table);
201      } catch (Throwable e) {
202        failures.incrementAndGet();
203        e.printStackTrace();
204      }
205    }
206  }
207
208  private int incrementCounter(Table table) throws Throwable {
209    CoprocessorRpcChannel channel = table.coprocessorService(ROW);
210    RowProcessorEndpoint.IncrementCounterProcessor processor =
211        new RowProcessorEndpoint.IncrementCounterProcessor(ROW);
212    RowProcessorService.BlockingInterface service =
213        RowProcessorService.newBlockingStub(channel);
214    ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
215    ProcessResponse protoResult = service.process(null, request);
216    IncCounterProcessorResponse response = IncCounterProcessorResponse
217        .parseFrom(protoResult.getRowProcessorResult());
218    Integer result = response.getResponse();
219    return result;
220  }
221
222  private void concurrentExec(
223      final Runnable task, final int numThreads) throws Throwable {
224    startSignal = new CountDownLatch(numThreads);
225    doneSignal = new CountDownLatch(numThreads);
226    for (int i = 0; i < numThreads; ++i) {
227      new Thread(new Runnable() {
228        @Override
229        public void run() {
230          try {
231            startSignal.countDown();
232            startSignal.await();
233            task.run();
234          } catch (Throwable e) {
235            failures.incrementAndGet();
236            e.printStackTrace();
237          }
238          doneSignal.countDown();
239        }
240      }).start();
241    }
242    doneSignal.await();
243  }
244
245  @Test
246  public void testMultipleRows() throws Throwable {
247    prepareTestData();
248    failures.set(0);
249    int numThreads = 100;
250    concurrentExec(new SwapRowsRunner(), numThreads);
251    LOG.debug("row keyvalues:" +
252              stringifyKvs(table.get(new Get(ROW)).listCells()));
253    LOG.debug("row2 keyvalues:" +
254              stringifyKvs(table.get(new Get(ROW2)).listCells()));
255    int failureNumber = failures.get();
256    if (failureNumber > 0) {
257      LOG.debug("We failed " + failureNumber + " times during test");
258    }
259    if (!swapped) {
260      assertEquals(rowSize, table.get(new Get(ROW)).listCells().size());
261      assertEquals(row2Size, table.get(new Get(ROW2)).listCells().size());
262    } else {
263      assertEquals(rowSize, table.get(new Get(ROW2)).listCells().size());
264      assertEquals(row2Size, table.get(new Get(ROW)).listCells().size());
265    }
266  }
267
268  class SwapRowsRunner implements Runnable {
269    @Override
270    public void run() {
271      try {
272        swapRows(table);
273      } catch (Throwable e) {
274        failures.incrementAndGet();
275        e.printStackTrace();
276      }
277    }
278  }
279
280  private void swapRows(Table table) throws Throwable {
281    CoprocessorRpcChannel channel = table.coprocessorService(ROW);
282    RowProcessorEndpoint.RowSwapProcessor processor =
283        new RowProcessorEndpoint.RowSwapProcessor(ROW, ROW2);
284    RowProcessorService.BlockingInterface service =
285        RowProcessorService.newBlockingStub(channel);
286    ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
287    service.process(null, request);
288  }
289
290  @Test
291  public void testTimeout() throws Throwable {
292    prepareTestData();
293    CoprocessorRpcChannel channel = table.coprocessorService(ROW);
294    RowProcessorEndpoint.TimeoutProcessor processor =
295        new RowProcessorEndpoint.TimeoutProcessor(ROW);
296    RowProcessorService.BlockingInterface service =
297        RowProcessorService.newBlockingStub(channel);
298    ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
299    boolean exceptionCaught = false;
300    try {
301      service.process(null, request);
302    } catch (Exception e) {
303      exceptionCaught = true;
304    }
305    assertTrue(exceptionCaught);
306  }
307
308  /**
309   * This class defines two RowProcessors:
310   * IncrementCounterProcessor and FriendsOfFriendsProcessor.
311   *
312   * We define the RowProcessors as the inner class of the endpoint.
313   * So they can be loaded with the endpoint on the coprocessor.
314   */
315  public static class RowProcessorEndpoint<S extends Message,T extends Message>
316  extends BaseRowProcessorEndpoint<S,T> {
317    public static class IncrementCounterProcessor extends
318        BaseRowProcessor<IncrementCounterProcessorTestProtos.IncCounterProcessorRequest,
319        IncrementCounterProcessorTestProtos.IncCounterProcessorResponse> {
320      int counter = 0;
321      byte[] row = new byte[0];
322
323      /**
324       * Empty constructor for Writable
325       */
326      IncrementCounterProcessor() {
327      }
328
329      IncrementCounterProcessor(byte[] row) {
330        this.row = row;
331      }
332
333      @Override
334      public Collection<byte[]> getRowsToLock() {
335        return Collections.singleton(row);
336      }
337
338      @Override
339      public IncCounterProcessorResponse getResult() {
340        IncCounterProcessorResponse.Builder i = IncCounterProcessorResponse.newBuilder();
341        i.setResponse(counter);
342        return i.build();
343      }
344
345      @Override
346      public boolean readOnly() {
347        return false;
348      }
349
350      @Override
351      public void process(long now, HRegion region,
352          List<Mutation> mutations, WALEdit walEdit) throws IOException {
353        // Scan current counter
354        List<Cell> kvs = new ArrayList<>();
355        Scan scan = new Scan(row, row);
356        scan.addColumn(FAM, COUNTER);
357        doScan(region, scan, kvs);
358        counter = kvs.isEmpty() ? 0 :
359          Bytes.toInt(CellUtil.cloneValue(kvs.iterator().next()));
360
361        // Assert counter value
362        assertEquals(expectedCounter, counter);
363
364        // Increment counter and send it to both memstore and wal edit
365        counter += 1;
366        expectedCounter += 1;
367
368
369        Put p = new Put(row);
370        KeyValue kv =
371            new KeyValue(row, FAM, COUNTER, now, Bytes.toBytes(counter));
372        p.add(kv);
373        mutations.add(p);
374        walEdit.add(kv);
375
376        // We can also inject some meta data to the walEdit
377        KeyValue metaKv = new KeyValue(
378            row, WALEdit.METAFAMILY,
379            Bytes.toBytes("I just increment counter"),
380            Bytes.toBytes(counter));
381        walEdit.add(metaKv);
382      }
383
384      @Override
385      public IncCounterProcessorRequest getRequestData() throws IOException {
386        IncCounterProcessorRequest.Builder builder = IncCounterProcessorRequest.newBuilder();
387        builder.setCounter(counter);
388        builder.setRow(ByteStringer.wrap(row));
389        return builder.build();
390      }
391
392      @Override
393      public void initialize(IncCounterProcessorRequest msg) {
394        this.row = msg.getRow().toByteArray();
395        this.counter = msg.getCounter();
396      }
397    }
398
399    public static class FriendsOfFriendsProcessor extends
400        BaseRowProcessor<FriendsOfFriendsProcessorRequest, FriendsOfFriendsProcessorResponse> {
401      byte[] row = null;
402      byte[] person = null;
403      final Set<String> result = new HashSet<>();
404
405      /**
406       * Empty constructor for Writable
407       */
408      FriendsOfFriendsProcessor() {
409      }
410
411      FriendsOfFriendsProcessor(byte[] row, byte[] person) {
412        this.row = row;
413        this.person = person;
414      }
415
416      @Override
417      public Collection<byte[]> getRowsToLock() {
418        return Collections.singleton(row);
419      }
420
421      @Override
422      public FriendsOfFriendsProcessorResponse getResult() {
423        FriendsOfFriendsProcessorResponse.Builder builder =
424            FriendsOfFriendsProcessorResponse.newBuilder();
425        builder.addAllResult(result);
426        return builder.build();
427      }
428
429      @Override
430      public boolean readOnly() {
431        return true;
432      }
433
434      @Override
435      public void process(long now, HRegion region,
436          List<Mutation> mutations, WALEdit walEdit) throws IOException {
437        List<Cell> kvs = new ArrayList<>();
438        { // First scan to get friends of the person
439          Scan scan = new Scan(row, row);
440          scan.addColumn(FAM, person);
441          doScan(region, scan, kvs);
442        }
443
444        // Second scan to get friends of friends
445        Scan scan = new Scan(row, row);
446        for (Cell kv : kvs) {
447          byte[] friends = CellUtil.cloneValue(kv);
448          for (byte f : friends) {
449            scan.addColumn(FAM, new byte[]{f});
450          }
451        }
452        doScan(region, scan, kvs);
453
454        // Collect result
455        result.clear();
456        for (Cell kv : kvs) {
457          for (byte b : CellUtil.cloneValue(kv)) {
458            result.add((char)b + "");
459          }
460        }
461      }
462
463      @Override
464      public FriendsOfFriendsProcessorRequest getRequestData() throws IOException {
465        FriendsOfFriendsProcessorRequest.Builder builder =
466            FriendsOfFriendsProcessorRequest.newBuilder();
467        builder.setPerson(ByteStringer.wrap(person));
468        builder.setRow(ByteStringer.wrap(row));
469        builder.addAllResult(result);
470        FriendsOfFriendsProcessorRequest f = builder.build();
471        return f;
472      }
473
474      @Override
475      public void initialize(FriendsOfFriendsProcessorRequest request)
476          throws IOException {
477        this.person = request.getPerson().toByteArray();
478        this.row = request.getRow().toByteArray();
479        result.clear();
480        result.addAll(request.getResultList());
481      }
482    }
483
484    public static class RowSwapProcessor extends
485        BaseRowProcessor<RowSwapProcessorRequest, RowSwapProcessorResponse> {
486      byte[] row1 = new byte[0];
487      byte[] row2 = new byte[0];
488
489      /**
490       * Empty constructor for Writable
491       */
492      RowSwapProcessor() {
493      }
494
495      RowSwapProcessor(byte[] row1, byte[] row2) {
496        this.row1 = row1;
497        this.row2 = row2;
498      }
499
500      @Override
501      public Collection<byte[]> getRowsToLock() {
502        List<byte[]> rows = new ArrayList<>(2);
503        rows.add(row1);
504        rows.add(row2);
505        return rows;
506      }
507
508      @Override
509      public boolean readOnly() {
510        return false;
511      }
512
513      @Override
514      public RowSwapProcessorResponse getResult() {
515        return RowSwapProcessorResponse.getDefaultInstance();
516      }
517
518      @Override
519      public void process(long now, HRegion region,
520          List<Mutation> mutations, WALEdit walEdit) throws IOException {
521
522        // Override the time to avoid race-condition in the unit test caused by
523        // inacurate timer on some machines
524        now = myTimer.getAndIncrement();
525
526        // Scan both rows
527        List<Cell> kvs1 = new ArrayList<>();
528        List<Cell> kvs2 = new ArrayList<>();
529        doScan(region, new Scan(row1, row1), kvs1);
530        doScan(region, new Scan(row2, row2), kvs2);
531
532        // Assert swapped
533        if (swapped) {
534          assertEquals(rowSize, kvs2.size());
535          assertEquals(row2Size, kvs1.size());
536        } else {
537          assertEquals(rowSize, kvs1.size());
538          assertEquals(row2Size, kvs2.size());
539        }
540        swapped = !swapped;
541
542        // Add and delete keyvalues
543        List<List<Cell>> kvs = new ArrayList<>(2);
544        kvs.add(kvs1);
545        kvs.add(kvs2);
546        byte[][] rows = new byte[][]{row1, row2};
547        for (int i = 0; i < kvs.size(); ++i) {
548          for (Cell kv : kvs.get(i)) {
549            // Delete from the current row and add to the other row
550            Delete d = new Delete(rows[i]);
551            KeyValue kvDelete =
552                new KeyValue(rows[i], CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv),
553                    kv.getTimestamp(), KeyValue.Type.Delete);
554            d.add(kvDelete);
555            Put p = new Put(rows[1 - i]);
556            KeyValue kvAdd =
557                new KeyValue(rows[1 - i], CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv),
558                    now, CellUtil.cloneValue(kv));
559            p.add(kvAdd);
560            mutations.add(d);
561            walEdit.add(kvDelete);
562            mutations.add(p);
563            walEdit.add(kvAdd);
564          }
565        }
566      }
567
568      @Override
569      public String getName() {
570        return "swap";
571      }
572
573      @Override
574      public RowSwapProcessorRequest getRequestData() throws IOException {
575        RowSwapProcessorRequest.Builder builder = RowSwapProcessorRequest.newBuilder();
576        builder.setRow1(ByteStringer.wrap(row1));
577        builder.setRow2(ByteStringer.wrap(row2));
578        return builder.build();
579      }
580
581      @Override
582      public void initialize(RowSwapProcessorRequest msg) {
583        this.row1 = msg.getRow1().toByteArray();
584        this.row2 = msg.getRow2().toByteArray();
585      }
586    }
587
588    public static class TimeoutProcessor extends
589        BaseRowProcessor<TimeoutProcessorRequest, TimeoutProcessorResponse> {
590
591      byte[] row = new byte[0];
592
593      /**
594       * Empty constructor for Writable
595       */
596      public TimeoutProcessor() {
597      }
598
599      public TimeoutProcessor(byte[] row) {
600        this.row = row;
601      }
602
603      public Collection<byte[]> getRowsToLock() {
604        return Collections.singleton(row);
605      }
606
607      @Override
608      public TimeoutProcessorResponse getResult() {
609        return TimeoutProcessorResponse.getDefaultInstance();
610      }
611
612      @Override
613      public void process(long now, HRegion region,
614          List<Mutation> mutations, WALEdit walEdit) throws IOException {
615        try {
616          // Sleep for a long time so it timeout
617          Thread.sleep(100 * 1000L);
618        } catch (Exception e) {
619          throw new IOException(e);
620        }
621      }
622
623      @Override
624      public boolean readOnly() {
625        return true;
626      }
627
628      @Override
629      public String getName() {
630        return "timeout";
631      }
632
633      @Override
634      public TimeoutProcessorRequest getRequestData() throws IOException {
635        TimeoutProcessorRequest.Builder builder = TimeoutProcessorRequest.newBuilder();
636        builder.setRow(ByteStringer.wrap(row));
637        return builder.build();
638      }
639
640      @Override
641      public void initialize(TimeoutProcessorRequest msg) throws IOException {
642        this.row = msg.getRow().toByteArray();
643      }
644    }
645
646    public static void doScan(
647        HRegion region, Scan scan, List<Cell> result) throws IOException {
648      InternalScanner scanner = null;
649      try {
650        scan.setIsolationLevel(IsolationLevel.READ_UNCOMMITTED);
651        scanner = region.getScanner(scan);
652        result.clear();
653        scanner.next(result);
654      } finally {
655        if (scanner != null) scanner.close();
656      }
657    }
658  }
659
660  static String stringifyKvs(Collection<Cell> kvs) {
661    StringBuilder out = new StringBuilder();
662    out.append("[");
663    if (kvs != null) {
664      for (Cell kv : kvs) {
665        byte[] col = CellUtil.cloneQualifier(kv);
666        byte[] val = CellUtil.cloneValue(kv);
667        if (Bytes.equals(col, COUNTER)) {
668          out.append(Bytes.toStringBinary(col) + ":" +
669                     Bytes.toInt(val) + " ");
670        } else {
671          out.append(Bytes.toStringBinary(col) + ":" +
672                     Bytes.toStringBinary(val) + " ");
673        }
674      }
675    }
676    out.append("]");
677    return out.toString();
678  }
679
680}