-
Notifications
You must be signed in to change notification settings - Fork 1k
/
client-test.cc
3219 lines (2773 loc) · 121 KB
/
client-test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include <algorithm>
#include <functional>
#include <regex>
#include <set>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "yb/client/client-internal.h"
#include "yb/client/client-test-util.h"
#include "yb/client/client.h"
#include "yb/client/client_utils.h"
#include "yb/client/error.h"
#include "yb/client/meta_cache.h"
#include "yb/client/schema.h"
#include "yb/client/session.h"
#include "yb/client/table.h"
#include "yb/client/table_alterer.h"
#include "yb/client/table_creator.h"
#include "yb/client/table_handle.h"
#include "yb/client/table_info.h"
#include "yb/client/tablet_server.h"
#include "yb/client/value.h"
#include "yb/client/yb_op.h"
#include "yb/dockv/partial_row.h"
#include "yb/common/ql_type.h"
#include "yb/common/ql_value.h"
#include "yb/common/schema.h"
#include "yb/common/wire_protocol.h"
#include "yb/consensus/consensus.proxy.h"
#include "yb/gutil/algorithm.h"
#include "yb/gutil/atomicops.h"
#include "yb/gutil/stl_util.h"
#include "yb/gutil/strings/substitute.h"
#include "yb/integration-tests/cluster_itest_util.h"
#include "yb/integration-tests/mini_cluster.h"
#include "yb/integration-tests/yb_mini_cluster_test_base.h"
#include "yb/master/catalog_manager_if.h"
#include "yb/master/master.h"
#include "yb/master/master_client.pb.h"
#include "yb/master/master_cluster.proxy.h"
#include "yb/master/master_ddl.pb.h"
#include "yb/master/master_error.h"
#include "yb/master/mini_master.h"
#include "yb/master/sys_catalog_initialization.h"
#include "yb/rpc/messenger.h"
#include "yb/rpc/proxy.h"
#include "yb/rpc/rpc_controller.h"
#include "yb/rpc/rpc_test_util.h"
#include "yb/rpc/sidecars.h"
#include "yb/tablet/tablet.h"
#include "yb/tablet/tablet_metadata.h"
#include "yb/tablet/tablet_peer.h"
#include "yb/tserver/mini_tablet_server.h"
#include "yb/tserver/tablet_server.h"
#include "yb/tserver/ts_tablet_manager.h"
#include "yb/tserver/tserver_service.proxy.h"
#include "yb/util/flags.h"
#include "yb/util/backoff_waiter.h"
#include "yb/util/metrics.h"
#include "yb/util/net/sockaddr.h"
#include "yb/util/random_util.h"
#include "yb/util/status.h"
#include "yb/util/status_log.h"
#include "yb/util/stopwatch.h"
#include "yb/util/sync_point.h"
#include "yb/util/test_thread_holder.h"
#include "yb/util/thread.h"
#include "yb/util/tostring.h"
#include "yb/util/tsan_util.h"
#include "yb/yql/cql/ql/util/statement_result.h"
#include "yb/yql/pgwrapper/pg_wrapper.h"
#include "yb/yql/pgwrapper/libpq_utils.h"
DECLARE_bool(enable_data_block_fsync);
DECLARE_bool(log_inject_latency);
DECLARE_double(leader_failure_max_missed_heartbeat_periods);
DECLARE_int32(heartbeat_interval_ms);
DECLARE_int32(log_inject_latency_ms_mean);
DECLARE_int32(log_inject_latency_ms_stddev);
DECLARE_int32(master_inject_latency_on_tablet_lookups_ms);
DECLARE_int32(max_create_tablets_per_ts);
DECLARE_int32(tablet_server_svc_queue_length);
DECLARE_int32(replication_factor);
DEFINE_NON_RUNTIME_int32(test_scan_num_rows, 1000, "Number of rows to insert and scan");
DECLARE_int32(min_backoff_ms_exponent);
DECLARE_int32(max_backoff_ms_exponent);
DECLARE_bool(TEST_force_master_lookup_all_tablets);
DECLARE_double(TEST_simulate_lookup_timeout_probability);
DECLARE_bool(ysql_legacy_colocated_database_creation);
DECLARE_int32(pgsql_proxy_webserver_port);
DECLARE_int32(scheduled_full_compaction_frequency_hours);
DECLARE_int32(rocksdb_level0_file_num_compaction_trigger);
METRIC_DECLARE_counter(rpcs_queue_overflow);
using namespace std::literals; // NOLINT
using namespace std::placeholders;
namespace yb {
namespace client {
using std::string;
using std::set;
using std::vector;
using base::subtle::Atomic32;
using base::subtle::NoBarrier_AtomicIncrement;
using base::subtle::NoBarrier_Load;
using base::subtle::NoBarrier_Store;
using dockv::PartitionSchema;
using master::GetNamespaceInfoResponsePB;
using master::GetTableLocationsRequestPB;
using master::GetTableLocationsResponsePB;
using master::TSInfoPB;
using std::shared_ptr;
using tablet::TabletPeer;
using tserver::MiniTabletServer;
namespace {
constexpr int32_t kNoBound = kint32max;
constexpr int kNumTablets = 2;
const std::string kKeyspaceName = "my_keyspace";
const std::string kPgsqlKeyspaceName = "psql" + kKeyspaceName;
const std::string kPgsqlSchemaName = "my_schema";
const std::string kPgsqlTableName = "table";
const std::string kPgsqlTableId = "tableid";
const std::string kPgsqlNamespaceName = "test_namespace";
} // namespace
class ClientTest: public YBMiniClusterTestBase<MiniCluster> {
public:
ClientTest() {
YBSchemaBuilder b;
b.AddColumn("key")->Type(DataType::INT32)->NotNull()->HashPrimaryKey();
b.AddColumn("int_val")->Type(DataType::INT32)->NotNull();
b.AddColumn("string_val")->Type(DataType::STRING)->Nullable();
b.AddColumn("non_null_with_default")->Type(DataType::INT32)->NotNull();
CHECK_OK(b.Build(&schema_));
ANNOTATE_UNPROTECTED_WRITE(FLAGS_enable_data_block_fsync) = false; // Keep unit tests fast.
}
void SetUp() override {
YBMiniClusterTestBase::SetUp();
// Reduce the TS<->Master heartbeat interval
ANNOTATE_UNPROTECTED_WRITE(FLAGS_heartbeat_interval_ms) = 10;
// Start minicluster and wait for tablet servers to connect to master.
auto opts = MiniClusterOptions();
opts.num_tablet_servers = 3;
opts.num_masters = NumMasters();
cluster_.reset(new MiniCluster(opts));
ASSERT_OK(cluster_->Start());
// Connect to the cluster.
ASSERT_OK(InitClient());
// Create a keyspace;
ASSERT_OK(client_->CreateNamespace(kKeyspaceName));
ASSERT_NO_FATALS(CreateTable(kTableName, kNumTablets, &client_table_));
ASSERT_NO_FATALS(CreateTable(kTable2Name, 1, &client_table2_));
ASSERT_NO_FATALS(CreatePgSqlTable());
}
void DoTearDown() override {
client_.reset();
if (cluster_) {
cluster_->Shutdown();
cluster_.reset();
}
YBMiniClusterTestBase::DoTearDown();
}
protected:
static const YBTableName kTableName;
static const YBTableName kTable2Name;
static const YBTableName kTable3Name;
virtual int NumMasters() {
return 1;
}
virtual Status InitClient() {
client_ = VERIFY_RESULT(YBClientBuilder()
.add_master_server_addr(yb::ToString(cluster_->mini_master()->bound_rpc_addr()))
.Build());
return Status::OK();
}
string GetFirstTabletId(YBTable* table) {
GetTableLocationsRequestPB req;
GetTableLocationsResponsePB resp;
table->name().SetIntoTableIdentifierPB(req.mutable_table());
CHECK_OK(cluster_->mini_master()->catalog_manager().GetTableLocations(&req, &resp));
CHECK_GT(resp.tablet_locations_size(), 0);
return resp.tablet_locations(0).tablet_id();
}
void CheckNoRpcOverflow() {
for (size_t i = 0; i < cluster_->num_tablet_servers(); i++) {
MiniTabletServer* server = cluster_->mini_tablet_server(i);
if (server->is_started()) {
ASSERT_EQ(0, server->server()->rpc_server()->
TEST_service_pool("yb.tserver.TabletServerService")->
RpcsQueueOverflowMetric()->value());
}
}
}
YBSessionPtr CreateSession(YBClient* client = nullptr) {
if (client == nullptr) {
client = client_.get();
}
return client->NewSession(10s * kTimeMultiplier);
}
// Inserts 'num_rows' test rows using 'client'
void InsertTestRows(YBClient* client, const TableHandle& table, int num_rows, int first_row = 0) {
auto session = CreateSession(client);
for (int i = first_row; i < num_rows + first_row; i++) {
session->Apply(BuildTestRow(table, i));
}
FlushSessionOrDie(session);
ASSERT_NO_FATALS(CheckNoRpcOverflow());
}
// Inserts 'num_rows' using the default client.
void InsertTestRows(const TableHandle& table, int num_rows, int first_row = 0) {
InsertTestRows(client_.get(), table, num_rows, first_row);
}
void UpdateTestRows(const TableHandle& table, int lo, int hi) {
auto session = CreateSession();
for (int i = lo; i < hi; i++) {
session->Apply(UpdateTestRow(table, i));
}
FlushSessionOrDie(session);
ASSERT_NO_FATALS(CheckNoRpcOverflow());
}
void DeleteTestRows(const TableHandle& table, int lo, int hi) {
auto session = CreateSession();
for (int i = lo; i < hi; i++) {
session->Apply(DeleteTestRow(table, i));
}
FlushSessionOrDie(session);
ASSERT_NO_FATALS(CheckNoRpcOverflow());
}
shared_ptr<YBqlWriteOp> BuildTestRow(const TableHandle& table, int index) {
auto insert = table.NewInsertOp();
auto req = insert->mutable_request();
QLAddInt32HashValue(req, index);
const auto& columns = table.schema().columns();
table.AddInt32ColumnValue(req, columns[1].name(), index * 2);
table.AddStringColumnValue(req, columns[2].name(), StringPrintf("hello %d", index));
table.AddInt32ColumnValue(req, columns[3].name(), index * 3);
return insert;
}
shared_ptr<YBqlWriteOp> UpdateTestRow(const TableHandle& table, int index) {
auto update = table.NewUpdateOp();
auto req = update->mutable_request();
QLAddInt32HashValue(req, index);
const auto& columns = table.schema().columns();
table.AddInt32ColumnValue(req, columns[1].name(), index * 2 + 1);
table.AddStringColumnValue(req, columns[2].name(), StringPrintf("hello again %d", index));
return update;
}
shared_ptr<YBqlWriteOp> DeleteTestRow(const TableHandle& table, int index) {
auto del = table.NewDeleteOp();
QLAddInt32HashValue(del->mutable_request(), index);
return del;
}
void DoTestScanWithoutPredicates() {
client::TableIteratorOptions options;
options.columns = std::vector<std::string>{"key"};
LOG_TIMING(INFO, "Scanning with no predicates") {
uint64_t sum = 0;
for (const auto& row : client::TableRange(client_table_, options)) {
sum += row.column(0).int32_value();
}
// The sum should be the sum of the arithmetic series from
// 0..FLAGS_test_scan_num_rows-1
uint64_t expected = FLAGS_test_scan_num_rows *
(0 + (FLAGS_test_scan_num_rows - 1)) / 2;
ASSERT_EQ(expected, sum);
}
}
void DoTestScanWithStringPredicate() {
TableIteratorOptions options;
options.filter = FilterBetween("hello 2"s, Inclusive::kFalse,
"hello 3"s, Inclusive::kFalse,
"string_val");
bool found = false;
LOG_TIMING(INFO, "Scanning with string predicate") {
for (const auto& row : TableRange(client_table_, options)) {
found = true;
Slice slice(row.column(2).string_value());
if (!slice.starts_with("hello 2") && !slice.starts_with("hello 3")) {
FAIL() << row.ToString();
}
}
}
ASSERT_TRUE(found);
}
void DoTestScanWithKeyPredicate() {
auto op = client_table_.NewReadOp();
auto req = op->mutable_request();
auto* const condition = req->mutable_where_expr()->mutable_condition();
condition->set_op(QL_OP_AND);
client_table_.AddInt32Condition(condition, "key", QL_OP_GREATER_THAN_EQUAL, 5);
client_table_.AddInt32Condition(condition, "key", QL_OP_LESS_THAN_EQUAL, 10);
client_table_.AddColumns({"key"}, req);
auto session = client_->NewSession(60s);
ASSERT_OK(session->TEST_ApplyAndFlush(op));
ASSERT_EQ(QLResponsePB::YQL_STATUS_OK, op->response().status());
auto rowblock = ql::RowsResult(op.get()).GetRowBlock();
for (const auto& row : rowblock->rows()) {
int32_t key = row.column(0).int32_value();
ASSERT_GE(key, 5);
ASSERT_LE(key, 10);
}
}
// Creates a table with RF=FLAGS_replication_factor, split into tablets based on 'split_rows'
// (or single tablet if 'split_rows' is empty).
void CreateTable(const YBTableName& table_name_orig,
int num_tablets,
TableHandle* table) {
size_t num_replicas = FLAGS_replication_factor;
// The implementation allows table name without a keyspace.
YBTableName table_name(table_name_orig.namespace_type(), table_name_orig.has_namespace() ?
table_name_orig.namespace_name() : kKeyspaceName, table_name_orig.table_name());
bool added_replicas = false;
// Add more tablet servers to satisfy all replicas, if necessary.
while (cluster_->num_tablet_servers() < num_replicas) {
ASSERT_OK(cluster_->AddTabletServer());
added_replicas = true;
}
if (added_replicas) {
ASSERT_OK(cluster_->WaitForTabletServerCount(num_replicas));
}
ASSERT_OK(table->Create(table_name, num_tablets, schema_, client_.get()));
}
void CreatePgSqlTable() {
std::unique_ptr<YBTableCreator> table_creator(client_->NewTableCreator());
ASSERT_OK(client_->CreateNamespace(
kPgsqlNamespaceName, YQL_DATABASE_PGSQL, "" /* creator */, "" /* ns_id */,
"" /* src_ns_id */, boost::none /* next_pg_oid */, nullptr /* txn */, false));
std::string kNamespaceId;
{
auto namespaces = ASSERT_RESULT(client_->ListNamespaces());
for (const auto& ns : namespaces) {
if (ns.id.name() == kPgsqlNamespaceName) {
kNamespaceId = ns.id.id();
break;
}
}
}
auto pgsql_table_name =
YBTableName(YQL_DATABASE_PGSQL, kNamespaceId, kPgsqlNamespaceName, kPgsqlTableName);
YBSchemaBuilder schema_builder;
schema_builder.AddColumn("key")->PrimaryKey()->Type(DataType::STRING)->NotNull();
schema_builder.AddColumn("value")->Type(DataType::INT64)->NotNull();
schema_builder.SetSchemaName(kPgsqlSchemaName);
EXPECT_OK(client_->CreateNamespaceIfNotExists(
kPgsqlNamespaceName, YQLDatabase::YQL_DATABASE_PGSQL, "" /* creator_role_name */,
kNamespaceId));
YBSchema schema;
EXPECT_OK(schema_builder.Build(&schema));
EXPECT_OK(table_creator->table_name(pgsql_table_name)
.table_id(kPgsqlTableId)
.schema(&schema)
.table_type(YBTableType::PGSQL_TABLE_TYPE)
.set_range_partition_columns({"key"})
.num_tablets(1)
.Create());
}
// Kills a tablet server.
// Boolean flags control whether to restart the tserver, and if so, whether to wait for it to
// finish bootstrapping.
Status KillTServerImpl(const string& uuid, const bool restart, const bool wait_started) {
bool ts_found = false;
for (size_t i = 0; i < cluster_->num_tablet_servers(); i++) {
MiniTabletServer* ts = cluster_->mini_tablet_server(i);
if (ts->server()->instance_pb().permanent_uuid() == uuid) {
if (restart) {
LOG(INFO) << "Restarting TS at " << ts->bound_rpc_addr();
RETURN_NOT_OK(ts->Restart());
if (wait_started) {
LOG(INFO) << "Waiting for TS " << ts->bound_rpc_addr() << " to finish bootstrapping";
RETURN_NOT_OK(ts->WaitStarted());
}
} else {
LOG(INFO) << "Killing TS " << uuid << " at " << ts->bound_rpc_addr();
ts->Shutdown();
}
ts_found = true;
break;
}
}
if (!ts_found) {
return STATUS(InvalidArgument, strings::Substitute("Could not find tablet server $1", uuid));
}
return Status::OK();
}
Status RestartTServerAndWait(const string& uuid) {
return KillTServerImpl(uuid, true, true);
}
Status RestartTServerAsync(const string& uuid) {
return KillTServerImpl(uuid, true, false);
}
Status KillTServer(const string& uuid) {
return KillTServerImpl(uuid, false, false);
}
void DoApplyWithoutFlushTest(int sleep_micros);
Result<std::unique_ptr<rpc::Messenger>> CreateMessenger(const std::string& name) {
return rpc::MessengerBuilder(name).Build();
}
void VerifyKeyRangeFiltering(const std::vector<string>& sorted_partitions,
const std::vector<internal::RemoteTabletPtr>& tablets,
const string& start_key, const string& end_key) {
auto start_idx = FindPartitionStartIndex(sorted_partitions, start_key);
auto end_idx = FindPartitionStartIndexExclusiveBound(sorted_partitions, end_key);
auto filtered_tablets = FilterTabletsByKeyRange(tablets, start_key, end_key);
std::vector<string> filtered_partitions;
std::transform(filtered_tablets.begin(), filtered_tablets.end(),
std::back_inserter(filtered_partitions),
[](const auto& tablet) { return tablet->partition().partition_key_start(); });
std::sort(filtered_partitions.begin(), filtered_partitions.end());
ASSERT_EQ(filtered_partitions,
std::vector<string>(&sorted_partitions[start_idx], &sorted_partitions[end_idx + 1]));
}
size_t FindPartitionStartIndexExclusiveBound(
const std::vector<std::string>& partitions,
const std::string& partition_key) {
if (partition_key.empty()) {
return partitions.size() - 1;
}
auto it = std::lower_bound(partitions.begin(), partitions.end(), partition_key);
if (it == partitions.end() || *it >= partition_key) {
if (it == partitions.begin()) {
return 0;
}
--it;
}
return it - partitions.begin();
}
enum WhichServerToKill {
DEAD_MASTER,
DEAD_TSERVER
};
void DoTestWriteWithDeadServer(WhichServerToKill which);
Result<NamespaceId> GetPGNamespaceId() {
master::GetNamespaceInfoResponsePB namespace_info;
RETURN_NOT_OK(client_->GetNamespaceInfo(
"" /* namespace_id */, kPgsqlKeyspaceName, YQL_DATABASE_PGSQL, &namespace_info));
return namespace_info.namespace_().id();
}
YBSchema schema_;
std::unique_ptr<MiniCluster> cluster_;
std::unique_ptr<YBClient> client_;
TableHandle client_table_;
TableHandle client_table2_;
TableHandle client_table3_;
};
const YBTableName ClientTest::kTableName(YQL_DATABASE_CQL, kKeyspaceName, "client-testtb");
const YBTableName ClientTest::kTable2Name(YQL_DATABASE_CQL, kKeyspaceName, "client-testtb2");
const YBTableName ClientTest::kTable3Name(YQL_DATABASE_CQL, kKeyspaceName, "client-testtb3");
namespace {
TableFilter MakeFilter(int32_t lower_bound, int32_t upper_bound, std::string column = "key") {
if (lower_bound != kNoBound) {
if (upper_bound != kNoBound) {
return FilterBetween(lower_bound, Inclusive::kTrue, upper_bound, Inclusive::kTrue,
std::move(column));
} else {
return FilterGreater(lower_bound, Inclusive::kTrue, std::move(column));
}
}
if (upper_bound != kNoBound) {
return FilterLess(upper_bound, Inclusive::kTrue, std::move(column));
}
return TableFilter();
}
size_t CountRowsFromClient(const TableHandle& table, YBConsistencyLevel consistency,
int32_t lower_bound, int32_t upper_bound) {
TableIteratorOptions options;
options.consistency = consistency;
options.columns = std::vector<std::string>{"key"};
options.filter = MakeFilter(lower_bound, upper_bound);
return boost::size(TableRange(table, options));
}
size_t CountRowsFromClient(const TableHandle& table, int32_t lower_bound, int32_t upper_bound) {
return CountRowsFromClient(table, YBConsistencyLevel::STRONG, lower_bound, upper_bound);
}
size_t CountRowsFromClient(const TableHandle& table) {
return CountRowsFromClient(table, kNoBound, kNoBound);
}
// Count the rows of a table, checking that the operation succeeds.
//
// Must be public to use as a thread closure.
void CheckRowCount(const TableHandle& table) {
CountRowsFromClient(table);
}
} // namespace
constexpr int kLookupWaitTimeSecs = 30;
constexpr int kNumTabletsPerTable = 8;
constexpr int kNumIterations = 1000;
class ClientTestForceMasterLookup :
public ClientTest, public ::testing::WithParamInterface<bool /* force_master_lookup */> {
public:
void SetUp() override {
ClientTest::SetUp();
// Do we want to force going to the master instead of using cache.
SetAtomicFlag(GetParam(), &FLAGS_TEST_force_master_lookup_all_tablets);
SetAtomicFlag(0.5, &FLAGS_TEST_simulate_lookup_timeout_probability);
}
void PerformManyLookups(const std::shared_ptr<YBTable>& table, bool point_lookup) {
for (int i = 0; i < kNumIterations; i++) {
if (point_lookup) {
auto key_rt = ASSERT_RESULT(LookupFirstTabletFuture(client_.get(), table).get());
ASSERT_NOTNULL(key_rt);
} else {
auto tablets = ASSERT_RESULT(client_->LookupAllTabletsFuture(
table, CoarseMonoClock::Now() + MonoDelta::FromSeconds(kLookupWaitTimeSecs)).get());
ASSERT_EQ(tablets.size(), kNumTabletsPerTable);
}
}
}
};
INSTANTIATE_TEST_CASE_P(ForceMasterLookup, ClientTestForceMasterLookup, ::testing::Bool());
TEST_P(ClientTestForceMasterLookup, TestConcurrentLookups) {
ASSERT_NO_FATALS(CreateTable(kTable3Name, kNumTabletsPerTable, &client_table3_));
std::shared_ptr<YBTable> table;
ASSERT_OK(client_->OpenTable(kTable3Name, &table));
ASSERT_OK(ASSERT_RESULT(cluster_->GetLeaderMiniMaster())->master()->
WaitUntilCatalogManagerIsLeaderAndReadyForTests());
auto t1 = std::thread([&]() { ASSERT_NO_FATALS(
PerformManyLookups(table, true /* point_lookup */)); });
auto t2 = std::thread([&]() { ASSERT_NO_FATALS(
PerformManyLookups(table, false /* point_lookup */)); });
t1.join();
t2.join();
}
TEST_F(ClientTest, TestLookupAllTablets) {
ASSERT_NO_FATALS(CreateTable(kTable3Name, kNumTabletsPerTable, &client_table3_));
std::shared_ptr<YBTable> table;
ASSERT_OK(client_->OpenTable(kTable3Name, &table));
ASSERT_OK(ASSERT_RESULT(cluster_->GetLeaderMiniMaster())->master()->
WaitUntilCatalogManagerIsLeaderAndReadyForTests());
auto future = client_->LookupAllTabletsFuture(
table, CoarseMonoClock::Now() + MonoDelta::FromSeconds(kLookupWaitTimeSecs));
auto tablets = ASSERT_RESULT(future.get());
ASSERT_EQ(tablets.size(), 8);
}
TEST_F(ClientTest, TestPointThenRangeLookup) {
ASSERT_NO_FATALS(CreateTable(kTable3Name, kNumTabletsPerTable, &client_table3_));
std::shared_ptr<YBTable> table;
ASSERT_OK(client_->OpenTable(kTable3Name, &table));
ASSERT_OK(ASSERT_RESULT(cluster_->GetLeaderMiniMaster())->master()->
WaitUntilCatalogManagerIsLeaderAndReadyForTests());
auto key_rt = ASSERT_RESULT(LookupFirstTabletFuture(client_.get(), table).get());
ASSERT_NOTNULL(key_rt);
auto tablets = ASSERT_RESULT(client_->LookupAllTabletsFuture(
table, CoarseMonoClock::Now() + MonoDelta::FromSeconds(kLookupWaitTimeSecs)).get());
ASSERT_EQ(tablets.size(), kNumTabletsPerTable);
}
// Test sanity checks in FindPartitionStartIndex
TEST_F(ClientTest, TestBadKeyRanges) {
std::vector<std::string> partition_starts;
const std::string low_key = "1111";
const std::string high_key = "9999";
// Empty partitions
ASSERT_DEATH({
FindPartitionStartIndex(partition_starts, low_key);
}, "Invalid table partition list");
// Non-empty first key
partition_starts.emplace_back("5555");
ASSERT_DEATH({
FindPartitionStartIndex(partition_starts, low_key);
}, "Invalid table partition list");
ASSERT_DEATH({
FindPartitionStartIndex(partition_starts, high_key);
}, "Invalid table partition list");
}
TEST_F(ClientTest, TestKeyRangeFiltering) {
ASSERT_NO_FATALS(CreateTable(kTable3Name, 8, &client_table3_));
std::shared_ptr<YBTable> table;
ASSERT_OK(client_->OpenTable(kTable3Name, &table));
ASSERT_OK(ASSERT_RESULT(cluster_->GetLeaderMiniMaster())->master()->
WaitUntilCatalogManagerIsLeaderAndReadyForTests());
auto tablets = ASSERT_RESULT(client_->LookupAllTabletsFuture(
table, CoarseMonoClock::Now() + MonoDelta::FromSeconds(kLookupWaitTimeSecs)).get());
// First, verify, that using empty bounds on both sides returns all tablets.
auto filtered_tablets = FilterTabletsByKeyRange(tablets, std::string(), std::string());
ASSERT_EQ(kNumTabletsPerTable, filtered_tablets.size());
std::vector<std::string> partition_starts;
for (const auto& tablet : tablets) {
partition_starts.push_back(tablet->partition().partition_key_start());
}
std::sort(partition_starts.begin(), partition_starts.end());
auto start_key = partition_starts[0];
auto end_key = partition_starts[2];
ASSERT_NO_FATALS(VerifyKeyRangeFiltering(partition_starts, tablets, start_key, end_key));
start_key = partition_starts[5];
end_key = partition_starts[7];
ASSERT_NO_FATALS(VerifyKeyRangeFiltering(partition_starts, tablets, start_key, end_key));
auto fixed_key = PartitionSchema::EncodeMultiColumnHashValue(10);
filtered_tablets = FilterTabletsByKeyRange(tablets, fixed_key, fixed_key);
ASSERT_EQ(1, filtered_tablets.size());
for (int i = 0; i < kNumIterations; i++) {
auto start_idx = RandomUniformInt<uint16_t>(0, PartitionSchema::kMaxPartitionKey - 1);
auto end_idx = RandomUniformInt<uint16_t>(start_idx + 1, PartitionSchema::kMaxPartitionKey);
ASSERT_NO_FATALS(VerifyKeyRangeFiltering(partition_starts, tablets,
PartitionSchema::EncodeMultiColumnHashValue(start_idx),
PartitionSchema::EncodeMultiColumnHashValue(end_idx)));
}
}
TEST_F(ClientTest, TestKeyRangeUpperBoundFiltering) {
ASSERT_NO_FATALS(CreateTable(kTable3Name, 8, &client_table3_));
std::shared_ptr<YBTable> table;
ASSERT_OK(client_->OpenTable(kTable3Name, &table));
ASSERT_OK(ASSERT_RESULT(cluster_->GetLeaderMiniMaster())->master()->
WaitUntilCatalogManagerIsLeaderAndReadyForTests());
auto tablets = ASSERT_RESULT(client_->LookupAllTabletsFuture(
table, CoarseMonoClock::Now() + MonoDelta::FromSeconds(kLookupWaitTimeSecs)).get());
std::vector<std::string> partitions;
partitions.reserve(tablets.size());
for (const auto& tablet : tablets) {
partitions.push_back(tablet->partition().partition_key_start());
}
std::sort(partitions.begin(), partitions.end());
// Special case: upper bound is not set, means upper bound is +Inf.
PgsqlReadRequestPB req;
auto wrapper = ASSERT_RESULT(TEST_FindPartitionKeyByUpperBound(partitions, req));
ASSERT_EQ(wrapper.get(), partitions.back());
// General cases.
for (bool is_inclusive : { true, false }) {
for (size_t idx = 0; idx < partitions.size(); ++idx) {
auto check_key = [&partitions, &req, idx, is_inclusive](const std::string& key) -> Status {
SCHECK(!key.empty(), IllegalState, "Invalid key");
req.clear_upper_bound();
req.mutable_upper_bound()->set_key(key);
req.mutable_upper_bound()->set_is_inclusive(is_inclusive);
auto* expected = &partitions[idx];
// If the key is the same as the lower partition bound and exclusive, the previous partition
// is the correct target.
if (!is_inclusive && *expected == key) {
SCHECK_GT(idx, 0, IllegalState, "Invalid partitions, first partition key must be empty");
expected = &partitions[idx - 1];
}
auto result = VERIFY_RESULT_REF(TEST_FindPartitionKeyByUpperBound(partitions, req));
SCHECK_EQ(*expected, result, IllegalState, Format(
"idx = $0, is_inclusive = $1, upper_bound = \"$2\"",
idx, is_inclusive, FormatBytesAsStr(req.upper_bound().key())));
return Status::OK();
};
// Get key and calculate bounds.
const auto& key = partitions[idx];
const uint16_t start = key.empty() ? 0 : PartitionSchema::DecodeMultiColumnHashValue(key);
const uint16_t last = (idx < partitions.size() - 1 ?
PartitionSchema::DecodeMultiColumnHashValue(partitions[idx + 1]) :
std::numeric_limits<decltype(start)>::max()) - 1;
// 1. Upper bound matches partition start.
ASSERT_OK(check_key(PartitionSchema::EncodeMultiColumnHashValue(start)));
// 2. Upper bound matches partition last key.
ASSERT_OK(check_key(PartitionSchema::EncodeMultiColumnHashValue(last)));
// 3. Upper bound matches some middle key from partition.
const auto middle = start + ((last - start) / 2);
ASSERT_OK(check_key(PartitionSchema::EncodeMultiColumnHashValue(middle)));
}
}
}
TEST_F(ClientTest, TestListTables) {
auto tables = ASSERT_RESULT(client_->ListTables("", true));
std::sort(tables.begin(), tables.end(), [](const YBTableName& n1, const YBTableName& n2) {
return n1.ToString() < n2.ToString();
});
ASSERT_EQ(2 + master::kNumSystemTablesWithTxn, tables.size());
ASSERT_EQ(kTableName, tables[0]) << "Tables:" << AsString(tables);
ASSERT_EQ(kTable2Name, tables[1]) << "Tables:" << AsString(tables);
tables.clear();
tables = ASSERT_RESULT(client_->ListTables("testtb2"));
ASSERT_EQ(1, tables.size());
ASSERT_EQ(kTable2Name, tables[0]) << "Tables:" << AsString(tables);
}
TEST_F(ClientTest, TestListTabletServers) {
auto tss = ASSERT_RESULT(client_->ListTabletServers());
ASSERT_EQ(3, tss.size());
set<string> actual_ts_uuids;
set<string> actual_ts_hostnames;
set<string> expected_ts_uuids;
set<string> expected_ts_hostnames;
for (size_t i = 0; i < tss.size(); ++i) {
auto server = cluster_->mini_tablet_server(i)->server();
expected_ts_uuids.insert(server->instance_pb().permanent_uuid());
actual_ts_uuids.insert(tss[i].uuid);
expected_ts_hostnames.insert(server->options().broadcast_addresses[0].host());
actual_ts_hostnames.insert(tss[i].hostname);
}
ASSERT_EQ(expected_ts_uuids, actual_ts_uuids);
ASSERT_EQ(expected_ts_hostnames, actual_ts_hostnames);
}
bool TableNotFound(const Status& status) {
return status.IsNotFound()
&& (master::MasterError(status) == master::MasterErrorPB::OBJECT_NOT_FOUND);
}
TEST_F(ClientTest, TestBadTable) {
shared_ptr<YBTable> t;
Status s = client_->OpenTable(
YBTableName(YQL_DATABASE_CQL, kKeyspaceName, "xxx-does-not-exist"), &t);
ASSERT_TRUE(TableNotFound(s)) << s;
}
// Test that, if the master is down, we experience a network error talking
// to it (no "find the new leader master" since there's only one master).
TEST_F(ClientTest, TestMasterDown) {
DontVerifyClusterBeforeNextTearDown();
cluster_->mini_master()->Shutdown();
shared_ptr<YBTable> t;
client_->data_->default_admin_operation_timeout_ = MonoDelta::FromSeconds(1);
Status s = client_->OpenTable(YBTableName(YQL_DATABASE_CQL, kKeyspaceName, "other-tablet"), &t);
ASSERT_TRUE(s.IsTimedOut());
}
// TODO scan with predicates is not supported.
TEST_F(ClientTest, TestScan) {
ASSERT_NO_FATALS(InsertTestRows(client_table_, FLAGS_test_scan_num_rows));
ASSERT_EQ(FLAGS_test_scan_num_rows, CountRowsFromClient(client_table_));
// Scan after insert
DoTestScanWithoutPredicates();
DoTestScanWithStringPredicate();
DoTestScanWithKeyPredicate();
// Scan after update
UpdateTestRows(client_table_, 0, FLAGS_test_scan_num_rows);
DoTestScanWithKeyPredicate();
// Scan after delete half
DeleteTestRows(client_table_, 0, FLAGS_test_scan_num_rows / 2);
DoTestScanWithKeyPredicate();
// Scan after delete all
DeleteTestRows(client_table_, FLAGS_test_scan_num_rows / 2 + 1, FLAGS_test_scan_num_rows);
DoTestScanWithKeyPredicate();
// Scan after re-insert
InsertTestRows(client_table_, 1);
DoTestScanWithKeyPredicate();
}
void CheckCounts(const TableHandle& table, const std::vector<int>& expected) {
std::vector<std::pair<int, int>> bounds = {
{ kNoBound, kNoBound },
{ kNoBound, 15 },
{ 27, kNoBound },
{ 0, 15 },
{ 0, 10 },
{ 0, 20 },
{ 0, 30 },
{ 14, 30 },
{ 30, 30 },
{ 50, kNoBound },
};
ASSERT_EQ(bounds.size(), expected.size());
for (size_t i = 0; i != bounds.size(); ++i) {
ASSERT_EQ(expected[i], CountRowsFromClient(table, bounds[i].first, bounds[i].second));
}
// Run through various scans.
}
TEST_F(ClientTest, TestScanMultiTablet) {
// 5 tablets, each with 10 rows worth of space.
TableHandle table;
ASSERT_NO_FATALS(CreateTable(YBTableName(YQL_DATABASE_CQL, "TestScanMultiTablet"), 5, &table));
// Insert rows with keys 12, 13, 15, 17, 22, 23, 25, 27...47 into each
// tablet, except the first which is empty.
auto session = CreateSession();
for (int i = 1; i < 5; i++) {
session->Apply(BuildTestRow(table, 2 + (i * 10)));
session->Apply(BuildTestRow(table, 3 + (i * 10)));
session->Apply(BuildTestRow(table, 5 + (i * 10)));
session->Apply(BuildTestRow(table, 7 + (i * 10)));
}
FlushSessionOrDie(session);
// Run through various scans.
CheckCounts(table, { 16, 3, 9, 3, 0, 4, 8, 6, 0, 0 });
// Update every other row
for (int i = 1; i < 5; ++i) {
session->Apply(UpdateTestRow(table, 2 + i * 10));
session->Apply(UpdateTestRow(table, 5 + i * 10));
}
FlushSessionOrDie(session);
// Check all counts the same (make sure updates don't change # of rows)
CheckCounts(table, { 16, 3, 9, 3, 0, 4, 8, 6, 0, 0 });
// Delete half the rows
for (int i = 1; i < 5; ++i) {
session->Apply(DeleteTestRow(table, 5 + i*10));
session->Apply(DeleteTestRow(table, 7 + i*10));
}
FlushSessionOrDie(session);
// Check counts changed accordingly
CheckCounts(table, { 8, 2, 4, 2, 0, 2, 4, 2, 0, 0 });
// Delete rest of rows
for (int i = 1; i < 5; ++i) {
session->Apply(DeleteTestRow(table, 2 + i*10));
session->Apply(DeleteTestRow(table, 3 + i*10));
}
FlushSessionOrDie(session);
// Check counts changed accordingly
CheckCounts(table, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
}
TEST_F(ClientTest, TestScanEmptyTable) {
TableIteratorOptions options;
options.columns = std::vector<std::string>();
ASSERT_EQ(boost::size(TableRange(client_table_, options)), 0);
}
// Test scanning with an empty projection. This should yield an empty
// row block with the proper number of rows filled in. Impala issues
// scans like this in order to implement COUNT(*).
TEST_F(ClientTest, TestScanEmptyProjection) {
ASSERT_NO_FATALS(InsertTestRows(client_table_, FLAGS_test_scan_num_rows));
TableIteratorOptions options;
options.columns = std::vector<std::string>();
ASSERT_EQ(boost::size(TableRange(client_table_, options)), FLAGS_test_scan_num_rows);
}
// Test a scan where we have a predicate on a key column that is not
// in the projection.
TEST_F(ClientTest, TestScanPredicateKeyColNotProjected) {
ASSERT_NO_FATALS(InsertTestRows(client_table_, FLAGS_test_scan_num_rows));
size_t nrows = 0;
TableIteratorOptions options;
options.columns = std::vector<std::string>{"key", "int_val"};
options.filter = MakeFilter(5, 10);
for (const auto& row : TableRange(client_table_, options)) {
int32_t key = row.column(0).int32_value();
int32_t val = row.column(1).int32_value();
ASSERT_EQ(key * 2, val);
++nrows;
}
ASSERT_EQ(6, nrows);
}
// Test a scan where we have a predicate on a non-key column that is
// not in the projection.
TEST_F(ClientTest, TestScanPredicateNonKeyColNotProjected) {
ASSERT_NO_FATALS(InsertTestRows(client_table_, FLAGS_test_scan_num_rows));
size_t nrows = 0;
TableIteratorOptions options;