-
Notifications
You must be signed in to change notification settings - Fork 9
/
ValuStor.hpp
1366 lines (1268 loc) · 56.2 KB
/
ValuStor.hpp
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
/*
ValuStor - Scylla DB key-value pair storage
version 1.0.3
Licensed under the MIT License
Copyright (c) 2017-2018 Sensaphone
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
*/
#ifndef VALUE_STORE_H
#define VALUE_STORE_H
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstring>
#include <deque>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
// See https://github.com/datastax/cpp-driver/releases
// This has been tested with version 2.7.1.
#include <cassandra.h>
namespace ValuStor{
typedef enum ErrorCode{
VALUE_ERROR = -9,
UNKNOWN_ERROR = -8,
BIND_ERROR = -7,
QUERY_ERROR = -6,
CONSISTENCY_ERROR = -5,
PREPARED_SELECT_FAILED = -4,
PREPARED_INSERT_FAILED = -3,
SESSION_FAILED = -2,
SUCCESS = 0,
NOT_FOUND = 1
} ErrorCode_t;
typedef enum InsertMode{
DEFAULT_BACKLOG_MODE = -1,
DISALLOW_BACKLOG = 0,
ALLOW_BACKLOG = 1,
USE_ONLY_BACKLOG = 2
} InsertMode_t;
//
// C++11 does not have C++14's make_index_sequence/make_integer_sequence.
// Manual template metaprogramming is required.
// The following is used to construct a sequence of indices.
//
// For Example:
// S<7>
// : I<{0}, S<6>>
// : I<{0}, I<{0}, S<5>>>
// : I<{0}, I<{0}, I<{0}, S<4>>>>
// : I<{0}, I<{0}, I<{0}, I<{0}, S<3>>>>>
// : I<{0}, I<{0}, I<{0}, I<{0}, I<{0}, S<2>>>>>>
// : I<{0}, I<{0}, I<{0}, I<{0}, I<{0}, I<{0}, S<1>>>>>>>
// : I<{0}, I<{0}, I<{0}, I<{0}, I<{0}, I<{0}, {0}>>>>>>
// : I<{0}, I<{0}, I<{0}, I<{0}, I<{0}, {0, 1}>>>>>
// : I<{0}, I<{0}, I<{0}, I<{0}, {0, 1, 2}>>>>
// : I<{0}, I<{0}, I<{0}, {0, 1, 2, 3}>>>
// : I<{0}, I<{0}, {0, 1, 2, 3, 4}>>
// : I<{0}, {0, 1, 2, 3, 4, 5}>
// : {0, 1, 2, 3, 4, 5, 6}
// Where,
// S = Sequencer
// I = Indexer
// {..} = Indices
//
// Usage:
// auto sequence = typename Sequencer<std::tuple_size<std::tuple<Keys...>>{}>::Indices{};
//
// The Indices are a list of {0, 1, .., n-1}
template<size_t...> struct Indices{};
// The Indexer is the "reducer", combining two sets of Indices into one set of Indices, one right after the other.
template<typename, typename> struct Indexer;
template<size_t... A, size_t... B> struct Indexer<Indices<A...>, Indices<B...>> : Indices<A...,(1+B)...>{};
// The Sequencer is the "mapper", splitting a count into two separate indices for indexing by the Indexer.
// These indices are sequenced recursively.
//
// Primary Template (recursive case):
// T=# of elements in the parent Indices
template<size_t T> struct Sequencer : Indexer<Indices<0>, typename Sequencer<T-1>::Indices>{};
//
// Specialization (base/terminating case):
template<> struct Sequencer<1> : Indices<0>{};
// ****************************************************************************************************
/// @class ValuStorUUIDGen
///
/// @brief Contains a CassUuidGen* that is used to globally generate CassUuid.
/// According to the documentation it is thread-safe and there should be one per application.
///
class ValuStorUUIDGen{
public:
CassUuidGen* const uuid_gen;
private:
ValuStorUUIDGen(void):
uuid_gen(cass_uuid_gen_new())
{}
~ValuStorUUIDGen(void){
cass_uuid_gen_free(this->uuid_gen);
}
public:
static ValuStorUUIDGen& instance(void){
static ValuStorUUIDGen generator;
return generator;
}
};
// ****************************************************************************************************
/// @class ValuStor
///
/// @brief A base object class from which all top level classes may inherit.
/// An object implements enough basic methods to support rudimentary object reflection.
///
template<typename Val_T, typename... Keys>
class ValuStor
{
public:
// ****************************************************************************************************
/// @class Result
///
class Result
{
friend class ValuStor;
public:
const ErrorCode_t error_code;
const std::string result_message;
const Val_T data;
std::vector<std::pair<Val_T, std::tuple<Keys...>>> results;
private:
// ****************************************************************************************************
/// @name Result
///
/// @brief Construct a Result object
///
Result(ErrorCode_t error_code, std::string result_message, Val_T result_data, std::tuple<Keys...>&& keys):
error_code(error_code),
result_message(result_message),
data(result_data),
results({std::make_pair(this->data, std::move(keys))})
{}
// ****************************************************************************************************
/// @name Result
///
/// @brief Construct a Result object
///
Result(ErrorCode_t error_code, std::string result_message, std::vector<std::pair<Val_T, std::tuple<Keys...>>>&& resulting_data):
error_code(error_code),
result_message(result_message),
data(resulting_data.size() > 0 ? resulting_data.at(0).first : Val_T{}),
results(std::move(resulting_data))
{}
public:
Result(void) = default;
~Result(void) = default;
Result(const Result& that) = default;
Result(Result&& that) = default;
Result& operator=(const Result&) = default;
Result& operator=(Result&&) = default;
// ****************************************************************************************************
/// @name bool()
///
/// @brief 'true' if the result was successful, 'false' if it was not.
///
explicit operator bool() const{
return this->error_code == SUCCESS;
}
};
private:
CassCluster* cluster;
CassSession* session;
const CassPrepared* prepared_insert;
std::map<size_t, const CassPrepared*> prepared_selects;
std::atomic<bool> is_initialized;
std::thread backlog_thread;
InsertMode_t default_backlog_mode;
std::vector<CassConsistency> read_consistencies;
std::vector<CassConsistency> write_consistencies;
std::atomic<bool>* do_terminate_thread_ptr;
std::shared_ptr<std::atomic<bool>> is_processing_backlog_ptr;
std::mutex* backlog_mutex_ptr;
std::deque<std::tuple<std::tuple<Keys...>,Val_T,int32_t,int64_t>>* backlog_queue_ptr;
std::vector<std::string> keys;
std::map<std::string, std::string> config;
const std::map<std::string, std::string> default_config = {
{"table", "cache.values"},
{"key_field", "key_field"},
{"value_field", "value_field"},
{"username", "username"},
{"password", "password"},
{"hosts", "127.0.0.1"},
{"port", "9042"},
{"read_consistencies", "LOCAL_QUORUM, LOCAL_ONE, ONE"},
{"write_consistencies", "LOCAL_ONE, ONE, ANY"},
{"client_io_threads", "2"},
{"client_queue_size", "8192"},
{"client_server_connects_per_thread", "1"},
{"client_max_connects_per_thread", "2"},
{"client_max_conc_connect_creation", "1"},
{"client_max_concurrent_requests", "100"},
{"client_log_level", "2"},
{"default_backlog_mode", "1"},
{"server_trusted_cert", ""},
{"server_verify_mode", "0"},
{"client_ssl_cert", ""},
{"client_ssl_key", ""},
{"client_key_password", ""}
};
private:
// ****************************************************************************************************
/// @name trim
///
/// @brief Trim the leading and trailing space from a string and return it.
///
/// @param str
///
/// @return copy of the trimmed string.
///
static std::string trim(const std::string str){
std::string s = str;
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) {
return not std::isspace(c);
}));
s.erase(std::find_if(s.rbegin(), s.rend(), [](int c) {
return not std::isspace(c);
}).base(), s.end());
return s;
} // trim()
// ****************************************************************************************************
/// @name str_to_int
///
/// @brief Convert a string to an integer, using a default value if an exception is thrown.
///
/// @param str
/// @param default_value
///
/// @return The integer value converted from the string, or the default value on an error.
///
static int str_to_int(std::string str, int default_value){
try{
return std::stoi(str);
}
catch(const std::exception& exception){
return default_value;
} // catch
} // str_to_int()
// ****************************************************************************************************
/// @name configure
///
/// @brief Configure the connection. The interal configuration must be valid.
///
void configure(void){
//
// Set the read/write consistencies
//
auto parse_consistencies = [](std::string str){
std::vector<CassConsistency> consistencies;
std::stringstream ss(str);
std::string element;
while(std::getline(ss, element, ','))
{
element = trim(element);
CassConsistency consistency = element == "ALL" ? CASS_CONSISTENCY_ALL :
element == "EACH_QUORUM" ? CASS_CONSISTENCY_EACH_QUORUM :
element == "QUORUM" ? CASS_CONSISTENCY_QUORUM :
element == "LOCAL_QUORUM" ? CASS_CONSISTENCY_LOCAL_QUORUM :
element == "ONE" ? CASS_CONSISTENCY_ONE :
element == "TWO" ? CASS_CONSISTENCY_THREE :
element == "LOCAL_ONE" ? CASS_CONSISTENCY_LOCAL_ONE :
element == "ANY" ? CASS_CONSISTENCY_ANY :
element == "SERIAL" ? CASS_CONSISTENCY_SERIAL :
element == "LOCAL_SERIAL" ? CASS_CONSISTENCY_LOCAL_SERIAL :
CASS_CONSISTENCY_UNKNOWN;
if(consistency != CASS_CONSISTENCY_UNKNOWN){
consistencies.push_back(consistency);
}
}
if(consistencies.size() == 0){
consistencies.push_back(CASS_CONSISTENCY_ANY);
}
return consistencies;
};
this->read_consistencies = parse_consistencies(config.at("read_consistencies"));
this->write_consistencies = parse_consistencies(config.at("write_consistencies"));
//
// Set the default backlog mode.
//
int backlog_mode = str_to_int(config.at("default_backlog_mode"), 1);
this->default_backlog_mode = backlog_mode == 0 ? DISALLOW_BACKLOG :
backlog_mode == 2 ? USE_ONLY_BACKLOG :
ALLOW_BACKLOG;
//
// Retrieve the keys
//
std::stringstream ss(this->config.at("key_field"));
std::string field;
while(std::getline(ss, field, ',')){
field = trim(field);
if(field != ""){
keys.push_back(field);
}
}
//
// Set the log level
//
int log_level = str_to_int(config.at("client_log_level"), 2);
cass_log_set_level(log_level == 0 ? CASS_LOG_DISABLED :
log_level == 1 ? CASS_LOG_CRITICAL :
log_level == 2 ? CASS_LOG_ERROR :
log_level == 3 ? CASS_LOG_WARN :
log_level == 4 ? CASS_LOG_INFO :
log_level == 5 ? CASS_LOG_DEBUG :
CASS_LOG_TRACE);
//
// Create the cluster profile once.
//
this->cluster = cass_cluster_new();
std::string username = config.at("username");
std::string password = config.at("password");
if(username != "" or password != ""){
cass_cluster_set_credentials(this->cluster, username.c_str(), password.c_str());
}
cass_cluster_set_contact_points(this->cluster, config.at("hosts").c_str());
cass_cluster_set_port(this->cluster, str_to_int(config.at("port"), 9042));
cass_cluster_set_num_threads_io(this->cluster, str_to_int(config.at("client_io_threads"), 2));
cass_cluster_set_queue_size_io(this->cluster, str_to_int(config.at("client_queue_size"), 8192));
cass_cluster_set_core_connections_per_host(this->cluster, str_to_int(config.at("client_server_connects_per_thread"), 1));
cass_cluster_set_max_connections_per_host(this->cluster, str_to_int(config.at("client_max_connects_per_thread"), 2));
cass_cluster_set_max_concurrent_creation(this->cluster, str_to_int(config.at("client_max_conc_connect_creation"), 1));
cass_cluster_set_max_concurrent_requests_threshold(this->cluster, str_to_int(config.at("client_max_concurrent_requests"), 100));
//
// Setup SSL (https://docs.datastax.com/en/developer/cpp-driver/2.0/topics/security/ssl/)
//
std::string server_trusted_cert = config.count("server_trusted_cert") ? config.at("server_trusted_cert") : "";
std::string client_ssl_cert = config.count("client_ssl_cert") ? config.at("client_ssl_cert") : "";
std::string client_ssl_key = config.count("client_ssl_key") ? config.at("client_ssl_key") : "";
if(server_trusted_cert != "" or
(client_ssl_cert != "" and client_ssl_key != "")){
CassSsl* ssl = cass_ssl_new();
//
// Server Certificate
//
if(server_trusted_cert != ""){
auto load_trusted_cert_file = [](const char* file, CassSsl* ssl) -> CassError{
std::ifstream input_file_stream(file);
std::stringstream string_buffer;
string_buffer << input_file_stream.rdbuf();
std::string certificate = string_buffer.str();
return cass_ssl_add_trusted_cert(ssl, certificate.c_str());
};
std::stringstream ss(server_trusted_cert);
std::string cert;
while(std::getline(ss, cert, ','))
{
cert = trim(cert);
if(cert != ""){
load_trusted_cert_file(cert.c_str(), ssl);
}
}
int verify_mode = str_to_int(config.at("server_verify_mode"), 1);
cass_ssl_set_verify_flags(ssl, verify_mode == 0 ? CASS_SSL_VERIFY_NONE :
verify_mode == 2 ? CASS_SSL_VERIFY_PEER_CERT | CASS_SSL_VERIFY_PEER_IDENTITY :
verify_mode == 3 ? CASS_SSL_VERIFY_PEER_CERT | CASS_SSL_VERIFY_PEER_IDENTITY_DNS :
CASS_SSL_VERIFY_PEER_CERT);
}
//
// Client Certificate (Authentication)
//
if(client_ssl_cert != "" and client_ssl_key != ""){
auto load_ssl_cert = [](const char* file, CassSsl* ssl) -> CassError{
std::ifstream input_file_stream(file);
std::stringstream string_buffer;
string_buffer << input_file_stream.rdbuf();
std::string certificate = string_buffer.str();
return cass_ssl_set_cert(ssl, certificate.c_str());
};
load_ssl_cert(client_ssl_cert.c_str(), ssl);
auto load_private_key = [](const char* file, CassSsl* ssl, const char* key_password) -> CassError{
std::ifstream input_file_stream(file);
std::stringstream string_buffer;
string_buffer << input_file_stream.rdbuf();
std::string certificate = string_buffer.str();
return cass_ssl_set_private_key(ssl, certificate.c_str(), key_password);
};
load_private_key(client_ssl_key.c_str(), ssl,
config.count("client_key_password") and config.at("client_key_password") != "" ?
config.at("client_key_password").c_str() : nullptr);
}
cass_cluster_set_ssl(this->cluster, ssl);
cass_ssl_free(ssl);
}
} // configure()
// ****************************************************************************************************
/// @name run_backlog_thread
///
/// @brief Run the backlog thread.
///
void run_backlog_thread(void){
//
// Start the backlog thread
//
std::atomic<bool> are_pointers_setup(false);
// *****************************************************************************
/// @name initialize
///
/// @brief Initialize the connection given a valid CassCluster* already setup.
///
auto initialize = [&](void){
this->session = cass_session_new();
if(this->session != nullptr){
CassFuture* connect_future = cass_session_connect(this->session, cluster);
if(connect_future != nullptr){
cass_future_wait_timed(connect_future, 4000000L); // Wait up to 4s
if (cass_future_error_code(connect_future) == CASS_OK) {
//
// Build the INSERT prepared statement
//
{
std::string statement = "INSERT INTO " + this->config.at("table") + " (" + this->config.at("key_field") +
", " + this->config.at("value_field") + ") VALUES (";
for(size_t ndx = 0; ndx < keys.size(); ndx++){
statement += "?,";
}
statement += "?) USING TTL ?";
CassFuture* future = cass_session_prepare(this->session, statement.c_str());
if(future != nullptr){
cass_future_wait_timed(future, 2000000L); // Wait up to 2s
if (cass_future_error_code(future) == CASS_OK) {
this->prepared_insert = cass_future_get_prepared(future);
}
else{
//
// Error: Unable to prepare insert statement
//
}
cass_future_free(future);
}
}
//
// Build the SELECT prepared statements
//
{
for(size_t total = 1; total <= keys.size(); total++){
// total == # of keys to move to the WHERE clause.
std::string statement = "SELECT " + this->config.at("value_field");
for(size_t value = total; value < keys.size(); value++){
statement += "," + keys.at(value);
}
statement += " FROM " + this->config.at("table") + " WHERE ";
for(size_t key = 0; key < total; key++){
statement += (key != 0 ? " AND " : "") + keys.at(key) + "=?";
}
CassFuture* future = cass_session_prepare(this->session, statement.c_str());
if(future != nullptr){
cass_future_wait_timed(future, 2000000L); // Wait up to 2s
if (cass_future_error_code(future) == CASS_OK) {
this->prepared_selects[total] = cass_future_get_prepared(future);
}
else{
//
// Error: Unable to prepare select statement
//
}
cass_future_free(future);
}
}
}
}
else{
//
// Error: Unable to connect
//
}
cass_future_free(connect_future);
if(this->session != nullptr and this->prepared_insert != nullptr and this->prepared_selects.size() != 0){
this->is_initialized = true;
}
else{
if(this->prepared_insert != nullptr){
cass_prepared_free(this->prepared_insert);
this->prepared_insert = nullptr;
}
for(const auto& pair : this->prepared_selects){
if(pair.second != nullptr){
cass_prepared_free(pair.second);
}
}
this->prepared_selects.clear();
}
}
if(not this->is_initialized and this->session != nullptr){
cass_session_free(this->session);
this->session = nullptr;
}
}
};
// *****************************************************************************
/// @name backlog_thread
///
/// @brief The backlog thread handles initializing the connection and manages the backlog queue.
///
this->backlog_thread = std::thread([&, initialize](void){
//
// Setup the pointers back to the master thread.
// The backlog thread will never close until the master thread tells it to close.
// At that point it can terminate after the master thread, so it must control the data to prevent seg faults.
//
std::atomic<bool> do_terminate_thread(false);
std::mutex backlog_mutex;
std::shared_ptr<std::atomic<bool>> is_processing_backlog = this->is_processing_backlog_ptr;
std::deque<std::tuple<std::tuple<Keys...>,Val_T,int32_t,int64_t>> backlog_queue;
this->do_terminate_thread_ptr = &do_terminate_thread;
this->backlog_mutex_ptr = &backlog_mutex;
this->backlog_queue_ptr = &backlog_queue;
//
// This tells the master thread that we are processing.
// It will not go out of scope until we set processing to 'false', allowing both threads to poll is_initialized without locking.
//
*is_processing_backlog = true;
//
// Notify the master thread that the pointers are setup and it is okay for 'are_pointers_setup' to go out-of-scope.
//
are_pointers_setup = true;
//
// Wait for the thread to initialize.
// During this period, the master thread cannot destruct since we are still accessing "is_initialized"
// "do_terminate_thread" must be set first.
// Once initialization takes place, we never need to access it again.
//
initialize();
while(not do_terminate_thread and not this->is_initialized){
try{
std::this_thread::sleep_for(std::chrono::seconds(1));
initialize();
}
catch(...){}
}
*is_processing_backlog = false;
while(not do_terminate_thread){
try{
std::this_thread::sleep_for(std::chrono::seconds(2));
//
// Get all the entries in the backlog so we can attempt to send them.
//
std::deque<std::tuple<std::tuple<Keys...>,Val_T,int32_t,int64_t>> backlog;
{
std::lock_guard<std::mutex> lock( backlog_mutex );
backlog = backlog_queue;
backlog_queue.clear();
*is_processing_backlog = backlog.size() > 0 and not do_terminate_thread;
}
//
// Attempt to process the backlog.
//
if(*is_processing_backlog){
std::vector<std::tuple<std::tuple<Keys...>,Val_T,int32_t,int64_t>> unprocessed;
for(auto& request : backlog){
if(not do_terminate_thread){
//
// Proxy the call to store().
// We need to unpack the tuple<Keys...> into paramters to store().
//
ValuStor::Result result = this->call_store(std::get<0>(request), // tuple<Keys...>
std::get<1>(request), // Val_T
std::get<2>(request), // TTL
DISALLOW_BACKLOG, // InsertMode
std::get<3>(request), // insert time
typename Sequencer<std::tuple_size<std::tuple<Keys...>>{}>::Indices{});
if(not result){
unprocessed.push_back(request);
}
}
}
//
// Reinsert the failed requests back into the front of the queue.
//
if(unprocessed.size() != 0){
std::lock_guard<std::mutex> lock( backlog_mutex );
if(not do_terminate_thread){
backlog_queue.insert(backlog_queue.begin(), unprocessed.begin(), unprocessed.end());
}
}
}
//
// Let the master process know that a backlog is no longer running.
//
*is_processing_backlog = false;
}
catch(...){}
}
//
// Acquire a lock one last time to ensure that the master thread isn't using the lock in the destructor.
//
{
std::lock_guard<std::mutex> lock( backlog_mutex );
}
});
//
// Wait for the thread to initialize and detach it from this thread.
//
backlog_thread.detach();
while(not are_pointers_setup){
std::this_thread::sleep_for(std::chrono::seconds(1));
}
} // run_backlog_thread()
public:
// ****************************************************************************************************
/// @name constructor
///
/// @brief Create a ValuStor, loading the configuration from the supplied configuration.
///
ValuStor(const std::map<std::string, std::string> configuration):
cluster(nullptr),
session(nullptr),
prepared_insert(nullptr),
is_initialized(false),
default_backlog_mode(ALLOW_BACKLOG),
do_terminate_thread_ptr(nullptr),
is_processing_backlog_ptr(new std::atomic<bool>(false)),
backlog_mutex_ptr(nullptr),
backlog_queue_ptr(nullptr)
{
//
// Use the configuration supplied.
//
for(const auto& pair : configuration){
std::string key = trim(pair.first);
if(this->default_config.count(key) != 0){
this->config[key] = pair.second;
}
}
//
// Add in any missing defaults
//
for(const auto& pair : this->default_config){
std::string key = trim(pair.first);
if(this->config.count(key) == 0){
this->config[key] = pair.second;
}
}
//
// Configure the connection
//
this->configure();
//
// Start the backlog thread (which will perform initialization)
//
this->run_backlog_thread();
}
// ****************************************************************************************************
/// @name constructor
///
/// @brief Create a ValuStor, loading the configuration from a file.
///
ValuStor(const std::string config_filename):
cluster(nullptr),
session(nullptr),
prepared_insert(nullptr),
is_initialized(false),
default_backlog_mode(ALLOW_BACKLOG),
do_terminate_thread_ptr(nullptr),
is_processing_backlog_ptr(new std::atomic<bool>(false)),
backlog_mutex_ptr(nullptr),
backlog_queue_ptr(nullptr)
{
//
// Load in the config
//
config = default_config;
try{
std::ifstream config_file(config_filename);
std::string line;
while(std::getline(config_file, line)){
auto comment_marker = line.find("#");
if(comment_marker != std::string::npos) {
line = line.substr(0, comment_marker);
}
auto equal_marker = line.find("=");
if(equal_marker != std::string::npos){
this->config[trim(line.substr(0, equal_marker))] = trim(line.substr(equal_marker + 1));
}
}
}
catch(const std::exception& exception){}
//
// Configure the connection
//
this->configure();
//
// Start the backlog thread (which will perform initialization)
//
this->run_backlog_thread();
}
// ****************************************************************************************************
/// @name destructor
///
/// @brief Close the connection, the backlog thread, and free up allocations.
///
///
~ValuStor(void)
{
//
// Terminate the backlog thread, but be careful as state is shared.
// By terminating the thread and clearing the queue while holding the lock, we can prevent most race conditions.
//
bool was_backlog_running = false;
{
std::lock_guard<std::mutex> lock(*this->backlog_mutex_ptr);
was_backlog_running = *this->is_processing_backlog_ptr;
this->backlog_queue_ptr->clear();
*this->do_terminate_thread_ptr = true;
}
//
// If the backlog thread was processing, we must wait for it to finish so it isn't accessing any of this' data.
// When it isn't in processing, it cannot reenter processing without knowing that "do_terminate_thread" was set.
// If the backlog was not running, it is impossible for there to be a race condition.
//
if(was_backlog_running){
while(*this->is_processing_backlog_ptr){
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
//
// Close up the cassandra connection.
//
for(const auto& pair : this->prepared_selects){
if(pair.second != nullptr){
cass_prepared_free(pair.second);
}
}
this->prepared_selects.clear();
if(this->prepared_insert != nullptr){
cass_prepared_free(this->prepared_insert);
}
if(this->session != nullptr){
cass_session_free(this->session);
}
if(this->cluster != nullptr){
cass_cluster_free(this->cluster);
}
}
private:
// ****************************************************************************************************
/// @name logFutureErrorMessage
///
static std::string logFutureErrorMessage(CassFuture* future, const std::string& description){
const char* message;
size_t message_length;
if(future != nullptr){
cass_future_error_message(future, &message, &message_length);
}
return "Scylla Error: " + description + ": '" + std::string(message, message_length) + "'";
}
public:
// ****************************************************************************************************
/// @name retrieve
///
/// @brief Get the value associated with the provided key.
///
/// @param keys
/// @param count
///
/// @return If 'result.first', the string value in 'result.second', otherwise not found.
///
ValuStor::Result retrieve(Keys... keys, size_t count = 0){
ErrorCode_t error_code = UNKNOWN_ERROR;
std::string error_message = "Scylla Error";
std::vector<std::pair<Val_T, std::tuple<Keys...>>> retrieved_data;
if(not this->is_initialized){
error_code = SESSION_FAILED;
error_message = "Scylla Error: Could not connect to server(s)";
}
else if(this->prepared_selects.size() == 0){
error_code = PREPARED_SELECT_FAILED;
error_message = "Scylla Error: Prepared Select Failed";
}
else{
//
// count = # of keys in the WHERE clause, or '0' for all.
// -----
// 1: SELECT v,k2,k3 FROM cache.tbl131 WHERE k1=?
// 2: SELECT v,k3 FROM cache.tbl131 WHERE k1=? AND k2=?
// 3: SELECT v FROM cache.tbl131 WHERE k1=? AND k2=? AND k3=?
//
auto prepared_select = this->prepared_selects.count(count) != 0 ? this->prepared_selects.at(count) :
this->prepared_selects.rbegin()->second;
CassStatement* statement = cass_prepared_bind(prepared_select);
if(statement != nullptr){
std::pair<CassError, size_t> bind_error = bind(statement, 0, keys...);
CassError error = bind_error.first;
if(error != CASS_OK and false){
error_code = BIND_ERROR;
error_message = "Scylla Error: Unable to bind parameters: " + std::string(cass_error_desc(error));
}
else{
for(const auto& level : this->read_consistencies){
error = cass_statement_set_consistency(statement, level);
if(error != CASS_OK){
error_code = CONSISTENCY_ERROR;
error_message = "Scylla Error: Unable to set statement consistency: " + std::string(cass_error_desc(error));
}
else{
CassFuture* result_future = cass_session_execute(this->session, statement);
if(result_future != nullptr){
cass_future_wait_timed(result_future, 2000000L); // Wait up to 2s
if (cass_future_error_code(result_future) != CASS_OK) {
error_code = QUERY_ERROR;
error_message = logFutureErrorMessage(result_future, "Unable to run query");
}
else{
const CassResult* cass_result = cass_future_get_result(result_future);
if(cass_result != nullptr){
size_t row_count = cass_result_row_count(cass_result);
if(row_count != 0){
CassIterator* iterator = cass_iterator_from_result(cass_result);
while (cass_iterator_next(iterator)) {
//
// We have a row of data to process
//
const CassRow* row = cass_iterator_get_row(iterator);
if (row != nullptr) {
CassError error = CASS_OK;
Val_T data_gotten{};
const CassValue* value = cass_row_get_column(row, 0);
if(value != nullptr){
error = get(value, &data_gotten); // Get the Val_T response.
if(error == CASS_OK){
error = get(row, 1, count, &keys...); // Get the Key(s) that may have optionally been SELECTed.
}
if(error == CASS_OK){
retrieved_data.push_back(std::make_pair(data_gotten, std::tuple<Keys...>(keys...)));
error_code = SUCCESS;
error_message = "Successful";
}
else{
error_code = VALUE_ERROR;
error_message = "Scylla Error: Unable to get the value: " + std::string(cass_error_desc(error));
break; // Error: Quit out.
}
}
else{
error_code = VALUE_ERROR;
error_message = "Scylla Error: Unable to get the value";
break; // Error: Quit out.
}
}
else{
error_code = NOT_FOUND;
error_message = "Error: Value Not Found";
break; // Error: Quit out.
}
}
cass_iterator_free(iterator);
}
else{
error_code = NOT_FOUND;
error_message = count == 0 or count == std::tuple_size<std::tuple<Keys...>>{} ? "Error: Value Not Found" :
"Error: Value Not Found. Did you specify the entire partition key?";
}
cass_result_free(cass_result);
cass_future_free(result_future); // Free it here, because we break out of the for loop.
break; // End in "success": No need to reduce consistency.
}
}
cass_future_free(result_future);
}
}
}
}
cass_statement_free(statement);
}
}
return ValuStor::Result(error_code, error_message, std::move(retrieved_data));
}
private:
// ****************************************************************************************************
/// @name store
///
/// @brief Internal version of store() used by the backlog.
///
template <class Tuple, size_t... IndexSequence>
ValuStor::Result call_store(Tuple t,
const Val_T& value,
int32_t seconds_ttl,
InsertMode_t insert_mode,
int64_t insert_microseconds_since_epoch,
Indices<IndexSequence...>) {
return store( std::get<IndexSequence>(t)..., value, seconds_ttl, insert_mode, insert_microseconds_since_epoch);
}
public:
// ****************************************************************************************************
/// @name store
///
/// @brief Get the value associated with the provided keys.
///
/// @param keys
/// @param value
///
/// @return 'true' if successful, 'false' otherwise.
///
ValuStor::Result store(const Keys&... keys,
const Val_T& value,
int32_t seconds_ttl = 0,
InsertMode_t insert_mode = DEFAULT_BACKLOG_MODE,