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.thrift2;
019
020import static java.nio.ByteBuffer.wrap;
021import static org.apache.hadoop.hbase.thrift.HBaseServiceHandler.CLEANUP_INTERVAL;
022import static org.apache.hadoop.hbase.thrift.HBaseServiceHandler.MAX_IDLETIME;
023import static org.apache.hadoop.hbase.thrift2.ThriftUtilities.deleteFromThrift;
024import static org.apache.hadoop.hbase.thrift2.ThriftUtilities.getFromThrift;
025import static org.apache.hadoop.hbase.thrift2.ThriftUtilities.incrementFromThrift;
026import static org.apache.hadoop.hbase.thrift2.ThriftUtilities.putFromThrift;
027import static org.apache.hadoop.hbase.thrift2.ThriftUtilities.scanFromThrift;
028import static org.junit.Assert.assertArrayEquals;
029import static org.junit.Assert.assertEquals;
030import static org.junit.Assert.assertFalse;
031import static org.junit.Assert.assertNull;
032import static org.junit.Assert.assertTrue;
033import static org.junit.Assert.fail;
034
035import java.io.IOException;
036import java.io.InterruptedIOException;
037import java.net.InetAddress;
038import java.nio.ByteBuffer;
039import java.util.ArrayList;
040import java.util.Arrays;
041import java.util.Collection;
042import java.util.Collections;
043import java.util.Comparator;
044import java.util.HashMap;
045import java.util.HashSet;
046import java.util.List;
047import java.util.Map;
048import java.util.Optional;
049import java.util.Set;
050import java.util.concurrent.TimeUnit;
051import org.apache.hadoop.conf.Configuration;
052import org.apache.hadoop.hbase.Cell;
053import org.apache.hadoop.hbase.CompatibilityFactory;
054import org.apache.hadoop.hbase.CoprocessorEnvironment;
055import org.apache.hadoop.hbase.HBaseClassTestRule;
056import org.apache.hadoop.hbase.HBaseTestingUtil;
057import org.apache.hadoop.hbase.ServerName;
058import org.apache.hadoop.hbase.TableName;
059import org.apache.hadoop.hbase.client.Admin;
060import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
061import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
062import org.apache.hadoop.hbase.client.Consistency;
063import org.apache.hadoop.hbase.client.Delete;
064import org.apache.hadoop.hbase.client.Durability;
065import org.apache.hadoop.hbase.client.Get;
066import org.apache.hadoop.hbase.client.Increment;
067import org.apache.hadoop.hbase.client.LogQueryFilter;
068import org.apache.hadoop.hbase.client.Put;
069import org.apache.hadoop.hbase.client.Scan;
070import org.apache.hadoop.hbase.client.Table;
071import org.apache.hadoop.hbase.client.TableDescriptor;
072import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
073import org.apache.hadoop.hbase.coprocessor.ObserverContext;
074import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
075import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
076import org.apache.hadoop.hbase.coprocessor.RegionObserver;
077import org.apache.hadoop.hbase.filter.ParseFilter;
078import org.apache.hadoop.hbase.security.UserProvider;
079import org.apache.hadoop.hbase.security.access.AccessControlClient;
080import org.apache.hadoop.hbase.security.access.Permission;
081import org.apache.hadoop.hbase.security.access.UserPermission;
082import org.apache.hadoop.hbase.test.MetricsAssertHelper;
083import org.apache.hadoop.hbase.testclassification.ClientTests;
084import org.apache.hadoop.hbase.testclassification.MediumTests;
085import org.apache.hadoop.hbase.thrift.ErrorThrowingGetObserver;
086import org.apache.hadoop.hbase.thrift.HBaseThriftTestingUtility;
087import org.apache.hadoop.hbase.thrift.HbaseHandlerMetricsProxy;
088import org.apache.hadoop.hbase.thrift.ThriftMetrics;
089import org.apache.hadoop.hbase.thrift.ThriftMetrics.ThriftServerType;
090import org.apache.hadoop.hbase.thrift2.generated.TAccessControlEntity;
091import org.apache.hadoop.hbase.thrift2.generated.TAppend;
092import org.apache.hadoop.hbase.thrift2.generated.TColumn;
093import org.apache.hadoop.hbase.thrift2.generated.TColumnFamilyDescriptor;
094import org.apache.hadoop.hbase.thrift2.generated.TColumnIncrement;
095import org.apache.hadoop.hbase.thrift2.generated.TColumnValue;
096import org.apache.hadoop.hbase.thrift2.generated.TCompareOperator;
097import org.apache.hadoop.hbase.thrift2.generated.TConsistency;
098import org.apache.hadoop.hbase.thrift2.generated.TDataBlockEncoding;
099import org.apache.hadoop.hbase.thrift2.generated.TDelete;
100import org.apache.hadoop.hbase.thrift2.generated.TDeleteType;
101import org.apache.hadoop.hbase.thrift2.generated.TDurability;
102import org.apache.hadoop.hbase.thrift2.generated.TFilterByOperator;
103import org.apache.hadoop.hbase.thrift2.generated.TGet;
104import org.apache.hadoop.hbase.thrift2.generated.THBaseService;
105import org.apache.hadoop.hbase.thrift2.generated.TIOError;
106import org.apache.hadoop.hbase.thrift2.generated.TIllegalArgument;
107import org.apache.hadoop.hbase.thrift2.generated.TIncrement;
108import org.apache.hadoop.hbase.thrift2.generated.TLogQueryFilter;
109import org.apache.hadoop.hbase.thrift2.generated.TMutation;
110import org.apache.hadoop.hbase.thrift2.generated.TNamespaceDescriptor;
111import org.apache.hadoop.hbase.thrift2.generated.TOnlineLogRecord;
112import org.apache.hadoop.hbase.thrift2.generated.TPermissionScope;
113import org.apache.hadoop.hbase.thrift2.generated.TPut;
114import org.apache.hadoop.hbase.thrift2.generated.TReadType;
115import org.apache.hadoop.hbase.thrift2.generated.TResult;
116import org.apache.hadoop.hbase.thrift2.generated.TRowMutations;
117import org.apache.hadoop.hbase.thrift2.generated.TScan;
118import org.apache.hadoop.hbase.thrift2.generated.TServerName;
119import org.apache.hadoop.hbase.thrift2.generated.TTableDescriptor;
120import org.apache.hadoop.hbase.thrift2.generated.TTableName;
121import org.apache.hadoop.hbase.thrift2.generated.TThriftServerType;
122import org.apache.hadoop.hbase.thrift2.generated.TTimeRange;
123import org.apache.hadoop.hbase.util.Bytes;
124import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
125import org.apache.thrift.TException;
126import org.apache.thrift.protocol.TBinaryProtocol;
127import org.apache.thrift.protocol.TProtocol;
128import org.apache.thrift.transport.TSocket;
129import org.apache.thrift.transport.TTransport;
130import org.junit.AfterClass;
131import org.junit.Assert;
132import org.junit.Before;
133import org.junit.BeforeClass;
134import org.junit.ClassRule;
135import org.junit.Rule;
136import org.junit.Test;
137import org.junit.experimental.categories.Category;
138import org.junit.rules.TestName;
139import org.slf4j.Logger;
140import org.slf4j.LoggerFactory;
141
142import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
143import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils;
144
145/**
146 * Unit testing for ThriftServer.HBaseServiceHandler, a part of the org.apache.hadoop.hbase.thrift2
147 * package.
148 */
149@Category({ClientTests.class, MediumTests.class})
150public class TestThriftHBaseServiceHandler {
151
152  @ClassRule
153  public static final HBaseClassTestRule CLASS_RULE =
154      HBaseClassTestRule.forClass(TestThriftHBaseServiceHandler.class);
155
156  private static final Logger LOG = LoggerFactory.getLogger(TestThriftHBaseServiceHandler.class);
157  private static final HBaseTestingUtil UTIL = new HBaseTestingUtil();
158
159  // Static names for tables, columns, rows, and values
160  private static byte[] tableAname = Bytes.toBytes("tableA");
161  private static byte[] familyAname = Bytes.toBytes("familyA");
162  private static byte[] familyBname = Bytes.toBytes("familyB");
163  private static byte[] qualifierAname = Bytes.toBytes("qualifierA");
164  private static byte[] qualifierBname = Bytes.toBytes("qualifierB");
165  private static byte[] valueAname = Bytes.toBytes("valueA");
166  private static byte[] valueBname = Bytes.toBytes("valueB");
167  private static ColumnFamilyDescriptor[] families = new ColumnFamilyDescriptor[] {
168    ColumnFamilyDescriptorBuilder.newBuilder(familyAname).setMaxVersions(3).build(),
169    ColumnFamilyDescriptorBuilder.newBuilder(familyBname).setMaxVersions(2).build() };
170
171
172  private static final MetricsAssertHelper metricsHelper =
173      CompatibilityFactory.getInstance(MetricsAssertHelper.class);
174
175  @Rule
176  public TestName name = new TestName();
177
178
179  public void assertTColumnValuesEqual(List<TColumnValue> columnValuesA,
180      List<TColumnValue> columnValuesB) {
181    assertEquals(columnValuesA.size(), columnValuesB.size());
182    Comparator<TColumnValue> comparator = new Comparator<TColumnValue>() {
183      @Override
184      public int compare(TColumnValue o1, TColumnValue o2) {
185        return Bytes.compareTo(Bytes.add(o1.getFamily(), o1.getQualifier()),
186            Bytes.add(o2.getFamily(), o2.getQualifier()));
187      }
188    };
189    Collections.sort(columnValuesA, comparator);
190    Collections.sort(columnValuesB, comparator);
191
192    for (int i = 0; i < columnValuesA.size(); i++) {
193      TColumnValue a = columnValuesA.get(i);
194      TColumnValue b = columnValuesB.get(i);
195      assertTColumnValueEqual(a, b);
196    }
197  }
198
199  public void assertTColumnValueEqual(TColumnValue a, TColumnValue b) {
200    assertArrayEquals(a.getFamily(), b.getFamily());
201    assertArrayEquals(a.getQualifier(), b.getQualifier());
202    assertArrayEquals(a.getValue(), b.getValue());
203  }
204
205  @BeforeClass
206  public static void beforeClass() throws Exception {
207    UTIL.getConfiguration().set("hbase.client.retries.number", "3");
208    UTIL.getConfiguration().setBoolean("hbase.regionserver.slowlog.buffer.enabled", true);
209
210    UTIL.getConfiguration().set("hbase.client.retries.number", "3");
211    UTIL.getConfiguration().setBoolean("hbase.security.authorization", true);
212    UTIL.getConfiguration().set("hbase.coprocessor.master.classes",
213      "org.apache.hadoop.hbase.security.access.AccessController");
214    UTIL.getConfiguration().set("hbase.coprocessor.region.classes",
215      "org.apache.hadoop.hbase.security.access.AccessController");
216    UTIL.getConfiguration().set("hbase.coprocessor.regionserver.classes",
217      "org.apache.hadoop.hbase.security.access.AccessController");
218
219    // as we opened access control, we need to start as a superuser. Otherwise, we will not have
220    // sufficient permission to do operations.
221    UTIL.getConfiguration().set("hbase.superuser", System.getProperty("user.name"));
222
223    UTIL.startMiniCluster();
224    TableDescriptor tableDescriptor = TableDescriptorBuilder
225      .newBuilder(TableName.valueOf(tableAname)).setColumnFamilies(Arrays.asList(families)).build();
226    try (Admin admin = UTIL.getAdmin()) {
227      admin.createTable(tableDescriptor);
228    }
229  }
230
231  @AfterClass
232  public static void afterClass() throws Exception {
233    UTIL.shutdownMiniCluster();
234  }
235
236  @Before
237  public void setup() throws Exception {
238
239  }
240
241  private ThriftHBaseServiceHandler createHandler() throws TException {
242    try {
243      Configuration conf = UTIL.getConfiguration();
244      return new ThriftHBaseServiceHandler(conf, UserProvider.instantiate(conf));
245    } catch (IOException ie) {
246      throw new TException(ie);
247    }
248  }
249
250  @Test
251  public void testExists() throws TIOError, TException {
252    ThriftHBaseServiceHandler handler = createHandler();
253    byte[] rowName = Bytes.toBytes("testExists");
254    ByteBuffer table = wrap(tableAname);
255
256    TGet get = new TGet(wrap(rowName));
257    assertFalse(handler.exists(table, get));
258
259    List<TColumnValue> columnValues = new ArrayList<>(2);
260    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
261    columnValues.add(new TColumnValue(wrap(familyBname), wrap(qualifierBname), wrap(valueBname)));
262    TPut put = new TPut(wrap(rowName), columnValues);
263    put.setColumnValues(columnValues);
264
265    handler.put(table, put);
266
267    assertTrue(handler.exists(table, get));
268  }
269
270  @Test
271  public void testExistsAll() throws TIOError, TException {
272    ThriftHBaseServiceHandler handler = createHandler();
273    byte[] rowName1 = Bytes.toBytes("testExistsAll1");
274    byte[] rowName2 = Bytes.toBytes("testExistsAll2");
275    ByteBuffer table = wrap(tableAname);
276
277    List<TGet> gets = new ArrayList<>();
278    gets.add(new TGet(wrap(rowName2)));
279    gets.add(new TGet(wrap(rowName2)));
280    List<Boolean> existsResult1 = handler.existsAll(table, gets);
281    assertFalse(existsResult1.get(0));
282    assertFalse(existsResult1.get(1));
283
284    List<TColumnValue> columnValues = new ArrayList<TColumnValue>();
285    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
286    columnValues.add(new TColumnValue(wrap(familyBname), wrap(qualifierBname), wrap(valueBname)));
287    List<TPut> puts = new ArrayList<TPut>();
288    puts.add(new TPut(wrap(rowName1), columnValues));
289    puts.add(new TPut(wrap(rowName2), columnValues));
290
291    handler.putMultiple(table, puts);
292    List<Boolean> existsResult2 = handler.existsAll(table, gets);
293
294    assertTrue(existsResult2.get(0));
295    assertTrue(existsResult2.get(1));
296  }
297
298  @Test
299  public void testPutGet() throws Exception {
300    ThriftHBaseServiceHandler handler = createHandler();
301    byte[] rowName = Bytes.toBytes("testPutGet");
302    ByteBuffer table = wrap(tableAname);
303
304    List<TColumnValue> columnValues = new ArrayList<>(2);
305    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
306    columnValues.add(new TColumnValue(wrap(familyBname), wrap(qualifierBname), wrap(valueBname)));
307    TPut put = new TPut(wrap(rowName), columnValues);
308
309    put.setColumnValues(columnValues);
310
311    handler.put(table, put);
312
313    TGet get = new TGet(wrap(rowName));
314
315    TResult result = handler.get(table, get);
316    assertArrayEquals(rowName, result.getRow());
317    List<TColumnValue> returnedColumnValues = result.getColumnValues();
318    assertTColumnValuesEqual(columnValues, returnedColumnValues);
319  }
320
321  @Test
322  public void testPutGetMultiple() throws Exception {
323    ThriftHBaseServiceHandler handler = createHandler();
324    ByteBuffer table = wrap(tableAname);
325    byte[] rowName1 = Bytes.toBytes("testPutGetMultiple1");
326    byte[] rowName2 = Bytes.toBytes("testPutGetMultiple2");
327
328    List<TColumnValue> columnValues = new ArrayList<>(2);
329    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
330    columnValues.add(new TColumnValue(wrap(familyBname), wrap(qualifierBname), wrap(valueBname)));
331    List<TPut> puts = new ArrayList<>(2);
332    puts.add(new TPut(wrap(rowName1), columnValues));
333    puts.add(new TPut(wrap(rowName2), columnValues));
334
335    handler.putMultiple(table, puts);
336
337    List<TGet> gets = new ArrayList<>(2);
338    gets.add(new TGet(wrap(rowName1)));
339    gets.add(new TGet(wrap(rowName2)));
340
341    List<TResult> results = handler.getMultiple(table, gets);
342    assertEquals(2, results.size());
343
344    assertArrayEquals(rowName1, results.get(0).getRow());
345    assertTColumnValuesEqual(columnValues, results.get(0).getColumnValues());
346
347    assertArrayEquals(rowName2, results.get(1).getRow());
348    assertTColumnValuesEqual(columnValues, results.get(1).getColumnValues());
349  }
350
351  @Test
352  public void testDeleteMultiple() throws Exception {
353    ThriftHBaseServiceHandler handler = createHandler();
354    ByteBuffer table = wrap(tableAname);
355    byte[] rowName1 = Bytes.toBytes("testDeleteMultiple1");
356    byte[] rowName2 = Bytes.toBytes("testDeleteMultiple2");
357
358    List<TColumnValue> columnValues = new ArrayList<>(2);
359    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
360    columnValues.add(new TColumnValue(wrap(familyBname), wrap(qualifierBname), wrap(valueBname)));
361    List<TPut> puts = new ArrayList<>(2);
362    puts.add(new TPut(wrap(rowName1), columnValues));
363    puts.add(new TPut(wrap(rowName2), columnValues));
364
365    handler.putMultiple(table, puts);
366
367    List<TDelete> deletes = new ArrayList<>(2);
368    deletes.add(new TDelete(wrap(rowName1)));
369    deletes.add(new TDelete(wrap(rowName2)));
370
371    List<TDelete> deleteResults = handler.deleteMultiple(table, deletes);
372    // 0 means they were all successfully applies
373    assertEquals(0, deleteResults.size());
374
375    assertFalse(handler.exists(table, new TGet(wrap(rowName1))));
376    assertFalse(handler.exists(table, new TGet(wrap(rowName2))));
377  }
378
379  @Test
380  public void testDelete() throws Exception {
381    ThriftHBaseServiceHandler handler = createHandler();
382    byte[] rowName = Bytes.toBytes("testDelete");
383    ByteBuffer table = wrap(tableAname);
384
385    List<TColumnValue> columnValues = new ArrayList<>(2);
386    TColumnValue columnValueA = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
387      wrap(valueAname));
388    TColumnValue columnValueB = new TColumnValue(wrap(familyBname), wrap(qualifierBname),
389      wrap(valueBname));
390    columnValues.add(columnValueA);
391    columnValues.add(columnValueB);
392    TPut put = new TPut(wrap(rowName), columnValues);
393
394    put.setColumnValues(columnValues);
395
396    handler.put(table, put);
397
398    TDelete delete = new TDelete(wrap(rowName));
399    List<TColumn> deleteColumns = new ArrayList<>(1);
400    TColumn deleteColumn = new TColumn(wrap(familyAname));
401    deleteColumn.setQualifier(qualifierAname);
402    deleteColumns.add(deleteColumn);
403    delete.setColumns(deleteColumns);
404
405    handler.deleteSingle(table, delete);
406
407    TGet get = new TGet(wrap(rowName));
408    TResult result = handler.get(table, get);
409    assertArrayEquals(rowName, result.getRow());
410    List<TColumnValue> returnedColumnValues = result.getColumnValues();
411    List<TColumnValue> expectedColumnValues = new ArrayList<>(1);
412    expectedColumnValues.add(columnValueB);
413    assertTColumnValuesEqual(expectedColumnValues, returnedColumnValues);
414  }
415
416  @Test
417  public void testDeleteAllTimestamps() throws Exception {
418    ThriftHBaseServiceHandler handler = createHandler();
419    byte[] rowName = Bytes.toBytes("testDeleteAllTimestamps");
420    ByteBuffer table = wrap(tableAname);
421
422    List<TColumnValue> columnValues = new ArrayList<>(1);
423    TColumnValue columnValueA = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
424      wrap(valueAname));
425    columnValueA.setTimestamp(EnvironmentEdgeManager.currentTime() - 10);
426    columnValues.add(columnValueA);
427    TPut put = new TPut(wrap(rowName), columnValues);
428
429    put.setColumnValues(columnValues);
430
431    handler.put(table, put);
432    columnValueA.setTimestamp(EnvironmentEdgeManager.currentTime());
433    handler.put(table, put);
434
435    TGet get = new TGet(wrap(rowName));
436    get.setMaxVersions(2);
437    TResult result = handler.get(table, get);
438    assertEquals(2, result.getColumnValuesSize());
439
440    TDelete delete = new TDelete(wrap(rowName));
441    List<TColumn> deleteColumns = new ArrayList<>(1);
442    TColumn deleteColumn = new TColumn(wrap(familyAname));
443    deleteColumn.setQualifier(qualifierAname);
444    deleteColumns.add(deleteColumn);
445    delete.setColumns(deleteColumns);
446    delete.setDeleteType(TDeleteType.DELETE_COLUMNS); // This is the default anyway.
447
448    handler.deleteSingle(table, delete);
449
450    get = new TGet(wrap(rowName));
451    result = handler.get(table, get);
452    assertNull(result.getRow());
453    assertEquals(0, result.getColumnValuesSize());
454  }
455
456  @Test
457  public void testDeleteSingleTimestamp() throws Exception {
458    ThriftHBaseServiceHandler handler = createHandler();
459    byte[] rowName = Bytes.toBytes("testDeleteSingleTimestamp");
460    ByteBuffer table = wrap(tableAname);
461
462    long timestamp1 = EnvironmentEdgeManager.currentTime() - 10;
463    long timestamp2 = EnvironmentEdgeManager.currentTime();
464
465    List<TColumnValue> columnValues = new ArrayList<>(1);
466    TColumnValue columnValueA = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
467      wrap(valueAname));
468    columnValueA.setTimestamp(timestamp1);
469    columnValues.add(columnValueA);
470    TPut put = new TPut(wrap(rowName), columnValues);
471
472    put.setColumnValues(columnValues);
473
474    handler.put(table, put);
475    columnValueA.setTimestamp(timestamp2);
476    handler.put(table, put);
477
478    TGet get = new TGet(wrap(rowName));
479    get.setMaxVersions(2);
480    TResult result = handler.get(table, get);
481    assertEquals(2, result.getColumnValuesSize());
482
483    TDelete delete = new TDelete(wrap(rowName));
484    List<TColumn> deleteColumns = new ArrayList<>(1);
485    TColumn deleteColumn = new TColumn(wrap(familyAname));
486    deleteColumn.setQualifier(qualifierAname);
487    deleteColumns.add(deleteColumn);
488    delete.setColumns(deleteColumns);
489    delete.setDeleteType(TDeleteType.DELETE_COLUMN);
490
491    handler.deleteSingle(table, delete);
492
493    get = new TGet(wrap(rowName));
494    result = handler.get(table, get);
495    assertArrayEquals(rowName, result.getRow());
496    assertEquals(1, result.getColumnValuesSize());
497    // the older timestamp should remain.
498    assertEquals(timestamp1, result.getColumnValues().get(0).getTimestamp());
499  }
500
501  @Test
502  public void testDeleteFamily() throws Exception {
503    ThriftHBaseServiceHandler handler = createHandler();
504    byte[] rowName = Bytes.toBytes("testDeleteFamily");
505    ByteBuffer table = wrap(tableAname);
506
507    long timestamp1 = EnvironmentEdgeManager.currentTime() - 10;
508    long timestamp2 = EnvironmentEdgeManager.currentTime();
509
510    List<TColumnValue> columnValues = new ArrayList<>();
511    TColumnValue columnValueA =
512        new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname));
513    columnValueA.setTimestamp(timestamp1);
514    columnValues.add(columnValueA);
515    TPut put = new TPut(wrap(rowName), columnValues);
516
517    put.setColumnValues(columnValues);
518
519    handler.put(table, put);
520    columnValueA.setTimestamp(timestamp2);
521    handler.put(table, put);
522
523    TGet get = new TGet(wrap(rowName));
524    get.setMaxVersions(2);
525    TResult result = handler.get(table, get);
526    assertEquals(2, result.getColumnValuesSize());
527
528    TDelete delete = new TDelete(wrap(rowName));
529    List<TColumn> deleteColumns = new ArrayList<>();
530    TColumn deleteColumn = new TColumn(wrap(familyAname));
531    deleteColumns.add(deleteColumn);
532    delete.setColumns(deleteColumns);
533    delete.setDeleteType(TDeleteType.DELETE_FAMILY);
534
535    handler.deleteSingle(table, delete);
536
537    get = new TGet(wrap(rowName));
538    result = handler.get(table, get);
539    assertArrayEquals(null, result.getRow());
540    assertEquals(0, result.getColumnValuesSize());
541  }
542
543  @Test
544  public void testDeleteFamilyVersion() throws Exception {
545    ThriftHBaseServiceHandler handler = createHandler();
546    byte[] rowName = Bytes.toBytes("testDeleteFamilyVersion");
547    ByteBuffer table = wrap(tableAname);
548
549    long timestamp1 = EnvironmentEdgeManager.currentTime() - 10;
550    long timestamp2 = EnvironmentEdgeManager.currentTime();
551
552    List<TColumnValue> columnValues = new ArrayList<>();
553    TColumnValue columnValueA =
554        new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname));
555    columnValueA.setTimestamp(timestamp1);
556    columnValues.add(columnValueA);
557    TPut put = new TPut(wrap(rowName), columnValues);
558
559    put.setColumnValues(columnValues);
560
561    handler.put(table, put);
562    columnValueA.setTimestamp(timestamp2);
563    handler.put(table, put);
564
565    TGet get = new TGet(wrap(rowName));
566    get.setMaxVersions(2);
567    TResult result = handler.get(table, get);
568    assertEquals(2, result.getColumnValuesSize());
569
570    TDelete delete = new TDelete(wrap(rowName));
571    List<TColumn> deleteColumns = new ArrayList<>();
572    TColumn deleteColumn = new TColumn(wrap(familyAname));
573    deleteColumn.setTimestamp(timestamp1);
574    deleteColumns.add(deleteColumn);
575    delete.setColumns(deleteColumns);
576    delete.setDeleteType(TDeleteType.DELETE_FAMILY_VERSION);
577
578    handler.deleteSingle(table, delete);
579
580    get = new TGet(wrap(rowName));
581    result = handler.get(table, get);
582    assertArrayEquals(rowName, result.getRow());
583    assertEquals(1, result.getColumnValuesSize());
584    assertEquals(timestamp2, result.getColumnValues().get(0).getTimestamp());
585  }
586
587  @Test
588  public void testIncrement() throws Exception {
589    ThriftHBaseServiceHandler handler = createHandler();
590    byte[] rowName = Bytes.toBytes("testIncrement");
591    ByteBuffer table = wrap(tableAname);
592
593    List<TColumnValue> columnValues = new ArrayList<>(1);
594    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname),
595      wrap(Bytes.toBytes(1L))));
596    TPut put = new TPut(wrap(rowName), columnValues);
597    put.setColumnValues(columnValues);
598    handler.put(table, put);
599
600    List<TColumnIncrement> incrementColumns = new ArrayList<>(1);
601    incrementColumns.add(new TColumnIncrement(wrap(familyAname), wrap(qualifierAname)));
602    TIncrement increment = new TIncrement(wrap(rowName), incrementColumns);
603    handler.increment(table, increment);
604
605    TGet get = new TGet(wrap(rowName));
606    TResult result = handler.get(table, get);
607
608    assertArrayEquals(rowName, result.getRow());
609    assertEquals(1, result.getColumnValuesSize());
610    TColumnValue columnValue = result.getColumnValues().get(0);
611    assertArrayEquals(Bytes.toBytes(2L), columnValue.getValue());
612  }
613
614  @Test
615  public void testAppend() throws Exception {
616    ThriftHBaseServiceHandler handler = createHandler();
617    byte[] rowName = Bytes.toBytes("testAppend");
618    ByteBuffer table = wrap(tableAname);
619    byte[] v1 = Bytes.toBytes("42");
620    byte[] v2 = Bytes.toBytes("23");
621    List<TColumnValue> columnValues = new ArrayList<>(1);
622    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(v1)));
623    TPut put = new TPut(wrap(rowName), columnValues);
624    put.setColumnValues(columnValues);
625    handler.put(table, put);
626
627    List<TColumnValue> appendColumns = new ArrayList<>(1);
628    appendColumns.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(v2)));
629    TAppend append = new TAppend(wrap(rowName), appendColumns);
630    handler.append(table, append);
631
632    TGet get = new TGet(wrap(rowName));
633    TResult result = handler.get(table, get);
634
635    assertArrayEquals(rowName, result.getRow());
636    assertEquals(1, result.getColumnValuesSize());
637    TColumnValue columnValue = result.getColumnValues().get(0);
638    assertArrayEquals(Bytes.add(v1, v2), columnValue.getValue());
639  }
640
641  /**
642   * check that checkAndPut fails if the cell does not exist, then put in the cell, then check
643   * that the checkAndPut succeeds.
644   */
645  @Test
646  public void testCheckAndPut() throws Exception {
647    ThriftHBaseServiceHandler handler = createHandler();
648    byte[] rowName = Bytes.toBytes("testCheckAndPut");
649    ByteBuffer table = wrap(tableAname);
650
651    List<TColumnValue> columnValuesA = new ArrayList<>(1);
652    TColumnValue columnValueA = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
653      wrap(valueAname));
654    columnValuesA.add(columnValueA);
655    TPut putA = new TPut(wrap(rowName), columnValuesA);
656    putA.setColumnValues(columnValuesA);
657
658    List<TColumnValue> columnValuesB = new ArrayList<>(1);
659    TColumnValue columnValueB = new TColumnValue(wrap(familyBname), wrap(qualifierBname),
660      wrap(valueBname));
661    columnValuesB.add(columnValueB);
662    TPut putB = new TPut(wrap(rowName), columnValuesB);
663    putB.setColumnValues(columnValuesB);
664
665    assertFalse(handler.checkAndPut(table, wrap(rowName), wrap(familyAname),
666      wrap(qualifierAname), wrap(valueAname), putB));
667
668    TGet get = new TGet(wrap(rowName));
669    TResult result = handler.get(table, get);
670    assertEquals(0, result.getColumnValuesSize());
671
672    handler.put(table, putA);
673
674    assertTrue(handler.checkAndPut(table, wrap(rowName), wrap(familyAname),
675      wrap(qualifierAname), wrap(valueAname), putB));
676
677    result = handler.get(table, get);
678    assertArrayEquals(rowName, result.getRow());
679    List<TColumnValue> returnedColumnValues = result.getColumnValues();
680    List<TColumnValue> expectedColumnValues = new ArrayList<>(2);
681    expectedColumnValues.add(columnValueA);
682    expectedColumnValues.add(columnValueB);
683    assertTColumnValuesEqual(expectedColumnValues, returnedColumnValues);
684  }
685
686  /**
687   * check that checkAndDelete fails if the cell does not exist, then put in the cell, then
688   * check that the checkAndDelete succeeds.
689   */
690  @Test
691  public void testCheckAndDelete() throws Exception {
692    ThriftHBaseServiceHandler handler = createHandler();
693    byte[] rowName = Bytes.toBytes("testCheckAndDelete");
694    ByteBuffer table = wrap(tableAname);
695
696    List<TColumnValue> columnValuesA = new ArrayList<>(1);
697    TColumnValue columnValueA = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
698      wrap(valueAname));
699    columnValuesA.add(columnValueA);
700    TPut putA = new TPut(wrap(rowName), columnValuesA);
701    putA.setColumnValues(columnValuesA);
702
703    List<TColumnValue> columnValuesB = new ArrayList<>(1);
704    TColumnValue columnValueB = new TColumnValue(wrap(familyBname), wrap(qualifierBname),
705      wrap(valueBname));
706    columnValuesB.add(columnValueB);
707    TPut putB = new TPut(wrap(rowName), columnValuesB);
708    putB.setColumnValues(columnValuesB);
709
710    // put putB so that we know whether the row has been deleted or not
711    handler.put(table, putB);
712
713    TDelete delete = new TDelete(wrap(rowName));
714
715    assertFalse(handler.checkAndDelete(table, wrap(rowName), wrap(familyAname),
716        wrap(qualifierAname), wrap(valueAname), delete));
717
718    TGet get = new TGet(wrap(rowName));
719    TResult result = handler.get(table, get);
720    assertArrayEquals(rowName, result.getRow());
721    assertTColumnValuesEqual(columnValuesB, result.getColumnValues());
722
723    handler.put(table, putA);
724
725    assertTrue(handler.checkAndDelete(table, wrap(rowName), wrap(familyAname),
726      wrap(qualifierAname), wrap(valueAname), delete));
727
728    result = handler.get(table, get);
729    assertFalse(result.isSetRow());
730    assertEquals(0, result.getColumnValuesSize());
731  }
732
733  @Test
734  public void testScan() throws Exception {
735    ThriftHBaseServiceHandler handler = createHandler();
736    ByteBuffer table = wrap(tableAname);
737
738    // insert data
739    TColumnValue columnValue = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
740      wrap(valueAname));
741    List<TColumnValue> columnValues = new ArrayList<>(1);
742    columnValues.add(columnValue);
743    for (int i = 0; i < 10; i++) {
744      TPut put = new TPut(wrap(Bytes.toBytes("testScan" + i)), columnValues);
745      handler.put(table, put);
746    }
747
748    // create scan instance
749    TScan scan = new TScan();
750    List<TColumn> columns = new ArrayList<>(1);
751    TColumn column = new TColumn();
752    column.setFamily(familyAname);
753    column.setQualifier(qualifierAname);
754    columns.add(column);
755    scan.setColumns(columns);
756    scan.setStartRow(Bytes.toBytes("testScan"));
757    scan.setStopRow(Bytes.toBytes("testScan\uffff"));
758
759    // get scanner and rows
760    int scanId = handler.openScanner(table, scan);
761    List<TResult> results = handler.getScannerRows(scanId, 10);
762    assertEquals(10, results.size());
763    for (int i = 0; i < 10; i++) {
764      // check if the rows are returned and in order
765      assertArrayEquals(Bytes.toBytes("testScan" + i), results.get(i).getRow());
766    }
767
768    // check that we are at the end of the scan
769    results = handler.getScannerRows(scanId, 10);
770    assertEquals(0, results.size());
771
772    // close scanner and check that it was indeed closed
773    handler.closeScanner(scanId);
774    try {
775      handler.getScannerRows(scanId, 10);
776      fail("Scanner id should be invalid");
777    } catch (TIllegalArgument e) {
778    }
779  }
780
781  /**
782   * Tests keeping a HBase scanner alive for long periods of time. Each call to getScannerRow()
783   * should reset the ConnectionCache timeout for the scanner's connection.
784   */
785  @org.junit.Ignore @Test // Flakey. Diasabled by HBASE-24079. Renable with Fails with HBASE-24083.
786  //  Caused by: java.util.concurrent.RejectedExecutionException:
787  //  Task org.apache.hadoop.hbase.client.ResultBoundedCompletionService$QueueingFuture@e385431
788  //  rejected from java.util.concurrent.ThreadPoolExecutor@   52b027d[Terminated, pool size = 0,
789  //  active threads = 0, queued tasks = 0, completed tasks = 1]
790  //  at org.apache.hadoop.hbase.thrift2.TestThriftHBaseServiceHandler.
791  //  testLongLivedScan(TestThriftHBaseServiceHandler.java:804)
792  public void testLongLivedScan() throws Exception {
793    int numTrials = 6;
794    int trialPause = 1000;
795    int cleanUpInterval = 100;
796    Configuration conf = new Configuration(UTIL.getConfiguration());
797    // Set the ConnectionCache timeout to trigger halfway through the trials
798    conf.setInt(MAX_IDLETIME, (numTrials / 2) * trialPause);
799    conf.setInt(CLEANUP_INTERVAL, cleanUpInterval);
800    ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(conf,
801        UserProvider.instantiate(conf));
802
803    ByteBuffer table = wrap(tableAname);
804    // insert data
805    TColumnValue columnValue = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
806        wrap(valueAname));
807    List<TColumnValue> columnValues = new ArrayList<>(1);
808    columnValues.add(columnValue);
809    for (int i = 0; i < numTrials; i++) {
810      TPut put = new TPut(wrap(Bytes.toBytes("testScan" + i)), columnValues);
811      handler.put(table, put);
812    }
813
814    // create scan instance
815    TScan scan = new TScan();
816    List<TColumn> columns = new ArrayList<>(1);
817    TColumn column = new TColumn();
818    column.setFamily(familyAname);
819    column.setQualifier(qualifierAname);
820    columns.add(column);
821    scan.setColumns(columns);
822    scan.setStartRow(Bytes.toBytes("testScan"));
823    scan.setStopRow(Bytes.toBytes("testScan\uffff"));
824    // Prevent the scanner from caching results
825    scan.setCaching(1);
826
827    // get scanner and rows
828    int scanId = handler.openScanner(table, scan);
829    for (int i = 0; i < numTrials; i++) {
830      // Make sure that the Scanner doesn't throw an exception after the ConnectionCache timeout
831      List<TResult> results = handler.getScannerRows(scanId, 1);
832      assertArrayEquals(Bytes.toBytes("testScan" + i), results.get(0).getRow());
833      Thread.sleep(trialPause);
834    }
835  }
836
837  @Test
838  public void testReverseScan() throws Exception {
839    ThriftHBaseServiceHandler handler = createHandler();
840    ByteBuffer table = wrap(tableAname);
841
842    // insert data
843    TColumnValue columnValue = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
844      wrap(valueAname));
845    List<TColumnValue> columnValues = new ArrayList<>(1);
846    columnValues.add(columnValue);
847    for (int i = 0; i < 10; i++) {
848      TPut put = new TPut(wrap(Bytes.toBytes("testReverseScan" + i)), columnValues);
849      handler.put(table, put);
850    }
851
852    // create reverse scan instance
853    TScan scan = new TScan();
854    scan.setReversed(true);
855    List<TColumn> columns = new ArrayList<>(1);
856    TColumn column = new TColumn();
857    column.setFamily(familyAname);
858    column.setQualifier(qualifierAname);
859    columns.add(column);
860    scan.setColumns(columns);
861    scan.setStartRow(Bytes.toBytes("testReverseScan\uffff"));
862    scan.setStopRow(Bytes.toBytes("testReverseScan"));
863
864    // get scanner and rows
865    int scanId = handler.openScanner(table, scan);
866    List<TResult> results = handler.getScannerRows(scanId, 10);
867    assertEquals(10, results.size());
868    for (int i = 0; i < 10; i++) {
869      // check if the rows are returned and in order
870      assertArrayEquals(Bytes.toBytes("testReverseScan" + (9 - i)), results.get(i).getRow());
871    }
872
873    // check that we are at the end of the scan
874    results = handler.getScannerRows(scanId, 10);
875    assertEquals(0, results.size());
876
877    // close scanner and check that it was indeed closed
878    handler.closeScanner(scanId);
879    try {
880      handler.getScannerRows(scanId, 10);
881      fail("Scanner id should be invalid");
882    } catch (TIllegalArgument e) {
883    }
884  }
885
886  @Test
887  public void testScanWithFilter() throws Exception {
888    ThriftHBaseServiceHandler handler = createHandler();
889    ByteBuffer table = wrap(tableAname);
890
891    // insert data
892    TColumnValue columnValue = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
893      wrap(valueAname));
894    List<TColumnValue> columnValues = new ArrayList<>(1);
895    columnValues.add(columnValue);
896    for (int i = 0; i < 10; i++) {
897      TPut put = new TPut(wrap(Bytes.toBytes("testScanWithFilter" + i)), columnValues);
898      handler.put(table, put);
899    }
900
901    // create scan instance with filter
902    TScan scan = new TScan();
903    List<TColumn> columns = new ArrayList<>(1);
904    TColumn column = new TColumn();
905    column.setFamily(familyAname);
906    column.setQualifier(qualifierAname);
907    columns.add(column);
908    scan.setColumns(columns);
909    scan.setStartRow(Bytes.toBytes("testScanWithFilter"));
910    scan.setStopRow(Bytes.toBytes("testScanWithFilter\uffff"));
911    // only get the key part
912    scan.setFilterString(wrap(Bytes.toBytes("KeyOnlyFilter()")));
913
914    // get scanner and rows
915    int scanId = handler.openScanner(table, scan);
916    List<TResult> results = handler.getScannerRows(scanId, 10);
917    assertEquals(10, results.size());
918    for (int i = 0; i < 10; i++) {
919      // check if the rows are returned and in order
920      assertArrayEquals(Bytes.toBytes("testScanWithFilter" + i), results.get(i).getRow());
921      // check that the value is indeed stripped by the filter
922      assertEquals(0, results.get(i).getColumnValues().get(0).getValue().length);
923    }
924
925    // check that we are at the end of the scan
926    results = handler.getScannerRows(scanId, 10);
927    assertEquals(0, results.size());
928
929    // close scanner and check that it was indeed closed
930    handler.closeScanner(scanId);
931    try {
932      handler.getScannerRows(scanId, 10);
933      fail("Scanner id should be invalid");
934    } catch (TIllegalArgument e) {
935    }
936  }
937
938  @Test
939  public void testScanWithColumnFamilyTimeRange() throws Exception {
940    ThriftHBaseServiceHandler handler = createHandler();
941    ByteBuffer table = wrap(tableAname);
942
943    // insert data
944    TColumnValue familyAColumnValue = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
945        wrap(valueAname));
946    TColumnValue familyBColumnValue = new TColumnValue(wrap(familyBname), wrap(qualifierBname),
947        wrap(valueBname));
948    long minTimestamp = EnvironmentEdgeManager.currentTime();
949    for (int i = 0; i < 10; i++) {
950      familyAColumnValue.setTimestamp(minTimestamp + i);
951      familyBColumnValue.setTimestamp(minTimestamp + i);
952      List<TColumnValue> columnValues = new ArrayList<>(2);
953      columnValues.add(familyAColumnValue);
954      columnValues.add(familyBColumnValue);
955      TPut put = new TPut(wrap(Bytes.toBytes("testScanWithColumnFamilyTimeRange" + i)),
956          columnValues);
957      handler.put(table, put);
958    }
959
960    // create scan instance with column family time range
961    TScan scan = new TScan();
962    Map<ByteBuffer,TTimeRange> colFamTimeRangeMap = new HashMap<>(2);
963    colFamTimeRangeMap.put(wrap(familyAname), new TTimeRange(minTimestamp + 3, minTimestamp + 5));
964    colFamTimeRangeMap.put(wrap(familyBname), new TTimeRange(minTimestamp + 6, minTimestamp + 9));
965    scan.setColFamTimeRangeMap(colFamTimeRangeMap);
966
967    // get scanner and rows
968    int scanId = handler.openScanner(table, scan);
969    List<TResult> results = handler.getScannerRows(scanId, 5);
970    assertEquals(5, results.size());
971    int familyACount = 0;
972    int familyBCount = 0;
973    for (TResult result : results) {
974      List<TColumnValue> columnValues = result.getColumnValues();
975      if (CollectionUtils.isNotEmpty(columnValues)) {
976        if (Bytes.equals(familyAname, columnValues.get(0).getFamily())) {
977          familyACount++;
978        } else if (Bytes.equals(familyBname, columnValues.get(0).getFamily())) {
979          familyBCount++;
980        }
981      }
982    }
983    assertEquals(2, familyACount);
984    assertEquals(3, familyBCount);
985
986    // check that we are at the end of the scan
987    results = handler.getScannerRows(scanId, 1);
988    assertEquals(0, results.size());
989
990    // close scanner and check that it was indeed closed
991    handler.closeScanner(scanId);
992    try {
993      handler.getScannerRows(scanId, 1);
994      fail("Scanner id should be invalid");
995    } catch (TIllegalArgument e) {
996    }
997  }
998
999  @Test
1000  public void testSmallScan() throws Exception {
1001    ThriftHBaseServiceHandler handler = createHandler();
1002    ByteBuffer table = wrap(tableAname);
1003
1004    // insert data
1005    TColumnValue columnValue = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
1006            wrap(valueAname));
1007    List<TColumnValue> columnValues = new ArrayList<>();
1008    columnValues.add(columnValue);
1009    for (int i = 0; i < 10; i++) {
1010      TPut put = new TPut(wrap(Bytes.toBytes("testSmallScan" + i)), columnValues);
1011      handler.put(table, put);
1012    }
1013
1014    // small scan instance
1015    TScan scan = new TScan();
1016    scan.setStartRow(Bytes.toBytes("testSmallScan"));
1017    scan.setStopRow(Bytes.toBytes("testSmallScan\uffff"));
1018    scan.setReadType(TReadType.PREAD);
1019    scan.setCaching(2);
1020
1021    // get scanner and rows
1022    int scanId = handler.openScanner(table, scan);
1023    List<TResult> results = handler.getScannerRows(scanId, 10);
1024    assertEquals(10, results.size());
1025    for (int i = 0; i < 10; i++) {
1026      // check if the rows are returned and in order
1027      assertArrayEquals(Bytes.toBytes("testSmallScan" + i), results.get(i).getRow());
1028    }
1029
1030    // check that we are at the end of the scan
1031    results = handler.getScannerRows(scanId, 10);
1032    assertEquals(0, results.size());
1033
1034    // close scanner and check that it was indeed closed
1035    handler.closeScanner(scanId);
1036    try {
1037      handler.getScannerRows(scanId, 10);
1038      fail("Scanner id should be invalid");
1039    } catch (TIllegalArgument e) {
1040    }
1041  }
1042
1043  @Test
1044  public void testPutTTL() throws Exception {
1045    ThriftHBaseServiceHandler handler = createHandler();
1046    byte[] rowName = Bytes.toBytes("testPutTTL");
1047    ByteBuffer table = wrap(tableAname);
1048    List<TColumnValue> columnValues = new ArrayList<>(1);
1049
1050    // Add some dummy data
1051    columnValues.add(
1052        new TColumnValue(
1053            wrap(familyAname),
1054            wrap(qualifierAname),
1055            wrap(Bytes.toBytes(1L))));
1056
1057
1058    TPut put = new TPut(wrap(rowName), columnValues);
1059    put.setColumnValues(columnValues);
1060
1061    Map<ByteBuffer, ByteBuffer> attributes = new HashMap<>();
1062
1063    // Time in ms for the kv's to live.
1064    long ttlTimeMs = 2000L;
1065
1066    // the _ttl attribute is a number of ms ttl for key values in this put.
1067    attributes.put(wrap(Bytes.toBytes("_ttl")), wrap(Bytes.toBytes(ttlTimeMs)));
1068    // Attach the attributes
1069    put.setAttributes(attributes);
1070    // Send it.
1071    handler.put(table, put);
1072
1073    // Now get the data back
1074    TGet getOne = new TGet(wrap(rowName));
1075    TResult resultOne = handler.get(table, getOne);
1076
1077    // It's there.
1078    assertArrayEquals(rowName, resultOne.getRow());
1079    assertEquals(1, resultOne.getColumnValuesSize());
1080
1081    // Sleep 30 seconds just to make 100% sure that the key value should be expired.
1082    Thread.sleep(ttlTimeMs * 15);
1083
1084    TGet getTwo = new TGet(wrap(rowName));
1085    TResult resultTwo = handler.get(table, getTwo);
1086
1087
1088    // Nothing should be there since it's ttl'd out.
1089    assertNull(resultTwo.getRow());
1090    assertEquals(0, resultTwo.getColumnValuesSize());
1091  }
1092
1093  /**
1094   * Padding numbers to make comparison of sort order easier in a for loop
1095   *
1096   * @param n  The number to pad.
1097   * @param pad  The length to pad up to.
1098   * @return The padded number as a string.
1099   */
1100  private String pad(int n, byte pad) {
1101    String res = Integer.toString(n);
1102    while (res.length() < pad) {
1103      res = "0" + res;
1104    }
1105    return res;
1106  }
1107
1108  @Test
1109  public void testScanWithBatchSize() throws Exception {
1110    ThriftHBaseServiceHandler handler = createHandler();
1111    ByteBuffer table = wrap(tableAname);
1112
1113    // insert data
1114    List<TColumnValue> columnValues = new ArrayList<>(100);
1115    for (int i = 0; i < 100; i++) {
1116      String colNum = pad(i, (byte) 3);
1117      TColumnValue columnValue = new TColumnValue(wrap(familyAname),
1118        wrap(Bytes.toBytes("col" + colNum)), wrap(Bytes.toBytes("val" + colNum)));
1119      columnValues.add(columnValue);
1120    }
1121    TPut put = new TPut(wrap(Bytes.toBytes("testScanWithBatchSize")), columnValues);
1122    handler.put(table, put);
1123
1124    // create scan instance
1125    TScan scan = new TScan();
1126    List<TColumn> columns = new ArrayList<>(1);
1127    TColumn column = new TColumn();
1128    column.setFamily(familyAname);
1129    columns.add(column);
1130    scan.setColumns(columns);
1131    scan.setStartRow(Bytes.toBytes("testScanWithBatchSize"));
1132    scan.setStopRow(Bytes.toBytes("testScanWithBatchSize\uffff"));
1133    // set batch size to 10 columns per call
1134    scan.setBatchSize(10);
1135
1136    // get scanner
1137    int scanId = handler.openScanner(table, scan);
1138    List<TResult> results = null;
1139    for (int i = 0; i < 10; i++) {
1140      // get batch for single row (10x10 is what we expect)
1141      results = handler.getScannerRows(scanId, 1);
1142      assertEquals(1, results.size());
1143      // check length of batch
1144      List<TColumnValue> cols = results.get(0).getColumnValues();
1145      assertEquals(10, cols.size());
1146      // check if the columns are returned and in order
1147      for (int y = 0; y < 10; y++) {
1148        int colNum = y + (10 * i);
1149        String colNumPad = pad(colNum, (byte) 3);
1150        assertArrayEquals(Bytes.toBytes("col" + colNumPad), cols.get(y).getQualifier());
1151      }
1152    }
1153
1154    // check that we are at the end of the scan
1155    results = handler.getScannerRows(scanId, 1);
1156    assertEquals(0, results.size());
1157
1158    // close scanner and check that it was indeed closed
1159    handler.closeScanner(scanId);
1160    try {
1161      handler.getScannerRows(scanId, 1);
1162      fail("Scanner id should be invalid");
1163    } catch (TIllegalArgument e) {
1164    }
1165  }
1166
1167  @Test
1168  public void testGetScannerResults() throws Exception {
1169    ThriftHBaseServiceHandler handler = createHandler();
1170    ByteBuffer table = wrap(tableAname);
1171
1172    // insert data
1173    TColumnValue columnValue =
1174        new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname));
1175    List<TColumnValue> columnValues = new ArrayList<>(1);
1176    columnValues.add(columnValue);
1177    for (int i = 0; i < 20; i++) {
1178      TPut put =
1179          new TPut(wrap(Bytes.toBytes("testGetScannerResults" + pad(i, (byte) 2))), columnValues);
1180      handler.put(table, put);
1181    }
1182
1183    // create scan instance
1184    TScan scan = new TScan();
1185    List<TColumn> columns = new ArrayList<>(1);
1186    TColumn column = new TColumn();
1187    column.setFamily(familyAname);
1188    column.setQualifier(qualifierAname);
1189    columns.add(column);
1190    scan.setColumns(columns);
1191    scan.setStartRow(Bytes.toBytes("testGetScannerResults"));
1192
1193    // get 5 rows and check the returned results
1194    scan.setStopRow(Bytes.toBytes("testGetScannerResults05"));
1195    List<TResult> results = handler.getScannerResults(table, scan, 5);
1196    assertEquals(5, results.size());
1197    for (int i = 0; i < 5; i++) {
1198      // check if the rows are returned and in order
1199      assertArrayEquals(Bytes.toBytes("testGetScannerResults" + pad(i, (byte) 2)), results.get(i)
1200          .getRow());
1201    }
1202
1203    // get 10 rows and check the returned results
1204    scan.setStopRow(Bytes.toBytes("testGetScannerResults10"));
1205    results = handler.getScannerResults(table, scan, 10);
1206    assertEquals(10, results.size());
1207    for (int i = 0; i < 10; i++) {
1208      // check if the rows are returned and in order
1209      assertArrayEquals(Bytes.toBytes("testGetScannerResults" + pad(i, (byte) 2)), results.get(i)
1210          .getRow());
1211    }
1212
1213    // get 20 rows and check the returned results
1214    scan.setStopRow(Bytes.toBytes("testGetScannerResults20"));
1215    results = handler.getScannerResults(table, scan, 20);
1216    assertEquals(20, results.size());
1217    for (int i = 0; i < 20; i++) {
1218      // check if the rows are returned and in order
1219      assertArrayEquals(Bytes.toBytes("testGetScannerResults" + pad(i, (byte) 2)), results.get(i)
1220          .getRow());
1221    }
1222
1223    // reverse scan
1224    scan = new TScan();
1225    scan.setColumns(columns);
1226    scan.setReversed(true);
1227    scan.setStartRow(Bytes.toBytes("testGetScannerResults20"));
1228    scan.setStopRow(Bytes.toBytes("testGetScannerResults"));
1229    results = handler.getScannerResults(table, scan, 20);
1230    assertEquals(20, results.size());
1231    for (int i = 0; i < 20; i++) {
1232      // check if the rows are returned and in order
1233      assertArrayEquals(Bytes.toBytes("testGetScannerResults" + pad(19 - i, (byte) 2)),
1234          results.get(i).getRow());
1235    }
1236  }
1237
1238  @Test
1239  public void testFilterRegistration() throws Exception {
1240    Configuration conf = UTIL.getConfiguration();
1241    conf.set("hbase.thrift.filters", "MyFilter:filterclass");
1242    ThriftServer.registerFilters(conf);
1243    Map<String, String> registeredFilters = ParseFilter.getAllFilters();
1244    assertEquals("filterclass", registeredFilters.get("MyFilter"));
1245  }
1246
1247  @Test
1248  public void testMetrics() throws Exception {
1249    Configuration conf = UTIL.getConfiguration();
1250    ThriftMetrics metrics = getMetrics(conf);
1251    ThriftHBaseServiceHandler hbaseHandler = createHandler();
1252    THBaseService.Iface handler =
1253        HbaseHandlerMetricsProxy.newInstance(hbaseHandler, metrics,  conf);
1254    byte[] rowName = Bytes.toBytes("testMetrics");
1255    ByteBuffer table = wrap(tableAname);
1256
1257    TGet get = new TGet(wrap(rowName));
1258    assertFalse(handler.exists(table, get));
1259
1260    List<TColumnValue> columnValues = new ArrayList<>(2);
1261    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
1262    columnValues.add(new TColumnValue(wrap(familyBname), wrap(qualifierBname),  wrap(valueBname)));
1263    TPut put = new TPut(wrap(rowName), columnValues);
1264    put.setColumnValues(columnValues);
1265
1266    handler.put(table, put);
1267
1268    assertTrue(handler.exists(table, get));
1269    metricsHelper.assertCounter("put_num_ops", 1, metrics.getSource());
1270    metricsHelper.assertCounter("exists_num_ops", 2, metrics.getSource());
1271  }
1272
1273  private static ThriftMetrics getMetrics(Configuration conf) throws Exception {
1274    ThriftMetrics m = new ThriftMetrics(conf, ThriftMetrics.ThriftServerType.TWO);
1275    m.getSource().init(); //Clear all the metrics
1276    return m;
1277  }
1278
1279  @Test
1280  public void testMetricsWithException() throws Exception {
1281    byte[] rowkey = Bytes.toBytes("row1");
1282    byte[] family = Bytes.toBytes("f");
1283    byte[] col = Bytes.toBytes("c");
1284    // create a table which will throw exceptions for requests
1285    TableName tableName = TableName.valueOf(name.getMethodName());
1286    TableDescriptor tableDesc = TableDescriptorBuilder.newBuilder(tableName)
1287      .setCoprocessor(ErrorThrowingGetObserver.class.getName())
1288      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(family)).build();
1289
1290    Table table = UTIL.createTable(tableDesc, null);
1291    table.put(new Put(rowkey).addColumn(family, col, Bytes.toBytes("val1")));
1292
1293    ThriftHBaseServiceHandler hbaseHandler = createHandler();
1294    ThriftMetrics metrics = getMetrics(UTIL.getConfiguration());
1295    THBaseService.Iface handler =
1296        HbaseHandlerMetricsProxy.newInstance(hbaseHandler, metrics, null);
1297    ByteBuffer tTableName = wrap(tableName.getName());
1298
1299    // check metrics increment with a successful get
1300    long preGetCounter = metricsHelper.checkCounterExists("get_num_ops", metrics.getSource()) ?
1301        metricsHelper.getCounter("get_num_ops", metrics.getSource()) :
1302        0;
1303    TGet tGet = new TGet(wrap(rowkey));
1304    TResult tResult = handler.get(tTableName, tGet);
1305
1306    List<TColumnValue> expectedColumnValues = Lists.newArrayList(
1307        new TColumnValue(wrap(family), wrap(col), wrap(Bytes.toBytes("val1")))
1308    );
1309    assertArrayEquals(rowkey, tResult.getRow());
1310    List<TColumnValue> returnedColumnValues = tResult.getColumnValues();
1311    assertTColumnValuesEqual(expectedColumnValues, returnedColumnValues);
1312
1313    metricsHelper.assertCounter("get_num_ops", preGetCounter + 1, metrics.getSource());
1314
1315    // check metrics increment when the get throws each exception type
1316    for (ErrorThrowingGetObserver.ErrorType type : ErrorThrowingGetObserver.ErrorType.values()) {
1317      testExceptionType(handler, metrics, tTableName, rowkey, type);
1318    }
1319  }
1320
1321  private void testExceptionType(THBaseService.Iface handler, ThriftMetrics metrics,
1322      ByteBuffer tTableName, byte[] rowkey, ErrorThrowingGetObserver.ErrorType errorType) {
1323    long preGetCounter = metricsHelper.getCounter("get_num_ops", metrics.getSource());
1324    String exceptionKey = errorType.getMetricName();
1325    long preExceptionCounter = metricsHelper.checkCounterExists(exceptionKey, metrics.getSource()) ?
1326        metricsHelper.getCounter(exceptionKey, metrics.getSource()) :
1327        0;
1328    TGet tGet = new TGet(wrap(rowkey));
1329    Map<ByteBuffer, ByteBuffer> attributes = new HashMap<>();
1330    attributes.put(wrap(Bytes.toBytes(ErrorThrowingGetObserver.SHOULD_ERROR_ATTRIBUTE)),
1331        wrap(Bytes.toBytes(errorType.name())));
1332    tGet.setAttributes(attributes);
1333    try {
1334      TResult tResult = handler.get(tTableName, tGet);
1335      fail("Get with error attribute should have thrown an exception");
1336    } catch (TException e) {
1337      LOG.info("Received exception: ", e);
1338      metricsHelper.assertCounter("get_num_ops", preGetCounter + 1, metrics.getSource());
1339      metricsHelper.assertCounter(exceptionKey, preExceptionCounter + 1, metrics.getSource());
1340    }
1341
1342  }
1343
1344  /**
1345   * See HBASE-17611
1346   *
1347   * Latency metrics were capped at ~ 2 seconds due to the use of an int variable to capture the
1348   * duration.
1349   */
1350  @Test
1351  public void testMetricsPrecision() throws Exception {
1352    byte[] rowkey = Bytes.toBytes("row1");
1353    byte[] family = Bytes.toBytes("f");
1354    byte[] col = Bytes.toBytes("c");
1355    // create a table which will throw exceptions for requests
1356    TableName tableName = TableName.valueOf("testMetricsPrecision");
1357    TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName)
1358      .setCoprocessor(DelayingRegionObserver.class.getName())
1359      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(family)).build();
1360
1361    Table table = null;
1362    try {
1363      table = UTIL.createTable(tableDescriptor, null);
1364
1365      table.put(new Put(rowkey).addColumn(family, col, Bytes.toBytes("val1")));
1366
1367      ThriftHBaseServiceHandler hbaseHandler = createHandler();
1368      ThriftMetrics metrics = getMetrics(UTIL.getConfiguration());
1369      THBaseService.Iface handler =
1370          HbaseHandlerMetricsProxy.newInstance(hbaseHandler, metrics, null);
1371      ByteBuffer tTableName = wrap(tableName.getName());
1372
1373      // check metrics latency with a successful get
1374      TGet tGet = new TGet(wrap(rowkey));
1375      TResult tResult = handler.get(tTableName, tGet);
1376
1377      List<TColumnValue> expectedColumnValues = Lists.newArrayList(
1378          new TColumnValue(wrap(family), wrap(col), wrap(Bytes.toBytes("val1")))
1379      );
1380      assertArrayEquals(rowkey, tResult.getRow());
1381      List<TColumnValue> returnedColumnValues = tResult.getColumnValues();
1382      assertTColumnValuesEqual(expectedColumnValues, returnedColumnValues);
1383
1384      metricsHelper.assertGaugeGt("get_max", 3000L, metrics.getSource());
1385    } finally {
1386      if (table != null) {
1387        try {
1388          table.close();
1389        } catch (IOException ignored) {
1390        }
1391        UTIL.deleteTable(tableName);
1392      }
1393    }
1394  }
1395
1396
1397  @Test
1398  public void testAttribute() throws Exception {
1399    byte[] rowName = Bytes.toBytes("testAttribute");
1400    byte[] attributeKey = Bytes.toBytes("attribute1");
1401    byte[] attributeValue = Bytes.toBytes("value1");
1402    Map<ByteBuffer, ByteBuffer> attributes = new HashMap<>();
1403    attributes.put(wrap(attributeKey), wrap(attributeValue));
1404
1405    TGet tGet = new TGet(wrap(rowName));
1406    tGet.setAttributes(attributes);
1407    Get get = getFromThrift(tGet);
1408    assertArrayEquals(get.getAttribute("attribute1"), attributeValue);
1409
1410    List<TColumnValue> columnValues = new ArrayList<>(1);
1411    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
1412    TPut tPut = new TPut(wrap(rowName) , columnValues);
1413    tPut.setAttributes(attributes);
1414    Put put = putFromThrift(tPut);
1415    assertArrayEquals(put.getAttribute("attribute1"), attributeValue);
1416
1417    TScan tScan = new TScan();
1418    tScan.setAttributes(attributes);
1419    Scan scan = scanFromThrift(tScan);
1420    assertArrayEquals(scan.getAttribute("attribute1"), attributeValue);
1421
1422    List<TColumnIncrement> incrementColumns = new ArrayList<>(1);
1423    incrementColumns.add(new TColumnIncrement(wrap(familyAname), wrap(qualifierAname)));
1424    TIncrement tIncrement = new TIncrement(wrap(rowName), incrementColumns);
1425    tIncrement.setAttributes(attributes);
1426    Increment increment = incrementFromThrift(tIncrement);
1427    assertArrayEquals(increment.getAttribute("attribute1"), attributeValue);
1428
1429    TDelete tDelete = new TDelete(wrap(rowName));
1430    tDelete.setAttributes(attributes);
1431    Delete delete = deleteFromThrift(tDelete);
1432    assertArrayEquals(delete.getAttribute("attribute1"), attributeValue);
1433  }
1434
1435  /**
1436   * Put valueA to a row, make sure put has happened, then create a mutation object to put valueB
1437   * and delete ValueA, then check that the row value is only valueB.
1438   */
1439  @Test
1440  public void testMutateRow() throws Exception {
1441    ThriftHBaseServiceHandler handler = createHandler();
1442    byte[] rowName = Bytes.toBytes("testMutateRow");
1443    ByteBuffer table = wrap(tableAname);
1444
1445    List<TColumnValue> columnValuesA = new ArrayList<>(1);
1446    TColumnValue columnValueA = new TColumnValue(wrap(familyAname), wrap(qualifierAname),
1447        wrap(valueAname));
1448    columnValuesA.add(columnValueA);
1449    TPut putA = new TPut(wrap(rowName), columnValuesA);
1450    putA.setColumnValues(columnValuesA);
1451
1452    handler.put(table,putA);
1453
1454    TGet get = new TGet(wrap(rowName));
1455    TResult result = handler.get(table, get);
1456    assertArrayEquals(rowName, result.getRow());
1457    List<TColumnValue> returnedColumnValues = result.getColumnValues();
1458
1459    List<TColumnValue> expectedColumnValues = new ArrayList<>(1);
1460    expectedColumnValues.add(columnValueA);
1461    assertTColumnValuesEqual(expectedColumnValues, returnedColumnValues);
1462
1463    List<TColumnValue> columnValuesB = new ArrayList<>(1);
1464    TColumnValue columnValueB = new TColumnValue(wrap(familyAname), wrap(qualifierBname),
1465        wrap(valueBname));
1466    columnValuesB.add(columnValueB);
1467    TPut putB = new TPut(wrap(rowName), columnValuesB);
1468    putB.setColumnValues(columnValuesB);
1469
1470    TDelete delete = new TDelete(wrap(rowName));
1471    List<TColumn> deleteColumns = new ArrayList<>(1);
1472    TColumn deleteColumn = new TColumn(wrap(familyAname));
1473    deleteColumn.setQualifier(qualifierAname);
1474    deleteColumns.add(deleteColumn);
1475    delete.setColumns(deleteColumns);
1476
1477    List<TMutation> mutations = new ArrayList<>(2);
1478    TMutation mutationA = TMutation.put(putB);
1479    mutations.add(mutationA);
1480
1481    TMutation mutationB = TMutation.deleteSingle(delete);
1482    mutations.add(mutationB);
1483
1484    TRowMutations tRowMutations = new TRowMutations(wrap(rowName),mutations);
1485    handler.mutateRow(table,tRowMutations);
1486
1487    result = handler.get(table, get);
1488    assertArrayEquals(rowName, result.getRow());
1489    returnedColumnValues = result.getColumnValues();
1490
1491    expectedColumnValues = new ArrayList<>(1);
1492    expectedColumnValues.add(columnValueB);
1493    assertTColumnValuesEqual(expectedColumnValues, returnedColumnValues);
1494  }
1495
1496  /**
1497   * Create TPut, TDelete , TIncrement objects, set durability then call ThriftUtility
1498   * functions to get Put , Delete and Increment respectively. Use getDurability to make sure
1499   * the returned objects have the appropriate durability setting.
1500   */
1501  @Test
1502  public void testDurability() throws Exception {
1503    byte[] rowName = Bytes.toBytes("testDurability");
1504    List<TColumnValue> columnValues = new ArrayList<>(1);
1505    columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)));
1506
1507    List<TColumnIncrement> incrementColumns = new ArrayList<>(1);
1508    incrementColumns.add(new TColumnIncrement(wrap(familyAname), wrap(qualifierAname)));
1509
1510    TDelete tDelete = new TDelete(wrap(rowName));
1511    tDelete.setDurability(TDurability.SKIP_WAL);
1512    Delete delete = deleteFromThrift(tDelete);
1513    assertEquals(Durability.SKIP_WAL, delete.getDurability());
1514
1515    tDelete.setDurability(TDurability.ASYNC_WAL);
1516    delete = deleteFromThrift(tDelete);
1517    assertEquals(Durability.ASYNC_WAL, delete.getDurability());
1518
1519    tDelete.setDurability(TDurability.SYNC_WAL);
1520    delete = deleteFromThrift(tDelete);
1521    assertEquals(Durability.SYNC_WAL, delete.getDurability());
1522
1523    tDelete.setDurability(TDurability.FSYNC_WAL);
1524    delete = deleteFromThrift(tDelete);
1525    assertEquals(Durability.FSYNC_WAL, delete.getDurability());
1526
1527    TPut tPut = new TPut(wrap(rowName), columnValues);
1528    tPut.setDurability(TDurability.SKIP_WAL);
1529    Put put = putFromThrift(tPut);
1530    assertEquals(Durability.SKIP_WAL, put.getDurability());
1531
1532    tPut.setDurability(TDurability.ASYNC_WAL);
1533    put = putFromThrift(tPut);
1534    assertEquals(Durability.ASYNC_WAL, put.getDurability());
1535
1536    tPut.setDurability(TDurability.SYNC_WAL);
1537    put = putFromThrift(tPut);
1538    assertEquals(Durability.SYNC_WAL, put.getDurability());
1539
1540    tPut.setDurability(TDurability.FSYNC_WAL);
1541    put = putFromThrift(tPut);
1542    assertEquals(Durability.FSYNC_WAL, put.getDurability());
1543
1544    TIncrement tIncrement = new TIncrement(wrap(rowName), incrementColumns);
1545
1546    tIncrement.setDurability(TDurability.SKIP_WAL);
1547    Increment increment = incrementFromThrift(tIncrement);
1548    assertEquals(Durability.SKIP_WAL, increment.getDurability());
1549
1550    tIncrement.setDurability(TDurability.ASYNC_WAL);
1551    increment = incrementFromThrift(tIncrement);
1552    assertEquals(Durability.ASYNC_WAL, increment.getDurability());
1553
1554    tIncrement.setDurability(TDurability.SYNC_WAL);
1555    increment = incrementFromThrift(tIncrement);
1556    assertEquals(Durability.SYNC_WAL, increment.getDurability());
1557
1558    tIncrement.setDurability(TDurability.FSYNC_WAL);
1559    increment = incrementFromThrift(tIncrement);
1560    assertEquals(Durability.FSYNC_WAL, increment.getDurability());
1561  }
1562
1563  @Test
1564  public void testCheckAndMutate() throws Exception {
1565    ThriftHBaseServiceHandler handler = createHandler();
1566    ByteBuffer table = wrap(tableAname);
1567    ByteBuffer row = wrap(Bytes.toBytes("row"));
1568    ByteBuffer family = wrap(familyAname);
1569    ByteBuffer qualifier = wrap(qualifierAname);
1570    ByteBuffer value = wrap(valueAname);
1571
1572    // Create a mutation to write to 'B', our "mutate" of "checkAndMutate"
1573    List<TColumnValue> columnValuesB = new ArrayList<>(1);
1574    TColumnValue columnValueB = new TColumnValue(family, wrap(qualifierBname), wrap(valueBname));
1575    columnValuesB.add(columnValueB);
1576    TPut putB = new TPut(row, columnValuesB);
1577    putB.setColumnValues(columnValuesB);
1578
1579    TRowMutations tRowMutations = new TRowMutations(row,
1580        Arrays.<TMutation> asList(TMutation.put(putB)));
1581
1582    // Empty table when we begin
1583    TResult result = handler.get(table, new TGet(row));
1584    assertEquals(0, result.getColumnValuesSize());
1585
1586    // checkAndMutate -- condition should fail because the value doesn't exist.
1587    assertFalse("Expected condition to not pass",
1588        handler.checkAndMutate(table, row, family, qualifier, TCompareOperator.EQUAL, value,
1589            tRowMutations));
1590
1591    List<TColumnValue> columnValuesA = new ArrayList<>(1);
1592    TColumnValue columnValueA = new TColumnValue(family, qualifier, value);
1593    columnValuesA.add(columnValueA);
1594
1595    // Put an update 'A'
1596    handler.put(table, new TPut(row, columnValuesA));
1597
1598    // Verify that the update is there
1599    result = handler.get(table, new TGet(row));
1600    assertEquals(1, result.getColumnValuesSize());
1601    assertTColumnValueEqual(columnValueA, result.getColumnValues().get(0));
1602
1603    // checkAndMutate -- condition should pass since we added the value
1604    assertTrue("Expected condition to pass",
1605        handler.checkAndMutate(table, row, family, qualifier, TCompareOperator.EQUAL, value,
1606            tRowMutations));
1607
1608    result = handler.get(table, new TGet(row));
1609    assertEquals(2, result.getColumnValuesSize());
1610    assertTColumnValueEqual(columnValueA, result.getColumnValues().get(0));
1611    assertTColumnValueEqual(columnValueB, result.getColumnValues().get(1));
1612  }
1613
1614  @Test
1615  public void testConsistency() throws Exception {
1616    byte[] rowName = Bytes.toBytes("testConsistency");
1617    TGet tGet = new TGet(wrap(rowName));
1618    tGet.setConsistency(TConsistency.STRONG);
1619    Get get = getFromThrift(tGet);
1620    assertEquals(Consistency.STRONG, get.getConsistency());
1621
1622    tGet.setConsistency(TConsistency.TIMELINE);
1623    tGet.setTargetReplicaId(1);
1624    get = getFromThrift(tGet);
1625    assertEquals(Consistency.TIMELINE, get.getConsistency());
1626    assertEquals(1, get.getReplicaId());
1627
1628    TScan tScan = new TScan();
1629    tScan.setConsistency(TConsistency.STRONG);
1630    Scan scan = scanFromThrift(tScan);
1631    assertEquals(Consistency.STRONG, scan.getConsistency());
1632
1633    tScan.setConsistency(TConsistency.TIMELINE);
1634    tScan.setTargetReplicaId(1);
1635    scan = scanFromThrift(tScan);
1636    assertEquals(Consistency.TIMELINE, scan.getConsistency());
1637    assertEquals(1, scan.getReplicaId());
1638
1639    TResult tResult = new TResult();
1640    assertFalse(tResult.isSetStale());
1641    tResult.setStale(true);
1642    assertTrue(tResult.isSetStale());
1643  }
1644
1645  @Test
1646  public void testDDLOpertions() throws Exception {
1647    String namespace = "testDDLOpertionsNamespace";
1648    String table = "testDDLOpertionsTable";
1649    TTableName tTableName = new TTableName();
1650    tTableName.setNs(Bytes.toBytes(namespace));
1651    tTableName.setQualifier(Bytes.toBytes(table));
1652    ThriftHBaseServiceHandler handler = createHandler();
1653    //create name space
1654    TNamespaceDescriptor namespaceDescriptor = new TNamespaceDescriptor();
1655    namespaceDescriptor.setName(namespace);
1656    namespaceDescriptor.putToConfiguration("key1", "value1");
1657    namespaceDescriptor.putToConfiguration("key2", "value2");
1658    handler.createNamespace(namespaceDescriptor);
1659    //list namespace
1660    List<TNamespaceDescriptor> namespaceDescriptors = handler.listNamespaceDescriptors();
1661    // should have 3 namespace, default hbase and testDDLOpertionsNamespace
1662    assertTrue(namespaceDescriptors.size() == 3);
1663    //modify namesapce
1664    namespaceDescriptor.putToConfiguration("kye3", "value3");
1665    handler.modifyNamespace(namespaceDescriptor);
1666    //get namespace
1667    TNamespaceDescriptor namespaceDescriptorReturned = handler.getNamespaceDescriptor(namespace);
1668    assertTrue(namespaceDescriptorReturned.getConfiguration().size() == 3);
1669    //create table
1670    TTableDescriptor tableDescriptor = new TTableDescriptor();
1671    tableDescriptor.setTableName(tTableName);
1672    TColumnFamilyDescriptor columnFamilyDescriptor1 = new TColumnFamilyDescriptor();
1673    columnFamilyDescriptor1.setName(familyAname);
1674    columnFamilyDescriptor1.setDataBlockEncoding(TDataBlockEncoding.DIFF);
1675    tableDescriptor.addToColumns(columnFamilyDescriptor1);
1676    List<ByteBuffer> splitKeys = new ArrayList<>();
1677    splitKeys.add(ByteBuffer.wrap(Bytes.toBytes(5)));
1678    handler.createTable(tableDescriptor, splitKeys);
1679    //modify table
1680    tableDescriptor.setDurability(TDurability.ASYNC_WAL);
1681    handler.modifyTable(tableDescriptor);
1682    //modify column family
1683    columnFamilyDescriptor1.setInMemory(true);
1684    handler.modifyColumnFamily(tTableName, columnFamilyDescriptor1);
1685    //add column family
1686    TColumnFamilyDescriptor columnFamilyDescriptor2 = new TColumnFamilyDescriptor();
1687    columnFamilyDescriptor2.setName(familyBname);
1688    columnFamilyDescriptor2.setDataBlockEncoding(TDataBlockEncoding.PREFIX);
1689    handler.addColumnFamily(tTableName, columnFamilyDescriptor2);
1690    //get table descriptor
1691    TTableDescriptor tableDescriptorReturned = handler.getTableDescriptor(tTableName);
1692    assertTrue(tableDescriptorReturned.getColumns().size() == 2);
1693    assertTrue(tableDescriptorReturned.getDurability() ==  TDurability.ASYNC_WAL);
1694    TColumnFamilyDescriptor columnFamilyDescriptor1Returned = tableDescriptorReturned.getColumns()
1695        .stream().filter(desc -> Bytes.equals(desc.getName(), familyAname)).findFirst().get();
1696    assertTrue(columnFamilyDescriptor1Returned.isInMemory() == true);
1697    //delete column family
1698    handler.deleteColumnFamily(tTableName, ByteBuffer.wrap(familyBname));
1699    tableDescriptorReturned = handler.getTableDescriptor(tTableName);
1700    assertTrue(tableDescriptorReturned.getColumns().size() == 1);
1701    //disable table
1702    handler.disableTable(tTableName);
1703    assertTrue(handler.isTableDisabled(tTableName));
1704    //enable table
1705    handler.enableTable(tTableName);
1706    assertTrue(handler.isTableEnabled(tTableName));
1707    assertTrue(handler.isTableAvailable(tTableName));
1708    //truncate table
1709    handler.disableTable(tTableName);
1710    handler.truncateTable(tTableName, true);
1711    assertTrue(handler.isTableAvailable(tTableName));
1712    //delete table
1713    handler.disableTable(tTableName);
1714    handler.deleteTable(tTableName);
1715    assertFalse(handler.tableExists(tTableName));
1716    //delete namespace
1717    handler.deleteNamespace(namespace);
1718    namespaceDescriptors = handler.listNamespaceDescriptors();
1719    // should have 2 namespace, default and hbase
1720    assertTrue(namespaceDescriptors.size() == 2);
1721  }
1722
1723  @Test
1724  public void testGetTableDescriptor() throws Exception {
1725    ThriftHBaseServiceHandler handler = createHandler();
1726    TTableDescriptor tableDescriptor = handler
1727        .getTableDescriptor(ThriftUtilities.tableNameFromHBase(TableName.valueOf(tableAname)));
1728    TableDescriptor table = ThriftUtilities.tableDescriptorFromThrift(tableDescriptor);
1729    assertTrue(table.getTableName().equals(TableName.valueOf(tableAname)));
1730    assertTrue(table.getColumnFamilies().length == 2);
1731    assertTrue(table.getColumnFamily(familyAname).getMaxVersions() == 3);
1732    assertTrue(table.getColumnFamily(familyBname).getMaxVersions() == 2);
1733  }
1734
1735  @Test
1736  public void testGetThriftServerType() throws Exception {
1737    ThriftHBaseServiceHandler handler = createHandler();
1738    assertEquals(TThriftServerType.TWO, handler.getThriftServerType());
1739  }
1740
1741  /**
1742   * Verify that thrift2 client calling thrift server can get the thrift server type correctly.
1743   */
1744  @Test
1745  public void testGetThriftServerOneType() throws Exception {
1746
1747    // start a thrift server
1748    HBaseThriftTestingUtility THRIFT_TEST_UTIL = new HBaseThriftTestingUtility();
1749
1750    LOG.info("Starting HBase Thrift server One");
1751    THRIFT_TEST_UTIL.startThriftServer(UTIL.getConfiguration(), ThriftServerType.ONE);
1752    try (TTransport transport = new TSocket(InetAddress.getLocalHost().getHostName(),
1753        THRIFT_TEST_UTIL.getServerPort())){
1754      TProtocol protocol = new TBinaryProtocol(transport);
1755      // This is our thrift2 client.
1756      THBaseService.Iface client = new THBaseService.Client(protocol);
1757      // open the transport
1758      transport.open();
1759      assertEquals(TThriftServerType.ONE.name(), client.getThriftServerType().name());
1760    } finally {
1761      THRIFT_TEST_UTIL.stopThriftServer();
1762    }
1763  }
1764
1765  @Test
1766  public void testSlowLogResponses() throws Exception {
1767
1768    // start a thrift server
1769    HBaseThriftTestingUtility THRIFT_TEST_UTIL = new HBaseThriftTestingUtility();
1770    Configuration configuration = UTIL.getConfiguration();
1771    configuration.setBoolean("hbase.regionserver.slowlog.buffer.enabled", true);
1772
1773    THRIFT_TEST_UTIL.startThriftServer(configuration, ThriftServerType.ONE);
1774    ThriftHBaseServiceHandler thriftHBaseServiceHandler =
1775      new ThriftHBaseServiceHandler(configuration,
1776        UserProvider.instantiate(configuration));
1777    Collection<ServerName> serverNames = UTIL.getAdmin().getRegionServers();
1778    Set<TServerName> tServerNames =
1779      ThriftUtilities.getServerNamesFromHBase(new HashSet<>(serverNames));
1780    List<Boolean> clearedResponses =
1781      thriftHBaseServiceHandler.clearSlowLogResponses(tServerNames);
1782    clearedResponses.forEach(Assert::assertTrue);
1783    TLogQueryFilter tLogQueryFilter = new TLogQueryFilter();
1784    tLogQueryFilter.setLimit(15);
1785    Assert.assertEquals(tLogQueryFilter.getFilterByOperator(), TFilterByOperator.OR);
1786    LogQueryFilter logQueryFilter = ThriftUtilities.getSlowLogQueryFromThrift(tLogQueryFilter);
1787    Assert.assertEquals(logQueryFilter.getFilterByOperator(), LogQueryFilter.FilterByOperator.OR);
1788    tLogQueryFilter.setFilterByOperator(TFilterByOperator.AND);
1789    logQueryFilter = ThriftUtilities.getSlowLogQueryFromThrift(tLogQueryFilter);
1790    Assert.assertEquals(logQueryFilter.getFilterByOperator(), LogQueryFilter.FilterByOperator.AND);
1791    List<TOnlineLogRecord> tLogRecords =
1792      thriftHBaseServiceHandler.getSlowLogResponses(tServerNames, tLogQueryFilter);
1793    assertEquals(tLogRecords.size(), 0);
1794  }
1795
1796  @Test
1797  public void testPerformTablePermissions() throws Throwable {
1798    // initialize fake objects.
1799    String fakeUser = "user";
1800    TAccessControlEntity tce = new TAccessControlEntity();
1801    tce.setActions("R");
1802    tce.setTableName(Bytes.toString(tableAname));
1803    tce.setScope(TPermissionScope.TABLE);
1804    tce.setUsername(fakeUser);
1805
1806    ThriftHBaseServiceHandler handler = createHandler();
1807    handler.grant(tce);
1808
1809    List<UserPermission> permissionList = AccessControlClient.getUserPermissions(UTIL.getConnection(),
1810        Bytes.toString(tableAname), fakeUser);
1811    // we only grant one R permission
1812    assertEquals(permissionList.size(), 1);
1813
1814    Permission.Action[] actions = permissionList.get(0).getPermission().getActions();
1815    assertEquals(actions.length, 1);
1816    assertEquals(actions[0], Permission.Action.READ);
1817
1818    // than revoke the permission
1819    handler.revoke(tce);
1820    permissionList = AccessControlClient.getUserPermissions(UTIL.getConnection(),
1821      Bytes.toString(tableAname), fakeUser);
1822
1823    // it should return an empty list
1824    assertEquals(0, permissionList.size());
1825  }
1826
1827
1828  @Test
1829  public void testPerformNamespacePermissions() throws Throwable {
1830    // initialize fake objects. We test the permission grant and revoke on default NS.
1831    String fakeUser = "user";
1832    String defaultNameSpace = "default";
1833    TAccessControlEntity tce = new TAccessControlEntity();
1834    tce.setActions("R");
1835    tce.setNsName(defaultNameSpace);
1836    tce.setScope(TPermissionScope.NAMESPACE);
1837    tce.setUsername(fakeUser);
1838
1839    ThriftHBaseServiceHandler handler = createHandler();
1840    handler.grant(tce);
1841
1842    List<UserPermission> permissionList = AccessControlClient.getUserPermissions(UTIL.getConnection(),
1843      "@" + defaultNameSpace, fakeUser);
1844
1845    // we only grant one R permission
1846    assertEquals(permissionList.size(), 1);
1847
1848    Permission.Action[] actions = permissionList.get(0).getPermission().getActions();
1849    assertEquals(actions.length, 1);
1850    assertEquals(actions[0], Permission.Action.READ);
1851
1852    // revoke the permission
1853    handler.revoke(tce);
1854    permissionList = AccessControlClient.getUserPermissions(UTIL.getConnection(),
1855      "@" + defaultNameSpace, fakeUser);
1856
1857    // it should return an empty list
1858    assertEquals(0, permissionList.size());
1859  }
1860
1861  public static class DelayingRegionObserver implements RegionCoprocessor, RegionObserver {
1862    private static final Logger LOG = LoggerFactory.getLogger(DelayingRegionObserver.class);
1863    // sleep time in msec
1864    private long delayMillis;
1865
1866    @Override
1867    public Optional<RegionObserver> getRegionObserver() {
1868      return Optional.of(this);
1869    }
1870
1871    @Override
1872    public void start(CoprocessorEnvironment e) throws IOException {
1873      this.delayMillis = e.getConfiguration()
1874          .getLong("delayingregionobserver.delay", 3000);
1875    }
1876
1877    @Override
1878    public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get,
1879                         List<Cell> results) throws IOException {
1880      try {
1881        long start = EnvironmentEdgeManager.currentTime();
1882        TimeUnit.MILLISECONDS.sleep(delayMillis);
1883        if (LOG.isTraceEnabled()) {
1884          LOG.trace("Slept for " + (EnvironmentEdgeManager.currentTime() - start) + " msec");
1885        }
1886      } catch (InterruptedException ie) {
1887        throw new InterruptedIOException("Interrupted while sleeping");
1888      }
1889    }
1890  }
1891}
1892