-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathClientImpl.cpp
More file actions
1718 lines (1499 loc) · 63 KB
/
Copy pathClientImpl.cpp
File metadata and controls
1718 lines (1499 loc) · 63 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
/* This file is part of VoltDB.
* Copyright (C) 2008-2025 VoltDB Inc.
*
* 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 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.
*/
#include "ClientImpl.h"
#include <cassert>
#include "AuthenticationResponse.hpp"
#include "AuthenticationRequest.hpp"
#include <event2/buffer.h>
#include <event2/thread.h>
#include <event2/event.h>
#include <boost/foreach.hpp>
#include <sstream>
#include <openssl/err.h>
#define HIGH_WATERMARK 1024 * 1024 * 55
#define RECONNECT_INTERVAL 10
namespace voltdb {
#ifdef DEBUG_EVENTS
static bool voltdb_clientimpl_debug_init_libevent = false;
static ClientImpl* voltdb_client_singleton = NULL;
#endif
const static char* CIPHER_SUITES_TO_SET = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:"
"RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS";
const static long SSL_OPTIONS_TO_SET = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
| SSL_OP_NO_TLSv1_1;
int64_t get_sec_time() {
struct timeval tp;
int res = gettimeofday(&tp, NULL);
assert(res == 0);
return tp.tv_sec;
}
class PendingConnection {
public:
PendingConnection(const std::string& hostname, const unsigned short port, const bool keepConnecting,
struct event_base *base, ClientImpl* ci) : m_hostname(hostname),
m_port(port),
m_keepConnecting(keepConnecting),
m_base(base),
m_bufferEvent(NULL),
m_authenticationResponseLength(-1),
m_status(true),
m_loginExchangeCompleted(false),
m_startPending(-1),
m_clientImpl(ci) {
}
void initiateAuthentication(struct bufferevent *bev) {
m_clientImpl->initiateAuthentication(bev, m_hostname, m_port);
}
void finalizeAuthentication() {
return m_clientImpl->finalizeAuthentication(this);
}
void cleanupBev() {
if (m_bufferEvent) {
// if in SSL mode, the allocated SSL context for bev will
// get released by bufferevent_free
bufferevent_free(m_bufferEvent);
m_bufferEvent = NULL;
}
}
~PendingConnection() {}
/*
* Host and port of pending connection
* */
const std::string m_hostname;
const unsigned short m_port;
const bool m_keepConnecting;
/*
*Event and event base associated with connection
*/
struct event_base *m_base;
struct bufferevent *m_bufferEvent;
int32_t m_authenticationResponseLength;
AuthenticationResponse m_response;
bool m_status;
bool m_loginExchangeCompleted;
int64_t m_startPending;
ClientImpl* m_clientImpl;
};
typedef boost::shared_ptr<PendingConnection> PendingConnectionSPtr;
class CxnContext {
/*
* Data associated with a specific connection
*/
public:
CxnContext(const std::string& name, unsigned short port, int hostId) : m_name(name),
m_port(port), m_nextLength(4), m_lengthOrMessage(true), m_hostId(hostId) { }
const std::string m_name;
const unsigned short m_port;
int32_t m_nextLength;
bool m_lengthOrMessage;
int m_hostId;
};
/**
type definition for the read or write callback.
The read callback is triggered when new data arrives in the input
buffer and the amount of readable data exceed the low watermark
which is 0 by default.
The write callback is triggered if the write buffer has been
exhausted or fell below its low watermark.
@param bev the bufferevent that triggered the callback
@param ctx the user specified context for this bufferevent
*/
static void authenticationReadCallback(struct bufferevent *bev, void *ctx) {
PendingConnection *pc = reinterpret_cast<PendingConnection*>(ctx);
struct evbuffer *evbuf = bufferevent_get_input(bev);
if (pc->m_bufferEvent != bev) {
std::ostringstream os;
os << "authenticationReadCallback PC buffer event: " << pc->m_bufferEvent
<< ", bev: " << bev << " " << pc->m_hostname << ":" << pc->m_port ;
std::cerr << os.str() << std::endl;
assert(pc->m_bufferEvent == bev);
}
if (pc->m_authenticationResponseLength < 0) {
char messageLengthBytes[4];
int read = evbuffer_remove(evbuf, messageLengthBytes, 4);
assert(read == 4);
ByteBuffer messageLengthBuffer(messageLengthBytes, 4);
int32_t messageLength = messageLengthBuffer.getInt32();
assert(messageLength > 0);
assert(messageLength < 1024 * 1024);
pc->m_authenticationResponseLength = messageLength;
if (evbuffer_get_length(evbuf) < static_cast<size_t>(messageLength)) {
bufferevent_setwatermark( bev, EV_READ, static_cast<size_t>(messageLength), HIGH_WATERMARK);
return;
}
}
ScopedByteBuffer buffer(pc->m_authenticationResponseLength);
int read = evbuffer_remove(evbuf, buffer.bytes(), static_cast<size_t>(pc->m_authenticationResponseLength));
assert(read == pc->m_authenticationResponseLength);
AuthenticationResponse response = AuthenticationResponse(buffer);
if (!response.success()) {
pc->m_authenticationResponseLength =-1;
return;
}
pc->m_response = response;
pc->m_loginExchangeCompleted = true;
bufferevent_setwatermark(bev, EV_READ, 4, HIGH_WATERMARK);
pc->finalizeAuthentication();
}
/**
type definition for the error callback of a bufferevent.
The error callback is triggered if either an EOF condition or another
unrecoverable error was encountered.
@param bev the bufferevent for which the error condition was reached
@param what a conjunction of flags: BEV_EVENT_READING or BEV_EVENT_WRITING
to indicate if the error was encountered on the read or write path,
and one of the following flags: BEV_EVENT_EOF, BEV_EVENT_ERROR,
BEV_EVENT_TIMEOUT, BEV_EVENT_CONNECTED.
@param ctx the user specified context for this bufferevent
*/
static void authenticationEventCallback(struct bufferevent *bev, short events, void *ctx) {
PendingConnection *pc = reinterpret_cast<PendingConnection*>(ctx);
if (events & BEV_EVENT_CONNECTED) {
pc->initiateAuthentication(bev);
} else if (events & (BEV_EVENT_ERROR | BEV_EVENT_EOF)) {
pc->m_status = false;
if (bev) {
pc->cleanupBev();
}
}
if (pc->m_startPending < 0) {
//connection is pending from regular createConnection API
event_base_loopexit(pc->m_base, NULL);
} else {
pc->m_startPending = get_sec_time();
}
}
/**
type definition for the read or write callback.
The read callback is triggered when new data arrives in the input
buffer and the amount of readable data exceed the low watermark
which is 0 by default.
The write callback is triggered if the write buffer has been
exhausted or fell below its low watermark.
@param bev the bufferevent that triggered the callback
@param ctx the user specified context for this bufferevent
*/
static void regularReadCallback(struct bufferevent *bev, void *ctx) {
ClientImpl *impl = reinterpret_cast<ClientImpl*>(ctx);
impl->regularReadCallback(bev);
}
void wakeupPipeCallback(evutil_socket_t fd, short what, void *ctx) {
ClientImpl *impl = reinterpret_cast<ClientImpl*>(ctx);
char buf[64];
ssize_t bytesRead = read(fd, buf, sizeof buf);
(void) bytesRead;
impl->eventBaseLoopBreak();
}
static void triggerExpiredRequestsScanCB(evutil_socket_t fd, short event, void *ctx) {
ClientImpl *impl = reinterpret_cast<ClientImpl*>(ctx);
impl->triggerScanForTimeoutRequestsEvent();
}
static void scanForExpiredRequestsCB(evutil_socket_t fd, short event, void *ctx) {
ClientImpl *impl = reinterpret_cast<ClientImpl*>(ctx);
char buf[8];
ssize_t bytesRead = read(fd, buf, sizeof buf);
(void) bytesRead;
impl->purgeExpiredRequests();
}
/*
* Only has to handle the case where there is an error or EOF
*/
static void regularEventCallback(struct bufferevent *bev, short events, void *ctx) {
ClientImpl *impl = reinterpret_cast<ClientImpl*>(ctx);
impl->regularEventCallback(bev, events);
}
boost::atomic<uint32_t> ClientImpl::m_numberOfClients(0);
boost::mutex ClientImpl::m_globalResourceLock;
void initOpenSSLLib() {
SSL_library_init();
ERR_load_crypto_strings();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
}
void ClientImpl::initSslConext() throw (SSLException) {
// If global locking support for SSL is needed, which at present is not, the global
// SSL locks will need to initialized here
// allocate SSL context for the client
if (m_clientSslCtx == NULL) {
m_clientSslCtx = SSL_CTX_new(TLSv1_2_client_method());
if (m_clientSslCtx == NULL) {
throw SSLException("Failed to create and initialize ssl client context");
}
if (SSL_CTX_set_cipher_list(m_clientSslCtx, CIPHER_SUITES_TO_SET) != 1) {
std::string cipherList(CIPHER_SUITES_TO_SET);
throw SSLException("Failed to set cipher list: " + cipherList);
}
SSL_CTX_set_options(m_clientSslCtx, SSL_OPTIONS_TO_SET);
}
}
/**
type definition for the read or write callback.
The read callback is triggered when new data arrives in the input
buffer and the amount of readable data exceed the low watermark
which is 0 by default.
The write callback is triggered if the write buffer has been
exhausted or fell below its low watermark.
@param bev the bufferevent that triggered the callback
@param ctx the user specified context for this bufferevent
*/
static void regularWriteCallback(struct bufferevent *bev, void *ctx) {
ClientImpl *impl = reinterpret_cast<ClientImpl*>(ctx);
impl->regularWriteCallback(bev);
}
ClientImpl::~ClientImpl() {
bool cleanupEvp = false;
bool cleanupErrorStrings = false;
for (std::vector<struct bufferevent *>::iterator bevItr = m_bevs.begin(); bevItr != m_bevs.end(); ++bevItr) {
if (m_enableSSL) {
notifySslClose(*bevItr);
}
// if in SSL mode, the allocated SSL context for bev will
// get released by bufferevent_free
bufferevent_free(*bevItr);
}
m_bevs.clear();
m_contexts.clear();
m_callbacks.clear();
if (m_passwordHash != NULL) {
free(m_passwordHash);
cleanupEvp = true;
}
if (m_cfg != NULL) {
event_config_free(m_cfg);
}
if (m_ev != NULL) {
event_free(m_ev);
}
if (m_timerMonitorEventInitialized) {
pthread_cancel(m_queryTimeoutMonitorThread);
// cancel and free any timer events
if (m_timerMonitorEventPtr) {
if (evtimer_pending(m_timerMonitorEventPtr, NULL)) {
evtimer_del(m_timerMonitorEventPtr);
}
event_free(m_timerMonitorEventPtr);
}
// free up rest of timer management trackers
if (m_timeoutServiceEventPtr) {
event_free(m_timeoutServiceEventPtr);
}
if (m_timerMonitorBase) {
event_base_free(m_timerMonitorBase);
}
::close(m_timerCheckPipe[0]);
::close(m_timerCheckPipe[1]);
m_timerMonitorEventInitialized = false;
}
event_base_free(m_base);
if (m_wakeupPipe[1] != -1) {
::close(m_wakeupPipe[0]);
::close(m_wakeupPipe[1]);
}
if (m_enableSSL) {
if (m_clientSslCtx != NULL) {
// free clients ssl context
SSL_CTX_free(m_clientSslCtx);
m_clientSslCtx = NULL;
}
cleanupErrorStrings = true;
}
{
boost::mutex::scoped_lock lock(m_globalResourceLock);
if (--m_numberOfClients == 0) {
if (cleanupEvp) {
// release global resource allocated for generating digest/hash
EVP_cleanup();
}
if (m_enableSSL) {
// unload ssl n crypto error strings
ERR_free_strings();
}
}
}
}
// Initialization for the library that only gets called once
pthread_once_t once_initLibevent = PTHREAD_ONCE_INIT;
void initLibevent() {
int status = evthread_use_pthreads();
if (status) {
std::ostringstream msg;
msg << "Failed to initialize libevent in thread-safe mode. Error: " << status;
throw LibEventException(msg.str());
}
}
const int64_t ClientImpl::VOLT_NOTIFICATION_MAGIC_NUMBER(9223372036854775806);
const std::string ClientImpl::SERVICE("database");
class CleanupEVP_MD_Ctx{
public:
explicit CleanupEVP_MD_Ctx(EVP_MD_CTX *ctx) : m_ctx(ctx) { }
~CleanupEVP_MD_Ctx() {
if (m_ctx != NULL) {
EVP_MD_CTX_cleanup(m_ctx);
}
}
private:
EVP_MD_CTX* m_ctx;
};
void ClientImpl::hashPassword(const std::string& password) throw (MDHashException) {
const EVP_MD *md = NULL;
size_t hashDataLength;
if (m_hashScheme == HASH_SHA256) {
hashDataLength = SHA256_DIGEST_LENGTH;
md = EVP_sha256();
}
else {
throw MDHashException("The only currently-supported hash-scheme is SHA256");
}
if (md == NULL) {
throw MDHashException("Failed to get digest for SHA56");
}
unsigned int md_len = -1;
m_passwordHash = (unsigned char *) malloc(hashDataLength);
EVP_MD_CTX mdctx;
EVP_MD_CTX_init(&mdctx);
CleanupEVP_MD_Ctx cleanup(&mdctx);
if (EVP_DigestInit_ex(&mdctx, md, NULL) == 0) {
throw MDHashException("Failed to setup the digest");
}
if (EVP_DigestUpdate(&mdctx, password.c_str(), password.size()) == 0) {
throw MDHashException("Failed to generate digest hash");
}
if (EVP_DigestFinal_ex(&mdctx, m_passwordHash, &md_len) == 0) {
throw MDHashException("Failed to retrieve the digest");
}
}
#ifdef DEBUG_EVENTS
static void debugEventCallback(int severity, const char* msg) {
std::ostringstream oss;
oss << msg;
ClientLogger::CLIENT_LOG_LEVEL voltdb_severity;
switch(severity) {
case _EVENT_LOG_DEBUG:
voltdb_severity = ClientLogger::DEBUG;
break;
case _EVENT_LOG_MSG:
voltdb_severity = ClientLogger::INFO;
break;
case _EVENT_LOG_WARN:
voltdb_severity = ClientLogger::WARNING;
break;
default:
voltdb_severity = ClientLogger::ERROR;
}
voltdb_client_singleton->logMessage(voltdb_severity, oss.str());
}
#endif
ClientImpl::ClientImpl(ClientConfig config) throw (Exception, LibEventException, MDHashException, SSLException) :
m_base(NULL), m_ev(NULL), m_cfg(NULL), m_nextRequestId(INT64_MIN), m_nextConnectionIndex(0),
m_listener(config.m_listener), m_invocationBlockedOnBackpressure(false),
m_backPressuredForOutstandingRequests(false),
m_isDraining(false), m_instanceIdIsSet(false), m_outstandingRequests(0), m_leaderAddress(-1),
m_clusterStartTime(-1), m_username(config.m_username), m_passwordHash(NULL), m_maxOutstandingRequests(config.m_maxOutstandingRequests),
m_ignoreBackpressure(false), m_useClientAffinity(true),m_updateHashinator(false), m_enableAbandon(config.m_enableAbandon), m_pendingConnectionSize(0),
m_enableQueryTimeout(config.m_enableQueryTimeout), m_queryTimeoutMonitorThread(0), m_timerMonitorBase(NULL), m_timerMonitorEventPtr(NULL),
m_timeoutServiceEventPtr(NULL), m_timerMonitorEventInitialized(false), m_timedoutRequests(0), m_responseHandleNotFound(0),
m_queryExpirationTime(config.m_queryTimeout), m_scanIntervalForTimedoutQuery(config.m_scanIntervalForTimedoutQuery),
m_pLogger(0), m_hashScheme(config.m_hashScheme), m_enableSSL(config.m_useSSL), m_clientSslCtx(NULL) {
pthread_once(&once_initLibevent, initLibevent);
#ifdef DEBUG_EVENTS
if (!voltdb_clientimpl_debug_init_libevent) {
event_enable_debug_logging(EVENT_DBG_ALL);
event_enable_debug_mode();
event_set_log_callback(debugEventCallback);
assert(voltdb_client_singleton == NULL);
voltdb_client_singleton = this;
voltdb_clientimpl_debug_init_libevent = true;
}
#endif
m_cfg = event_config_new();
if (m_cfg == NULL) {
throw LibEventException("Failed to create configuration for event");
}
event_config_set_flag(m_cfg, EVENT_BASE_FLAG_NO_CACHE_TIME | EVENT_BASE_FLAG_PRECISE_TIMER);
m_base = event_base_new_with_config(m_cfg);
assert(m_base);
if (m_base == NULL) {
throw LibEventException("Failed to create and initialize main event base");
}
hashPassword(config.m_password);
m_wakeupPipe[0] = -1;
m_wakeupPipe[1] = -1;
if (m_enableQueryTimeout) {
m_timerMonitorBase = event_base_new();
if (m_timerMonitorBase == NULL) {
throw LibEventException("Failed to create and initialize event base for query-timeout monitor");
}
}
m_timerCheckPipe[0] = -1;
m_timerCheckPipe[1] = -1;
{
// Initialize the OpenSSL resources that needs to initialized only once for the process.
// When client count goes to zero, the OpenSSL library are released in destructor.
// Check client count and initialize the resources if needed
boost::mutex::scoped_lock lock(m_globalResourceLock);
if ((++m_numberOfClients == 1) && m_enableSSL) {
initOpenSSLLib();
}
}
if (m_enableSSL) {
// Initialize per client SSL context
initSslConext();
}
}
class FreeBEVOnFailure {
public:
FreeBEVOnFailure(struct bufferevent *bev) : m_pc(NULL), m_bev(bev) {}
FreeBEVOnFailure(PendingConnection *pc) : m_pc(pc), m_bev(pc->m_bufferEvent) {}
~FreeBEVOnFailure() {
if (m_bev) {
if (m_pc) {
m_pc->cleanupBev();
}
else {
bufferevent_free(m_bev);
}
}
}
void success() {
m_bev = NULL;
}
private:
PendingConnection *m_pc;
struct bufferevent *m_bev;
};
void ClientImpl::initiateConnection(boost::shared_ptr<PendingConnection> &pc) throw (ConnectException,
LibEventException,
SSLException) {
std::ostringstream ss;
ss << "ClientImpl::initiateConnection to " << pc->m_hostname << ":" << pc->m_port;
if (pc->m_bufferEvent != NULL) {
ss << ", clean up existing bev: " << pc->m_bufferEvent;
pc->cleanupBev();
}
if (m_enableSSL) {
SSL *bevSsl = SSL_new(m_clientSslCtx);
if (bevSsl == NULL) {
ss.str("");
ss << "Failed to create SSL structure for TLS/SSL connection: " << pc->m_hostname << ":" << pc->m_port;
throw SSLException(ss.str());
}
pc->m_bufferEvent = bufferevent_openssl_socket_new(m_base, -1, bevSsl, BUFFEREVENT_SSL_CONNECTING,
BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
// If dirty shutdown needs to be supported, it needs to be set here. Leaving comment as a placeholder
}
else {
pc->m_bufferEvent = bufferevent_socket_new(m_base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
}
if (pc->m_bufferEvent == NULL) {
if (pc->m_keepConnecting) {
createPendingConnection(pc->m_hostname, pc->m_port);
} else {
ss.str("");
ss << "!!!! ClientImpl::initiateConnection to " << pc->m_hostname << ":" << pc->m_port << " failed getting socket";
logMessage(ClientLogger::ERROR, ss.str());
throw ConnectException(pc->m_hostname, pc->m_port);
}
}
ss << ", new bev: " << pc->m_bufferEvent;
logMessage(ClientLogger::INFO, ss.str());
FreeBEVOnFailure protector(pc.get());
bufferevent_setcb(pc->m_bufferEvent, authenticationReadCallback, NULL, authenticationEventCallback, pc.get());
//std::cout << ss.str() << " thread-id: " << (long) pthread_self() << std::endl;
if (bufferevent_socket_connect_hostname(pc->m_bufferEvent, NULL, AF_INET, pc->m_hostname.c_str(), pc->m_port) != 0) {
if (pc->m_keepConnecting) {
//std::cout << "CI::free bev: " << pc->m_bufevent <<std::endl;
if (pc->m_bufferEvent != NULL) {
pc->cleanupBev();
}
protector.success();
createPendingConnection(pc->m_hostname, pc->m_port);
} else {
ss.str("");
ss << "!!!! ClientImpl::initiateConnection to " << pc->m_hostname << ":" << pc->m_port << " failed";
logMessage(ClientLogger::ERROR, ss.str());
throw LibEventException(ss.str());
}
}
protector.success();
}
void ClientImpl::close() {
//drain before we close;
drain();
if (m_wakeupPipe[1] != -1) {
::close(m_wakeupPipe[0]);
::close(m_wakeupPipe[1]);
}
if (m_bevs.empty()) return;
for (std::vector<struct bufferevent *>::iterator bevEntryItr = m_bevs.begin(); bevEntryItr != m_bevs.end(); ++bevEntryItr) {
if (m_enableSSL) {
notifySslClose(*bevEntryItr);
}
// if in SSL mode, the allocated SSL context for bev will
// get released by bufferevent_free
bufferevent_free(*bevEntryItr);
}
m_bevs.clear();
}
void ClientImpl::initiateAuthentication(struct bufferevent *bev, const std::string& hostname, unsigned short port) throw (LibEventException) {
logMessage(ClientLogger::DEBUG, "ClientImpl::initiateAuthentication");
FreeBEVOnFailure protector(bev);
bufferevent_setwatermark( bev, EV_READ, 4, HIGH_WATERMARK);
bufferevent_setwatermark( bev, EV_WRITE, 8192, 262144);
if (bufferevent_enable(bev, EV_READ)) {
std::ostringstream os;
os << "initiateAuthentication: failed to enable read events "<< hostname << ":" << (unsigned int) port << "; bev:" << bev;
if (m_pLogger) {
m_pLogger->log(ClientLogger::ERROR, os.str());
}
throw LibEventException(os.str());
}
AuthenticationRequest authRequest(m_username, SERVICE, m_passwordHash, m_hashScheme );
ScopedByteBuffer bb(authRequest.getSerializedSize());
authRequest.serializeTo(&bb);
struct evbuffer *evbuf = bufferevent_get_output(bev);
if (evbuffer_add( evbuf, bb.bytes(), static_cast<size_t>(bb.remaining()))) {
std::ostringstream os;
os << "initiateAuthentication: failed to add data event buffer"<< hostname << ":" << (unsigned int) port << "; bev:" << bev;
if (m_pLogger) {
m_pLogger->log(ClientLogger::ERROR, os.str());
}
throw LibEventException(os.str());
}
protector.success();
}
void ClientImpl::finalizeAuthentication(PendingConnection* pc) throw (Exception,
ConnectException) {
logMessage(ClientLogger::DEBUG, "ClientImpl::finalizeAuthentication");
FreeBEVOnFailure protector(pc);
bool pcRemoved = false;
bool exitEventLoop = false;
struct bufferevent *bev = pc->m_bufferEvent;
event_base *evBasePtr = pc->m_base;
if (pc->m_startPending < 0) {
// triggered through create connection
exitEventLoop = true;
}
if (pc->m_loginExchangeCompleted) {
logMessage(ClientLogger::DEBUG, "ClientImpl::finalizeAuthentication OK");
if (!m_instanceIdIsSet) {
m_instanceIdIsSet = true;
m_clusterStartTime = pc->m_response.getClusterStartTime();
m_leaderAddress = pc->m_response.getLeaderAddress();
} else {
if (m_clusterStartTime != pc->m_response.getClusterStartTime() ||
m_leaderAddress != pc->m_response.getLeaderAddress()) {
throw ClusterInstanceMismatchException();
}
}
//save event for host id
int hostId = pc->m_response.getHostId();
m_hostIdToEvent[hostId] = bev;
bufferevent_setwatermark( bev, EV_READ, 4, HIGH_WATERMARK);
m_bevs.push_back(bev);
// save connection information for the event
m_contexts[bev] =
boost::shared_ptr<CxnContext>(new CxnContext(pc->m_hostname, pc->m_port, hostId));
boost::shared_ptr<CallbackMap> callbackMap(new CallbackMap());
m_callbacks[bev] = callbackMap;
pc->m_bufferEvent = NULL;
bufferevent_setcb(bev,
voltdb::regularReadCallback,
voltdb::regularWriteCallback,
voltdb::regularEventCallback,
this);
{
boost::mutex::scoped_lock lock(m_pendingConnectionLock);
for (std::list<PendingConnectionSPtr>::iterator i = m_pendingConnectionList.begin();
i != m_pendingConnectionList.end();
++i) {
if (i->get() == pc) {
m_pendingConnectionList.erase(i);
m_pendingConnectionSize.store(m_pendingConnectionList.size(), boost::memory_order_release);
pcRemoved = true;
break;
}
}
}
//update topology info and procedures info
if (m_useClientAffinity) {
updateHashinator();
subscribeToTopologyNotifications();
}
std::ostringstream ss;
ss << "connectionActive " << m_contexts[bev]->m_name << ":" << m_contexts[bev]->m_port ;
logMessage(ClientLogger::INFO, ss.str());
//Notify client that a connection was active
if (m_listener.get() != NULL) {
try {
m_listener->connectionActive( m_contexts[bev]->m_name, m_bevs.size() );
} catch (const std::exception& e) {
ss.str("");
ss << "Encountered exception while reporting connection active status to listener: " << e.what() << std::endl;
logMessage(ClientLogger::ERROR, ss.str());
}
}
// set up timer thread if query timeout is enabled
if (m_timerMonitorEventInitialized == false && m_enableQueryTimeout) {
assert(m_timerCheckPipe[0] == -1);
assert(m_timerCheckPipe[1] == -1);
if (pipe(m_timerCheckPipe) == 0) {
setUpTimeoutCheckerMonitor();
m_timerMonitorEventInitialized = true;
}
else {
throw PipeCreationException();
}
}
}
else {
logMessage(ClientLogger::DEBUG, "ClientImpl::finalizeAuthentication Fail");
std::ostringstream ss;
ss << "connection failed " << " " << pc->m_hostname << ":" << pc->m_port;
logMessage(ClientLogger::ERROR, ss.str());
throw ConnectException();
}
if (exitEventLoop) {
event_base_loopexit(evBasePtr, NULL);
}
else if (!pcRemoved) {
logMessage(ClientLogger::INFO, "ClientImpl::finalizeAuthentication, update start pending time");
pc->m_startPending = get_sec_time();
}
protector.success();
}
void *timerThreadRun(void *ctx) {
ClientImpl *client = reinterpret_cast<ClientImpl*>(ctx);
client->runTimeoutMonitor();
}
void ClientImpl::runTimeoutMonitor() throw (LibEventException) {
if (event_base_dispatch(m_timerMonitorBase) == -1) {
throw LibEventException("runTimeoutMonitor: failed to run event loop for timer monitor");
} else {
//std::cout << "dispatched timer event: " << std::endl;
}
}
void ClientImpl::startMonitorThread() throw (TimerThreadException){
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);
pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
int status = pthread_create(&m_queryTimeoutMonitorThread, &threadAttr, timerThreadRun, this);
pthread_attr_destroy(&threadAttr);
if (status != 0) {
std::ostringstream os;
os << "startMonitorThread: Thread creation failed, failure code: " << status;
throw new TimerThreadException(os.str());
}
}
void ClientImpl::setUpTimeoutCheckerMonitor() throw (LibEventException){
// setup to receive timeout scan notification
m_timeoutServiceEventPtr = event_new(m_base, m_timerCheckPipe[0], EV_READ | EV_PERSIST, scanForExpiredRequestsCB, this);
if (m_timeoutServiceEventPtr == NULL) {
throw LibEventException("setUpTimeoutCheckerMonitor: failed creating timer event");
}
event_add(m_timeoutServiceEventPtr, NULL);
// setup to send timeout scan notification
m_timerMonitorEventPtr = evtimer_new(m_timerMonitorBase, triggerExpiredRequestsScanCB, this);
if (m_timerMonitorEventPtr == NULL) {
throw LibEventException("setUpTimeoutCheckerMonitor: evtimer_new failed");
}
if (evtimer_add(m_timerMonitorEventPtr, &m_scanIntervalForTimedoutQuery) != 0) {
throw LibEventException("setUpTimeoutCheckerMonitor: failed adding timeout event");
}
startMonitorThread();
}
void ClientImpl::createConnection(const std::string& hostname,
const unsigned short port,
const bool keepConnecting) throw (Exception,
ConnectException,
LibEventException,
PipeCreationException,
TimerThreadException,
SSLException) {
if (m_pLogger) {
std::ostringstream os;
os << "ClientImpl::createConnection" << " hostname:" << hostname << " port:" << port;
m_pLogger->log(ClientLogger::INFO, os.str());
}
if (0 == pipe(m_wakeupPipe)) {
if (m_ev != NULL) {
event_free(m_ev);
}
m_ev = event_new(m_base, m_wakeupPipe[0], EV_READ|EV_PERSIST, wakeupPipeCallback, this);
event_add(m_ev, NULL);
} else {
m_wakeupPipe[1] = -1;
}
PendingConnectionSPtr pc(new PendingConnection(hostname, port, keepConnecting, m_base, this));
initiateConnection(pc);
int dispatchStatus = event_base_dispatch(m_base);
if (dispatchStatus == -1) {
throw LibEventException("CreateConnection: Failed to run base loop");
}
if (pc->m_status) {
dispatchStatus = event_base_dispatch(m_base);
if (dispatchStatus == -1) {
throw LibEventException("CreateConnection: Failed to run base loop");
}
if (pc->m_loginExchangeCompleted) {
return;
}
}
if (keepConnecting) {
if (pc->m_bufferEvent != NULL) {
pc->cleanupBev();
}
createPendingConnection(hostname, port);
} else {
// if no error has been reported for the connection, back off and listen if
// any events were there to process before calling it no-connection
int retry = 0;
while (pc->m_status && retry < 5) {
++retry;
dispatchStatus = event_base_dispatch(m_base);
if (dispatchStatus == -1) {
throw LibEventException("CreateConnection: Failed to run base loop");
}
timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 10000;
nanosleep(&ts, NULL);
if (pc->m_loginExchangeCompleted) {
return;
}
}
throw ConnectException(hostname, port);
}
}
static void reconnectCallback(evutil_socket_t fd, short events, void *clientData) {
ClientImpl *self = reinterpret_cast<ClientImpl*>(clientData);
self->reconnectEventCallback();
}
void ClientImpl::reconnectEventCallback() {
if (m_pendingConnectionSize.load(boost::memory_order_consume) <= 0) return;
boost::mutex::scoped_lock lock(m_pendingConnectionLock);
const int64_t now = get_sec_time();
BOOST_FOREACH( PendingConnectionSPtr& pc, m_pendingConnectionList ) {
if ((now - pc->m_startPending) > RECONNECT_INTERVAL) {
pc->m_startPending = now;
initiateConnection(pc);
}
}
struct timeval tv;
tv.tv_sec = RECONNECT_INTERVAL;
tv.tv_usec = 0;
event_base_once(m_base, -1, EV_TIMEOUT, reconnectCallback, this, &tv);
}
void ClientImpl::createPendingConnection(const std::string &hostname, const unsigned short port, int64_t time) {
logMessage(ClientLogger::DEBUG, "ClientImpl::createPendingConnection");
PendingConnectionSPtr pc(new PendingConnection(hostname, port, false, m_base, this));
pc->m_startPending = time;
{
boost::mutex::scoped_lock lock(m_pendingConnectionLock);
m_pendingConnectionList.push_back(pc);
m_pendingConnectionSize.store(m_pendingConnectionList.size(), boost::memory_order_release);
}
struct timeval tv;
tv.tv_sec = (time > 0)? RECONNECT_INTERVAL : 0;
tv.tv_usec = 0;
event_base_once(m_base, -1, EV_TIMEOUT, reconnectCallback, this, &tv);
}
/*
* A synchronous callback returns the invocation response to the provided address
* and requests the event loop break
*/
class SyncCallback : public ProcedureCallback {
public:
SyncCallback(InvocationResponse *responseOut) : m_responseOut(responseOut) {
}
bool callback(InvocationResponse response) throw (Exception) {
(*m_responseOut) = response;
return true;
}
void abandon(AbandonReason reason) {}
private:
InvocationResponse *m_responseOut;
};
void ClientImpl::purgeExpiredRequests() {
struct timeval now;
event_base_gettimeofday_cached(m_base, &now);
BEVToCallbackMap::iterator end = m_callbacks.end();
std::vector<Table> dummyTable;
InvocationResponse response(0, STATUS_CODE_CONNECTION_TIMEOUT, "client timedout waiting for response",
STATUS_CODE_UNINITIALIZED_APP_STATUS_CODE, "No response received in allotted time",
dummyTable);
for (BEVToCallbackMap::iterator itr = m_callbacks.begin(); itr != end; ++itr) {
boost::shared_ptr<CallbackMap> callbackMap = itr->second;
for (CallbackMap::iterator cbItr = callbackMap->begin();
cbItr != callbackMap->end(); ++cbItr) {
timeval expirationTime = cbItr->second->getExpirationTime();
if (cbItr->second->isReadOnly() && (!timercmp(&expirationTime, &now, >))) {
response.setClientData(cbItr->first);
try {
cbItr->second->getCallback()->callback(response);
} catch (std::exception &excp) {
if (m_listener.get() != NULL) {
try {
m_listener->uncaughtException(excp, cbItr->second->getCallback(), response);
} catch (const std::exception &e) {
std::string str ("Uncaught exception");
logMessage(ClientLogger::ERROR, str + e.what());
}
}
}
callbackMap->erase(cbItr);
--m_outstandingRequests;
++m_timedoutRequests;
}
}
}
}
InvocationResponse ClientImpl::invoke(Procedure &proc) throw (Exception, NoConnectionsException, UninitializedParamsException, LibEventException) {
// Before making a synchronous request, process any existing requests.
while (! drain()) {}
if (m_bevs.empty()) {
throw NoConnectionsException();
}