-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdynamo_handler.cpp
More file actions
4520 lines (4161 loc) · 162 KB
/
dynamo_handler.cpp
File metadata and controls
4520 lines (4161 loc) · 162 KB
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
/**
* Copyright (C) 2025 EloqData Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under either of the following two licenses:
* 1. GNU Affero General Public License, version 3, as published by the Free
* Software Foundation.
* 2. GNU General Public License as published by the Free Software
* Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License or GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* and GNU General Public License V2 along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "dynamo_handler.h"
#include <aws/core/auth/AWSCredentials.h>
#include <aws/core/utils/Array.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/utils/UUID.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/dynamodb/model/BatchWriteItemRequest.h>
#include <aws/dynamodb/model/BatchWriteItemResult.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/DeleteItemRequest.h>
#include <aws/dynamodb/model/DeleteItemResult.h>
#include <aws/dynamodb/model/DeleteRequest.h>
#include <aws/dynamodb/model/DeleteTableRequest.h>
#include <aws/dynamodb/model/DeleteTableResult.h>
#include <aws/dynamodb/model/DescribeTableRequest.h>
#include <aws/dynamodb/model/DescribeTimeToLiveRequest.h>
#include <aws/dynamodb/model/DescribeTimeToLiveResult.h>
#include <aws/dynamodb/model/GetItemRequest.h>
#include <aws/dynamodb/model/ListTablesRequest.h>
#include <aws/dynamodb/model/ListTablesResult.h>
#include <aws/dynamodb/model/PutItemRequest.h>
#include <aws/dynamodb/model/PutItemResult.h>
#include <aws/dynamodb/model/QueryRequest.h>
#include <aws/dynamodb/model/QueryResult.h>
#include <aws/dynamodb/model/ScanRequest.h>
#include <aws/dynamodb/model/TimeToLiveDescription.h>
#include <aws/dynamodb/model/TimeToLiveSpecification.h>
#include <aws/dynamodb/model/TransactWriteItemsRequest.h>
#include <aws/dynamodb/model/TransactWriteItemsResult.h>
#include <aws/dynamodb/model/UpdateItemRequest.h>
#include <aws/dynamodb/model/UpdateItemResult.h>
#include <aws/dynamodb/model/UpdateTimeToLiveRequest.h>
#include <aws/dynamodb/model/UpdateTimeToLiveResult.h>
#include <algorithm> //std::min
#include <map>
#include <memory>
#include <set>
#include "kv_store.h"
#include "tx_service.h"
// #include "sequences.h"
#include "bthread/timer_thread.h"
#include "butil/string_splitter.h"
#include "dynamo_handler_typed.h"
#include "dynamo_scanner.h"
#include "tx_service/include/error_messages.h"
#include "tx_service/include/tx_record.h"
using namespace Aws::DynamoDB::Model;
// dynamo handler meter
std::unique_ptr<metrics::Meter> EloqDS::dynamo_metrics_meter;
static const metrics::Name DYNAMO_FLUSH_ROWS_COUNT_NAME_{
"dynamo_flush_rows_count"};
static const metrics::Name DYNAMO_LOAD_SLICE_DURATION_NAME_{
"dynamo_load_slice_duration"};
static const metrics::Name DYNAMO_READ_DURATION_NAME_{"dynamo_read_duration"};
typedef struct DynamoCatalog
{
std::string partition_key_;
ScalarAttributeType pk_type_;
std::string sort_key_;
ScalarAttributeType sk_type_;
} DynamoCatalog;
static const std::string dynamo_table_catalog_name = "eloqkv_tables";
static const std::string dynamo_database_catalog_name = "eloqkv_databases";
static const std::string dynamo_mvcc_archive_name = "mvcc_archives";
static const std::string dynamo_table_statistics_version_name =
"table_statistics_version";
static const std::string dynamo_table_statistics_name = "table_statistics";
static const std::string dynamo_range_table_name = "table_ranges";
static const std::string dynamo_last_range_id_name =
"table_last_range_partition_id";
static const std::string dynamo_cluster_config_name = "cluster_config";
static const std::unordered_map<std::string, DynamoCatalog> dynamo_sys_tables(
{{std::string(dynamo_table_catalog_name),
{std::string("tablename"),
ScalarAttributeType::S,
std::string(),
ScalarAttributeType::NOT_SET}},
{std::string(dynamo_database_catalog_name),
{std::string("dbname"),
ScalarAttributeType::S,
std::string(),
ScalarAttributeType::NOT_SET}},
{std::string(dynamo_mvcc_archive_name),
{std::string("tblname___key"),
ScalarAttributeType::B,
std::string("commit_ts"),
ScalarAttributeType::N}},
{std::string(dynamo_table_statistics_version_name),
{std::string("tablename"),
ScalarAttributeType::S,
std::string(),
ScalarAttributeType::NOT_SET}},
{std::string(dynamo_table_statistics_name),
{std::string("tablename"),
ScalarAttributeType::S,
std::string("version:indextype:indexname:segment_id"),
ScalarAttributeType::S}},
{std::string(dynamo_cluster_config_name),
{std::string("pk"),
ScalarAttributeType::N,
std::string(),
ScalarAttributeType::NOT_SET}}
#ifdef RANGE_PARTITION_ENABLED
,
{std::string(dynamo_range_table_name),
{std::string("tablename"),
ScalarAttributeType::S,
std::string("start_key"),
ScalarAttributeType::B}},
{std::string(dynamo_last_range_id_name),
{std::string("tablename"),
ScalarAttributeType::S,
std::string(),
ScalarAttributeType::NOT_SET}}
#endif
});
const int dynamo_api_retry = 5;
// Max batch size for BatchWrite.
const int dynamo_batch_size = 25;
// Max number of async requests sent before waiting for previous results.
const int dynamo_max_futures = 32;
// DynamoDB treat timestamps older than 5 years as invalid timestamps
// and would never expire them.
const int dynamo_no_expire_ttl = 0;
// We expire deleted items after 24 hours.
const int dynamo_expire_ttl = 86400;
static thread_local std::unique_ptr<EloqDS::PartitionFinder> partition_finder;
EloqDS::DynamoHandler::DynamoHandler(const std::string &keyspace,
const std::string &endpoint,
const std::string ®ion,
const std::string &aws_access_key_id,
const std::string &aws_secret_key,
bool bootstrap,
bool ddl_skip_kv,
int worker_pool_size,
bool skip_putall)
: keyspace_(keyspace),
is_bootstrap_(bootstrap),
ddl_skip_kv_(ddl_skip_kv),
/*sdk_options_(),*/ worker_pool_(worker_pool_size),
skip_putall_(skip_putall)
{
// This must be called before doing anything else with this library.
// Aws::InitAPI(sdk_options_);
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = region;
if (endpoint.size())
{
// Override endpoint if provided.
clientConfig.endpointOverride = endpoint;
}
clientConfig.executor =
Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>(
"dynamo-executor", 10);
if (aws_access_key_id.empty() || aws_secret_key.empty())
{
client_ = std::make_unique<Aws::DynamoDB::DynamoDBClient>(clientConfig);
}
else
{
Aws::Auth::AWSCredentials credentials(aws_access_key_id,
aws_secret_key);
client_ = std::make_unique<Aws::DynamoDB::DynamoDBClient>(credentials,
clientConfig);
}
}
EloqDS::DynamoHandler::~DynamoHandler()
{
worker_pool_.Shutdown();
// Aws::ShutdownAPI(sdk_options_);
}
/*
* @brief
* Create system tables eloqkv_databases, eloqkv_tables
* if they do not exist yet. This function should be safe to be
* called concurrently by other hosts.
*
* eloqkv_databases
* {
* dbname String (Parition Key),
* definition Binary
* }
*
* eloqkv_tables
* {
* tablename String (Partition Key),
* content Binary,
* timestamp Number,
* statistics Binary,
* kvtablename, String,
* kvindexname, Map
* }
*
* mvcc_archives
* {
* tblname___key String (Partition Key),
* commit_ts Number (Sort Key),
* commit_ts Number,
* payload_status Number,
* payload Binary
* }
*
* table_ranges
* {
* tablename String (Partition Key),
* ___mono_key___ Binary (Sort Key),
* ___partition_key___ Number,
* ___slice_keys___ List,
* ___slice_sizes___ List,
* ___version___ Number
* }
*
* table_last_range_partition_id
* {
* tablename String (Partition Key),
* last_partition_id Number
* }
*
* table_statistics
* {
* tablename String (Partition Key),
* version:indextype:indexname:segment_id String (Sort Key),
* records Number,
* samplekeys NumberSet
* }
*
* table_statistics_version
* {
* tablename String (Partition Key),
* version Number
* }
*
* cluster_config
* {
* pk Number (Partition Key),
* ngids List,
* ips List,
* ports List,
* ng_members List,
* version Number
* }
*/
bool EloqDS::DynamoHandler::Connect()
{
DescribeTableRequest dtr;
std::unordered_map<std::string, bool> sys_table_active = {
{dynamo_table_catalog_name, false},
{dynamo_database_catalog_name, false},
{dynamo_mvcc_archive_name, false}};
bool need_init = false;
for (const auto &[tablename, sys_table] : dynamo_sys_tables)
{
dtr.SetTableName(keyspace_ + '.' + tablename);
// check if sys table already exists
const DescribeTableOutcome &dtr_result = client_->DescribeTable(dtr);
if (dtr_result.IsSuccess())
{
// Check if the table is in active status
const TableStatus &status =
dtr_result.GetResult().GetTable().GetTableStatus();
if (status == TableStatus::ACTIVE)
{
sys_table_active[tablename] = true;
continue;
}
// Any status other than ACTIVE and CREATING is invalid
if (status != TableStatus::CREATING)
return false;
// Other host might be creating the table now, let's wait for them
// to complete
}
else if (dtr_result.GetError().GetErrorType() ==
Aws::DynamoDB::DynamoDBErrors::RESOURCE_NOT_FOUND)
{
need_init = true;
// Create the sys table if it doesn't exist yet
CreateTableRequest ctr;
AttributeDefinition partition_key;
partition_key.WithAttributeName(sys_table.partition_key_)
.WithAttributeType(sys_table.pk_type_);
ctr.AddAttributeDefinitions(std::move(partition_key));
KeySchemaElement pk_schema;
pk_schema.WithAttributeName(sys_table.partition_key_)
.WithKeyType(Aws::DynamoDB::Model::KeyType::HASH);
ctr.AddKeySchema(std::move(pk_schema));
ctr.SetTableName(keyspace_ + '.' + tablename);
ctr.SetBillingMode(BillingMode::PAY_PER_REQUEST);
// Add sort key if exists
if (sys_table.sort_key_.size())
{
AttributeDefinition sort_key;
sort_key.WithAttributeName(sys_table.sort_key_)
.WithAttributeType(sys_table.sk_type_);
ctr.AddAttributeDefinitions(std::move(sort_key));
KeySchemaElement sk_schema;
sk_schema.WithAttributeName(sys_table.sort_key_)
.WithKeyType(Aws::DynamoDB::Model::KeyType::RANGE);
ctr.AddKeySchema(std::move(sk_schema));
}
const CreateTableOutcome &ctr_result = client_->CreateTable(ctr);
// If the error is RESOURCE_IN_USE that means someone else just
// created this table before us. Lets wait for the table to become
// active. Otherwise the create request has failed, return false
if (!ctr_result.IsSuccess() &&
ctr_result.GetError().GetErrorType() !=
Aws::DynamoDB::DynamoDBErrors::RESOURCE_IN_USE)
{
return false;
}
}
else
{
return false;
}
}
// Create table request is an async request, verify if the tables are in
// active state if they are just created.
for (auto &[tablename, active] : sys_table_active)
{
if (active)
{
continue;
}
dtr.SetTableName(keyspace_ + '.' + tablename);
for (uint retry = 0; retry < 25; ++retry)
{
const DescribeTableOutcome &dtr_result =
client_->DescribeTable(dtr);
if (!dtr_result.IsSuccess())
{
return false;
}
if (dtr_result.GetResult().GetTable().GetTableStatus() ==
TableStatus::ACTIVE)
{
active = true;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
// Create Table failed or timed out
if (!active)
{
LOG(INFO) << "Create sys table " << tablename << " failed";
return false;
}
}
// Set TTL attribute for archive table
DynamoCatalogInfo archive_info;
archive_info.kv_table_name_ = dynamo_mvcc_archive_name;
UpdateDynamoTTL(&archive_info);
if (!archive_info.ttl_set)
{
LOG(INFO) << "Set TTL on MVCC archive table failed";
}
else
{
archive_ttl_set_ = true;
}
if (need_init && !InitPreBuiltTables())
{
return false;
}
ScheduleTimerTasks();
return true;
}
void EloqDS::DynamoHandler::ScheduleTimerTasks()
{
timer_thd_.start(nullptr);
CleanDefunctKvTables(this);
}
bool EloqDS::DynamoHandler::PutAll(std::vector<txservice::FlushRecord> &batch,
const txservice::TableName &table_name,
const txservice::TableSchema *table_schema,
uint32_t node_group)
{
if (skip_putall_)
{
LOG(INFO) << "skip PutAll, table:" << table_name.String()
<< ", batch size:" << batch.size();
return true;
}
LOG(INFO) << "PutAll begin, table:" << table_name.String()
<< ", batch size:" << batch.size();
uint64_t begin_ts = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
DynamoCatalogInfo *kv_info =
static_cast<DynamoCatalogInfo *>(table_schema->GetKVCatalogInfo());
if (!kv_info->ttl_set)
{
// Update TTL for the table if it is not set on create.
UpdateDynamoTTL(kv_info);
}
if (partition_finder == nullptr)
{
partition_finder = PartitionFinderFactory::Create();
}
#ifdef RANGE_PARTITION_ENABLED
dynamic_cast<RangePartitionFinder *>(partition_finder.get())
->Init(tx_service_, node_group);
#endif
std::vector<std::pair<uint, Partition>> target_partitions;
PartitionResultType rt =
partition_finder->FindPartitions(table_name, batch, target_partitions);
if (rt != PartitionResultType::NORMAL)
{
partition_finder->ReleaseReadLocks();
return false;
}
assert(target_partitions.size());
// Make sure each worker has decent amount of work to do.
uint worker_cnt = std::min((int) worker_pool_.WorkerPoolSize(),
(int) target_partitions.size());
uint workload = target_partitions.size() / worker_cnt;
std::mutex worker_mux;
std::condition_variable worker_cv;
uint finished_cnt = 0;
std::atomic_bool res = true;
// Assign a slice of the checkpoint vector to each worker.
for (uint i = 0; i < worker_cnt - 1; i++)
{
worker_pool_.SubmitWork(
[this,
&table_name,
&batch,
&target_partitions,
i,
workload,
table_schema,
node_group,
&worker_mux,
&worker_cv,
&finished_cnt,
&res]
{
PutAllThread(
this,
&table_name,
&batch,
(target_partitions.cbegin() + (i + 1) * workload)->first,
std::vector(
target_partitions.cbegin() + i * workload,
target_partitions.cbegin() + ((i + 1) * workload)),
table_schema,
node_group,
&res);
std::unique_lock<std::mutex> worker_lk(worker_mux);
finished_cnt++;
worker_cv.notify_one();
});
}
worker_pool_.SubmitWork(
[this,
&table_name,
&batch,
&target_partitions,
worker_cnt,
workload,
table_schema,
node_group,
&worker_mux,
&worker_cv,
&finished_cnt,
&res]
{
PutAllThread(this,
&table_name,
&batch,
batch.size(),
std::vector(target_partitions.cbegin() +
(worker_cnt - 1) * workload,
target_partitions.cend()),
table_schema,
node_group,
&res);
std::unique_lock<std::mutex> worker_lk(worker_mux);
finished_cnt++;
worker_cv.notify_one();
});
{
std::unique_lock<std::mutex> worker_lk(worker_mux);
worker_cv.wait(worker_lk,
[&finished_cnt, &worker_cnt]
{ return worker_cnt == finished_cnt; });
}
partition_finder->ReleaseReadLocks();
uint64_t end_ts = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
LOG(INFO) << "PutAll end, table:" << table_name.String()
<< ", result:" << static_cast<int>(res.load())
<< ", batch size:" << batch.size()
<< ", used time(ms):" << (end_ts - begin_ts);
return res.load();
}
/**
* @brief Worker thread function for putall/putskall. Each thread is assigned
* at least dynamo_max_futures/3 partitions and 3000 records from a single
* table. The reason that we spawned worker threads to process requests in
* parallel is that we have found request preparation phase is taking much
* more time compared to the waiting time of sent futures, thus we cannot
* completely consume the write throughput of DynamoDB with only one thread.
*
* @param handler
* @param table_name
* @param batch
* @param end
* @param target_partitions
* @param table_schema
* @param node_group
*/
void EloqDS::DynamoHandler::PutAllThread(
DynamoHandler *handler,
const txservice::TableName *table_name,
std::vector<txservice::FlushRecord> *batch,
uint32_t end,
std::vector<std::pair<uint, Partition>> target_partitions,
const txservice::TableSchema *table_schema,
uint32_t node_group,
std::atomic_bool *put_res)
{
bool putall_success = true;
std::vector<std::pair<BatchWriteItemOutcomeCallable, size_t>> flush_futures;
std::vector<std::pair<uint, uint>> partition_offset;
DynamoCatalogInfo *kv_info =
static_cast<DynamoCatalogInfo *>(table_schema->GetKVCatalogInfo());
const txservice::RecordSchema *rec_schema = table_schema->RecordSchema();
#ifdef RANGE_PARTITION_ENABLED
std::map<int32_t, const TxKey *> ranges;
#endif
const std::string *kv_table_name;
if (table_name->IsBase())
{
kv_table_name = &kv_info->kv_table_name_;
}
else
{
kv_table_name = &kv_info->kv_index_names_.at(*table_name);
}
// Set up partition offset, which is a vector that stores current idx
// in this partition, and the last idx in this partition.
for (auto part_it = target_partitions.begin();
part_it != target_partitions.end();
part_it++)
{
if (std::next(part_it) != target_partitions.end())
{
partition_offset.emplace_back(part_it->first,
std::next(part_it)->first);
}
else
{
partition_offset.emplace_back(part_it->first, end);
}
}
auto part_it = target_partitions.begin();
auto idx_it = partition_offset.begin();
Aws::Vector<WriteRequest> write_reqs;
// DynamoDB has a 1000 WCU throughput limitation on a single partition.
// In order to maximize DynamoDB throughput, we need to avoid only sending
// requests on a single partition. After sending a batch from the current
// partition, we need to move on to the next partition. We remove processed
// partitions from target_partitions so we should end up with an empty
// vector when all records in all partitions are processed.
while (target_partitions.size() &&
Sharder::Instance().LeaderTerm(node_group) > 0 &&
put_res->load(std::memory_order_acquire))
{
// When we reached the last partition, start
// from beginning again.
if (part_it == target_partitions.end())
{
part_it = target_partitions.begin();
idx_it = partition_offset.begin();
}
if (idx_it->first >= idx_it->second)
{
// Done with this partition.
part_it = target_partitions.erase(part_it);
idx_it = partition_offset.erase(idx_it);
continue;
}
assert(part_it != target_partitions.end());
assert(idx_it->first < idx_it->second);
Partition out_partition = part_it->second;
int32_t pk1 = out_partition.Pk1();
#ifdef RANGE_PARTITION_ENABLED
const txservice::TxKey *key = batch->at(idx_it->first).Key();
int32_t new_pk1 = out_partition.NewPk1(key);
assert(out_partition.RangeOwner() == node_group);
pk1 = new_pk1 == -1 ? pk1 : new_pk1;
#endif
uint64_t now = LocalCcShards::ClockTsInMillseconds();
for (; idx_it->first < idx_it->second &&
write_reqs.size() < dynamo_batch_size;
idx_it->first++)
{
using namespace txservice;
FlushRecord &ckpt_rec = batch->at(idx_it->first);
WriteRequest write_req;
if (ckpt_rec.payload_status_ != RecordStatus::Deleted &&
(!ckpt_rec.Payload()->HasTTL() ||
ckpt_rec.Payload()->GetTTL() > now))
{
AttributeValue pk, sk, version, deleted, ttl;
PutRequest put_req;
pk.SetN(pk1);
put_req.AddItem(dynamo_partition_key_attribute_name,
std::move(pk));
DynamoHandlerTyped::BindDynamoReqForKey(
sk, *ckpt_rec.Key().GetKey<EloqKV::EloqKey>());
version.SetN(std::to_string(ckpt_rec.commit_ts_));
deleted.SetBool(
ckpt_rec.payload_status_ == RecordStatus::Deleted ? true
: false);
if (ckpt_rec.payload_status_ == RecordStatus::Deleted)
{
// Set TTL on the timestamp column. Make DynamoDB delete
// this record after 24 hours. We don't need to set the rest
// of the cols since this row will become a tombstone row.
// Also the payload of ckpt record is empty.
int commit_ts_in_sec =
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::microseconds(ckpt_rec.commit_ts_))
.count();
ttl.SetN(
std::to_string(commit_ts_in_sec + dynamo_expire_ttl));
}
else
{
const txservice::TxRecord *ckpt_payload =
ckpt_rec.Payload();
// We need to specify all columns otherwise put request will
// remove unset columns from this row.
if (ckpt_payload->HasTTL())
{
int ttl_in_sec =
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::milliseconds(
ckpt_payload->GetTTL()))
.count();
ttl.SetN(ttl_in_sec);
}
else
{
ttl.SetN(dynamo_no_expire_ttl);
}
DynamoHandlerTyped::BindDynamoReqForPayload(
put_req, ckpt_payload, rec_schema, *table_name);
DynamoHandlerTyped::BindBlobFieldForUnpackInfo(
put_req, ckpt_payload);
}
put_req.AddItem(dynamo_sort_key_attribute_name, std::move(sk));
put_req.AddItem("___version___", std::move(version));
put_req.AddItem("___deleted___", std::move(deleted));
put_req.AddItem("___exp_time___", std::move(ttl));
write_req.SetPutRequest(std::move(put_req));
}
else
{
// expired or deleted keys.
AttributeValue pk, sk;
DeleteRequest del_req;
pk.SetN(pk1);
del_req.AddKey(dynamo_partition_key_attribute_name,
std::move(pk));
DynamoHandlerTyped::BindDynamoReqForKey(
sk, *ckpt_rec.Key().GetKey<EloqKV::EloqKey>());
del_req.AddKey(dynamo_sort_key_attribute_name, std::move(sk));
write_req.SetDeleteRequest(std::move(del_req));
}
write_reqs.push_back(std::move(write_req));
}
if (write_reqs.size() < dynamo_batch_size &&
target_partitions.size() > 1)
{
// Batch is not full and current partition is not the last.
continue;
}
// Send out the batch and store the future. We stop and wait for results
// for every dynamo_max_futures batch requests sent.
size_t flush_size = write_reqs.size();
assert(flush_size);
BatchWriteItemRequest batch_req;
batch_req.AddRequestItems(handler->keyspace_ + '.' + *kv_table_name,
std::move(write_reqs));
flush_futures.emplace_back(
handler->client_->BatchWriteItemCallable(std::move(batch_req)),
flush_size);
// Iterator advance
if (idx_it->first >= idx_it->second)
{
part_it = target_partitions.erase(part_it);
idx_it = partition_offset.erase(idx_it);
}
else
{
idx_it++, part_it++;
}
// Wait until all inflight requests done
if (flush_futures.size() == dynamo_max_futures ||
target_partitions.empty())
{
for (auto fut_it = flush_futures.begin();
fut_it != flush_futures.end();)
{
const BatchWriteItemOutcome &res = fut_it->first.get();
if (!res.IsSuccess() && !res.GetError().ShouldRetry())
{
put_res->compare_exchange_strong(putall_success, false);
LOG(ERROR)
<< "putall on table " << table_name->String()
<< " failed, errmsg: " << res.GetError().GetMessage();
return;
}
if (res.GetResult().GetUnprocessedItems().size() > 0 &&
!handler->RetryUnprocessedItems(res))
{
put_res->compare_exchange_strong(putall_success, false);
LOG(ERROR) << "putall on table " << table_name->String()
<< " failed.";
return;
}
if (metrics::enable_kv_metrics)
{
metrics::kv_meter->Collect(
metrics::NAME_KV_FLUSH_ROWS_TOTAL,
fut_it->second,
"base");
}
fut_it = flush_futures.erase(fut_it);
}
}
}
if (Sharder::Instance().LeaderTerm(node_group) < 0)
{
LOG(WARNING) << "DynamoHandler: leader transferred of ng#"
<< node_group;
put_res->compare_exchange_strong(putall_success, false);
}
}
/*
* @brief: DynamoHandler API for create table and drop table.
*
* This function should also handle create/drop of secondary key indexes,
* insert/delete of related catalog rows in table catalog.
* Execution result will be put in hd_res
*/
void EloqDS::DynamoHandler::UpsertTable(
const txservice::TableSchema *old_table_schema,
const txservice::TableSchema *table_schema,
txservice::OperationType op_type,
uint64_t write_time,
txservice::NodeGroupId ng_id,
int64_t tx_term,
txservice::CcHandlerResult<txservice::Void> *hd_res,
const txservice::AlterTableInfo *alter_table_info,
txservice::CcRequestBase *cc_req,
txservice::CcShard *ccs,
txservice::CcErrorCode *err_code)
{
int64_t leader_term = Sharder::Instance().TryPinNodeGroupData(ng_id);
if (leader_term < 0)
{
hd_res->SetError(CcErrorCode::TX_NODE_NOT_LEADER);
return;
}
std::shared_ptr<void> defer_unpin(
nullptr,
[ng_id](void *) { Sharder::Instance().UnpinNodeGroupData(ng_id); });
if (leader_term != tx_term)
{
hd_res->SetError(CcErrorCode::NG_TERM_CHANGED);
return;
}
const std::shared_ptr<UpsertTableData> table_data =
std::make_shared<UpsertTableData>(this,
&table_schema->GetBaseTableName(),
old_table_schema,
table_schema,
op_type,
write_time,
defer_unpin,
hd_res,
alter_table_info);
switch (op_type)
{
case txservice::OperationType::DropTable:
{
const std::string &old_kv_table_name =
static_cast<const DynamoCatalogInfo *>(
old_table_schema->GetKVCatalogInfo())
->kv_table_name_;
DropKvTableAsync(old_kv_table_name);
DeleteTableRequest fake_req;
DeleteTableResult fake_res;
DeleteTableOutcome fake_outcome(std::move(fake_res));
OnDeleteDynamoTable(client_.get(), fake_req, fake_outcome, table_data);
break;
}
case txservice::OperationType::CreateTable:
{
// Fill ./mysql/sequences table schema for Sequences::instance_
// At this point the schema operation of ./mysql/sequences is
// irrevertible and the schema will not be changed so we can safely
// install the schema here. if (table_schema->GetBaseTableName() ==
// Sequences::table_name_)
if (table_schema->GetBaseTableName() ==
DynamoHandlerTyped::sequence_table_name_)
{
// Sequences::SetTableSchema(
// static_cast<const MysqlTableSchema *>(table_schema));
DynamoHandlerTyped::SetSequenceTableSchema(table_schema);
}
CreateTableRequest ctr;
AttributeDefinition partition_key, sort_key;
// Partition key should always be the pk generated by tx_service
partition_key.WithAttributeName(dynamo_partition_key_attribute_name)
.WithAttributeType(ScalarAttributeType::N);
ctr.AddAttributeDefinitions(std::move(partition_key));
KeySchemaElement pk_schema, sk_schema;
pk_schema.WithAttributeName(dynamo_partition_key_attribute_name)
.WithKeyType(Aws::DynamoDB::Model::KeyType::HASH);
ctr.AddKeySchema(std::move(pk_schema));
// Sort key should be the binary value packed from mysql primary key
// cols
sort_key.WithAttributeName(dynamo_sort_key_attribute_name)
.WithAttributeType(ScalarAttributeType::B);
ctr.AddAttributeDefinitions(sort_key);
sk_schema.WithAttributeName(dynamo_sort_key_attribute_name)
.WithKeyType(Aws::DynamoDB::Model::KeyType::RANGE);
ctr.AddKeySchema(std::move(sk_schema));
const std::string &kv_table_name =
static_cast<const DynamoCatalogInfo *>(
table_schema->GetKVCatalogInfo())
->kv_table_name_;
ctr.SetTableName(keyspace_ + '.' + kv_table_name.data());
ctr.SetBillingMode(BillingMode::PAY_PER_REQUEST);
client_->CreateTableAsync(ctr, OnCreateDynamoTable, table_data);
break;
}
case txservice::OperationType::AddIndex:
{
assert(table_data->alter_table_info_->index_add_count_ > 0 &&
table_data->alter_table_info_->index_add_count_ ==
table_data->alter_table_info_->index_add_names_.size());
const std::shared_ptr<const UpsertTableData> new_data =
std::make_shared<const UpsertTableData>(
*table_data,
table_data->alter_table_info_->index_add_names_.cbegin());
UpsertSkTable(new_data);
break;
}
case txservice::OperationType::DropIndex:
{
assert(table_data->alter_table_info_->index_drop_count_ > 0 &&
table_data->alter_table_info_->index_drop_count_ ==
table_data->alter_table_info_->index_drop_names_.size());
const std::shared_ptr<const UpsertTableData> new_data =
std::make_shared<const UpsertTableData>(
*table_data,
table_data->alter_table_info_->index_drop_names_.cbegin(),
false);
UpsertSkTable(new_data);
break;
}
case txservice::OperationType::Update:
UpsertCatalog(table_data);
break;
case OperationType::TruncateTable:
{
const std::string &old_kv_table_name =
static_cast<const DynamoCatalogInfo *>(
old_table_schema->GetKVCatalogInfo())
->kv_table_name_;
DropKvTableAsync(old_kv_table_name);
const std::string &new_kv_table_name =
static_cast<const DynamoCatalogInfo *>(
table_schema->GetKVCatalogInfo())
->kv_table_name_;
CreateKvTableIfNotExists(new_kv_table_name);
UpsertCatalog(table_data);
break;
}
default:
LOG(INFO) << "Unsupported command for DynamoHandler::UpsertTable.";
break;
}
}
void EloqDS::DynamoHandler::OnDeleteDynamoTable(
const Aws::DynamoDB::DynamoDBClient *client,
const DeleteTableRequest &request,
const DeleteTableOutcome &result,
const std::shared_ptr<const Aws::Client::AsyncCallerContext> &context)
{
const std::shared_ptr<const UpsertTableData> table_data =
std::dynamic_pointer_cast<const UpsertTableData>(context);
assert(table_data->op_type_ == txservice::OperationType::DropTable);
if (!result.IsSuccess() &&
result.GetError().GetErrorType() !=
Aws::DynamoDB::DynamoDBErrors::RESOURCE_NOT_FOUND)
{
LOG(ERROR) << "Delete dynamo table failed, "
<< result.GetError().GetMessage();
table_data->hd_res_->SetError(CcErrorCode::DATA_STORE_ERR);
return;
}
uint index_cnt = table_data->old_table_schema_->IndexesSize();
if (index_cnt != 0)
{
// const auto *mysql_table_shema=
// static_cast<const MysqlTableSchema *>(table_data->table_schema_);
const std::unordered_map<
uint16_t,
std::pair<txservice::TableName, txservice::SecondaryKeySchema>>