-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathdragonfly_connection.cc
2102 lines (1718 loc) · 66.8 KB
/
dragonfly_connection.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022, DragonflyDB authors. All rights reserved.
// See LICENSE for licensing terms.
//
#include "facade/dragonfly_connection.h"
#include <absl/container/flat_hash_map.h>
#include <absl/strings/match.h>
#include <absl/strings/str_cat.h>
#include <absl/time/time.h>
#include <mimalloc.h>
#include <numeric>
#include <variant>
#include "base/flags.h"
#include "base/histogram.h"
#include "base/io_buf.h"
#include "base/logging.h"
#include "core/heap_size.h"
#include "facade/conn_context.h"
#include "facade/dragonfly_listener.h"
#include "facade/memcache_parser.h"
#include "facade/redis_parser.h"
#include "facade/service_interface.h"
#include "io/file.h"
#include "util/fibers/proactor_base.h"
#ifdef DFLY_USE_SSL
#include "util/tls/tls_socket.h"
#endif
#ifdef __linux__
#include "util/fibers/uring_file.h"
#include "util/fibers/uring_proactor.h"
#include "util/fibers/uring_socket.h"
#endif
using namespace std;
using facade::operator""_MB;
ABSL_FLAG(bool, tcp_nodelay, true,
"Configures dragonfly connections with socket option TCP_NODELAY");
ABSL_FLAG(bool, primary_port_http_enabled, true,
"If true allows accessing http console on main TCP port");
ABSL_FLAG(uint16_t, admin_port, 0,
"If set, would enable admin access to console on the assigned port. "
"This supports both HTTP and RESP protocols");
ABSL_FLAG(string, admin_bind, "",
"If set, the admin consol TCP connection would be bind the given address. "
"This supports both HTTP and RESP protocols");
ABSL_FLAG(uint64_t, request_cache_limit, 64_MB,
"Amount of memory to use for request cache in bytes - per IO thread.");
ABSL_FLAG(uint64_t, pipeline_buffer_limit, 128_MB,
"Amount of memory to use for storing pipeline requests - per IO thread."
"Please note that clients that send excecissively huge pipelines, "
"may deadlock themselves. See https://github.com/dragonflydb/dragonfly/discussions/3997"
"for details.");
ABSL_FLAG(uint32_t, pipeline_queue_limit, 10000,
"Pipeline queue max length, the server will stop reading from the client socket"
" once its pipeline queue crosses this limit, and will resume once it processes "
"excessive requests. This is to prevent OOM states. Users of huge pipelines sizes "
"may require increasing this limit to prevent the risk of deadlocking."
"See https://github.com/dragonflydb/dragonfly/discussions/3997 for details");
ABSL_FLAG(uint64_t, publish_buffer_limit, 128_MB,
"Amount of memory to use for storing pub commands in bytes - per IO thread");
ABSL_FLAG(bool, no_tls_on_admin_port, false, "Allow non-tls connections on admin port");
ABSL_FLAG(uint32_t, pipeline_squash, 10,
"Number of queued pipelined commands above which squashing is enabled, 0 means disabled");
// When changing this constant, also update `test_large_cmd` test in connection_test.py.
ABSL_FLAG(uint32_t, max_multi_bulk_len, 1u << 16,
"Maximum multi-bulk (array) length that is "
"allowed to be accepted when parsing RESP protocol");
ABSL_FLAG(uint64_t, max_bulk_len, 2u << 30,
"Maximum bulk length that is "
"allowed to be accepted when parsing RESP protocol");
ABSL_FLAG(size_t, max_client_iobuf_len, 1u << 16,
"Maximum io buffer length that is used to read client requests.");
ABSL_FLAG(bool, migrate_connections, true,
"When enabled, Dragonfly will try to migrate connections to the target thread on which "
"they operate. Currently this is only supported for Lua script invocations, and can "
"happen at most once per connection.");
using namespace util;
using namespace std;
using absl::GetFlag;
using nonstd::make_unexpected;
namespace facade {
namespace {
void SendProtocolError(RedisParser::Result pres, SinkReplyBuilder* builder) {
constexpr string_view res = "-ERR Protocol error: "sv;
if (pres == RedisParser::BAD_BULKLEN) {
builder->SendProtocolError(absl::StrCat(res, "invalid bulk length"));
} else if (pres == RedisParser::BAD_ARRAYLEN) {
builder->SendProtocolError(absl::StrCat(res, "invalid multibulk length"));
} else {
builder->SendProtocolError(absl::StrCat(res, "parse error"));
}
}
// TODO: to implement correct matcher according to HTTP spec
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
// One place to find a good implementation would be https://github.com/h2o/picohttpparser
bool MatchHttp11Line(string_view line) {
return (absl::StartsWith(line, "GET ") || absl::StartsWith(line, "POST ")) &&
absl::EndsWith(line, "HTTP/1.1");
}
void UpdateIoBufCapacity(const io::IoBuf& io_buf, ConnectionStats* stats,
absl::FunctionRef<void()> f) {
const size_t prev_capacity = io_buf.Capacity();
f();
const size_t capacity = io_buf.Capacity();
if (stats != nullptr && prev_capacity != capacity) {
VLOG(2) << "Grown io_buf to " << capacity;
stats->read_buf_capacity += capacity - prev_capacity;
}
}
struct TrafficLogger {
// protects agains closing the file while writing or data races when opening the file.
// Also, makes sure that LogTraffic are executed atomically.
fb2::Mutex mutex;
unique_ptr<io::WriteFile> log_file;
void ResetLocked();
// Returns true if Write succeeded, false if it failed and the recording should be aborted.
bool Write(string_view blob);
bool Write(iovec* blobs, size_t len);
};
void TrafficLogger::ResetLocked() {
if (log_file) {
log_file->Close();
log_file.reset();
}
}
// Returns true if Write succeeded, false if it failed and the recording should be aborted.
bool TrafficLogger::Write(string_view blob) {
auto ec = log_file->Write(io::Buffer(blob));
if (ec) {
LOG(ERROR) << "Error writing to traffic log: " << ec;
ResetLocked();
return false;
}
return true;
}
bool TrafficLogger::Write(iovec* blobs, size_t len) {
auto ec = log_file->Write(blobs, len);
if (ec) {
LOG(ERROR) << "Error writing to traffic log: " << ec;
ResetLocked();
return false;
}
return true;
}
thread_local TrafficLogger tl_traffic_logger{};
thread_local base::Histogram* io_req_size_hist = nullptr;
void OpenTrafficLogger(string_view base_path) {
unique_lock lk{tl_traffic_logger.mutex};
if (tl_traffic_logger.log_file)
return;
#ifdef __linux__
// Open file with append mode, without it concurrent fiber writes seem to conflict
string path = absl::StrCat(
base_path, "-", absl::Dec(ProactorBase::me()->GetPoolIndex(), absl::kZeroPad3), ".bin");
auto file = util::fb2::OpenWrite(path, io::WriteFile::Options{/*.append = */ false});
if (!file) {
LOG(ERROR) << "Error opening a file " << path << " for traffic logging: " << file.error();
return;
}
tl_traffic_logger.log_file = unique_ptr<io::WriteFile>{file.value()};
#else
LOG(WARNING) << "Traffic logger is only supported on Linux";
#endif
// Write version, incremental numbering :)
uint8_t version[1] = {2};
tl_traffic_logger.log_file->Write(version);
}
void LogTraffic(uint32_t id, bool has_more, absl::Span<RespExpr> resp,
ServiceInterface::ContextInfo ci) {
string_view cmd = resp.front().GetView();
if (absl::EqualsIgnoreCase(cmd, "debug"sv))
return;
DVLOG(2) << "Recording " << cmd;
char stack_buf[1024];
char* next = stack_buf;
// We write id, timestamp, db_index, has_more, num_parts, part_len, part_len, part_len, ...
// And then all the part blobs concatenated together.
auto write_u32 = [&next](uint32_t i) {
absl::little_endian::Store32(next, i);
next += 4;
};
// id
write_u32(id);
// timestamp
absl::little_endian::Store64(next, absl::GetCurrentTimeNanos());
next += 8;
// db_index
write_u32(ci.db_index);
// has_more, num_parts
write_u32(has_more ? 1 : 0);
write_u32(uint32_t(resp.size()));
// Grab the lock and check if the file is still open.
lock_guard lk{tl_traffic_logger.mutex};
if (!tl_traffic_logger.log_file)
return;
// part_len, ...
for (auto part : resp) {
if (size_t(next - stack_buf + 4) > sizeof(stack_buf)) {
if (!tl_traffic_logger.Write(string_view{stack_buf, size_t(next - stack_buf)})) {
return;
}
next = stack_buf;
}
write_u32(part.GetView().size());
}
// Write the data itself.
array<iovec, 16> blobs;
unsigned index = 0;
if (next != stack_buf) {
blobs[index++] = iovec{.iov_base = stack_buf, .iov_len = size_t(next - stack_buf)};
}
for (auto part : resp) {
blobs[index++] = iovec{.iov_base = const_cast<char*>(part.GetView().data()),
.iov_len = part.GetView().size()};
if (index >= blobs.size()) {
if (!tl_traffic_logger.Write(blobs.data(), blobs.size())) {
return;
}
index = 0;
}
}
if (index) {
tl_traffic_logger.Write(blobs.data(), index);
}
}
constexpr size_t kMinReadSize = 256;
const char* kPhaseName[Connection::NUM_PHASES] = {"SETUP", "READ", "PROCESS", "SHUTTING_DOWN",
"PRECLOSE"};
// Keeps track of total per-thread sizes of dispatch queues to limit memory taken up by messages
// in these queues.
struct QueueBackpressure {
QueueBackpressure() {
}
// Block until subscriber memory usage is below limit, can be called from any thread.
void EnsureBelowLimit();
bool IsPipelineBufferOverLimit(size_t size, uint32_t q_len) const {
return size >= pipeline_buffer_limit || q_len > pipeline_queue_max_len;
}
// Used by publisher/subscriber actors to make sure we do not publish too many messages
// into the queue. Thread-safe to allow safe access in EnsureBelowLimit.
util::fb2::EventCount pubsub_ec;
atomic_size_t subscriber_bytes = 0;
// Used by pipelining/execution fiber to throttle the incoming pipeline messages.
// Used together with pipeline_buffer_limit to limit the pipeline usage per thread.
util::fb2::CondVarAny pipeline_cnd;
size_t publish_buffer_limit = 0; // cached flag publish_buffer_limit
size_t pipeline_cache_limit = 0; // cached flag pipeline_cache_limit
size_t pipeline_buffer_limit = 0; // cached flag for buffer size in bytes
uint32_t pipeline_queue_max_len = 256; // cached flag for pipeline queue max length.
};
void QueueBackpressure::EnsureBelowLimit() {
pubsub_ec.await(
[this] { return subscriber_bytes.load(memory_order_relaxed) <= publish_buffer_limit; });
}
// Global array for each io thread to keep track of the total memory usage of the dispatch queues.
QueueBackpressure* thread_queue_backpressure = nullptr;
QueueBackpressure& GetQueueBackpressure() {
DCHECK(thread_queue_backpressure != nullptr);
return thread_queue_backpressure[ProactorBase::me()->GetPoolIndex()];
}
} // namespace
thread_local vector<Connection::PipelineMessagePtr> Connection::pipeline_req_pool_;
class PipelineCacheSizeTracker {
public:
bool CheckAndUpdateWatermark(size_t pipeline_sz) {
const auto now = absl::Now();
const auto elapsed = now - last_check_;
min_ = std::min(min_, pipeline_sz);
if (elapsed < absl::Milliseconds(10)) {
return false;
}
const bool watermark_reached = (min_ > 0);
min_ = Limits::max();
last_check_ = absl::Now();
return watermark_reached;
}
private:
using Limits = std::numeric_limits<size_t>;
absl::Time last_check_ = absl::Now();
size_t min_ = Limits::max();
};
thread_local PipelineCacheSizeTracker tl_pipe_cache_sz_tracker;
void Connection::PipelineMessage::SetArgs(const RespVec& args) {
auto* next = storage.data();
for (size_t i = 0; i < args.size(); ++i) {
RespExpr::Buffer buf = args[i].GetBuf();
size_t s = buf.size();
if (s)
memcpy(next, buf.data(), s);
next[s] = '\0';
this->args[i] = MutableSlice(next, s);
next += (s + 1);
}
}
Connection::MCPipelineMessage::MCPipelineMessage(MemcacheParser::Command cmd_in,
std::string_view value_in)
: cmd{std::move(cmd_in)}, value{value_in}, backing_size{0} {
// Note: The process of laundering string_views should be placed in an utility function,
// but there are no other uses like this so far.
// Compute total size and create backing
backing_size = cmd.key.size() + value.size();
for (const auto& ext_key : cmd.keys_ext)
backing_size += ext_key.size();
backing = make_unique<char[]>(backing_size);
// Copy everything into backing
if (!cmd.key.empty())
memcpy(backing.get(), cmd.key.data(), cmd.key.size());
if (!value.empty())
memcpy(backing.get() + cmd.key.size(), value.data(), value.size());
size_t offset = cmd.key.size() + value.size();
for (const auto& ext_key : cmd.keys_ext) {
if (!ext_key.empty())
memcpy(backing.get() + offset, ext_key.data(), ext_key.size());
offset += ext_key.size();
}
// Update string_views
cmd.key = string_view{backing.get(), cmd.key.size()};
value = string_view{backing.get() + cmd.key.size(), value.size()};
offset = cmd.key.size() + value.size();
for (auto& key : cmd.keys_ext) {
key = {backing.get() + offset, key.size()};
offset += key.size();
}
}
void Connection::MessageDeleter::operator()(PipelineMessage* msg) const {
msg->~PipelineMessage();
mi_free(msg);
}
void Connection::MessageDeleter::operator()(PubMessage* msg) const {
msg->~PubMessage();
mi_free(msg);
}
void Connection::PipelineMessage::Reset(size_t nargs, size_t capacity) {
storage.resize(capacity);
args.resize(nargs);
}
size_t Connection::PipelineMessage::StorageCapacity() const {
return storage.capacity() + args.capacity();
}
size_t Connection::MessageHandle::UsedMemory() const {
struct MessageSize {
size_t operator()(const PubMessagePtr& msg) {
return sizeof(PubMessage) + (msg->channel.size() + msg->message.size());
}
size_t operator()(const PipelineMessagePtr& msg) {
return sizeof(PipelineMessage) + msg->args.capacity() * sizeof(MutableSlice) +
msg->storage.capacity();
}
size_t operator()(const MonitorMessage& msg) {
return msg.capacity();
}
size_t operator()(const AclUpdateMessagePtr& msg) {
size_t key_cap = std::accumulate(
msg->keys.key_globs.begin(), msg->keys.key_globs.end(), 0, [](auto acc, auto& str) {
return acc + (str.first.capacity() * sizeof(char)) + sizeof(str.second);
});
return sizeof(AclUpdateMessage) + msg->username.capacity() * sizeof(char) +
msg->commands.capacity() * sizeof(uint64_t) + key_cap;
}
size_t operator()(const MigrationRequestMessage& msg) {
return 0;
}
size_t operator()(const CheckpointMessage& msg) {
return 0; // no access to internal type, memory usage negligible
}
size_t operator()(const InvalidationMessage& msg) {
return 0;
}
size_t operator()(const MCPipelineMessagePtr& msg) {
return sizeof(MCPipelineMessage) + msg->backing_size +
msg->cmd.keys_ext.size() * sizeof(string_view);
}
};
return sizeof(MessageHandle) + visit(MessageSize{}, this->handle);
}
bool Connection::MessageHandle::IsReplying() const {
return IsPubMsg() || holds_alternative<MonitorMessage>(handle) ||
holds_alternative<PipelineMessagePtr>(handle) ||
(holds_alternative<MCPipelineMessagePtr>(handle) &&
!get<MCPipelineMessagePtr>(handle)->cmd.no_reply);
}
struct Connection::AsyncOperations {
AsyncOperations(SinkReplyBuilder* b, Connection* me)
: stats{&tl_facade_stats->conn_stats}, builder{b}, self(me) {
}
void operator()(const PubMessage& msg);
void operator()(PipelineMessage& msg);
void operator()(const MCPipelineMessage& msg);
void operator()(const MonitorMessage& msg);
void operator()(const AclUpdateMessage& msg);
void operator()(const MigrationRequestMessage& msg);
void operator()(CheckpointMessage msg);
void operator()(const InvalidationMessage& msg);
template <typename T, typename D> void operator()(unique_ptr<T, D>& ptr) {
operator()(*ptr.get());
}
ConnectionStats* stats = nullptr;
SinkReplyBuilder* builder = nullptr;
Connection* self = nullptr;
};
void Connection::AsyncOperations::operator()(const MonitorMessage& msg) {
RedisReplyBuilder* rbuilder = (RedisReplyBuilder*)builder;
rbuilder->SendSimpleString(msg);
}
void Connection::AsyncOperations::operator()(const AclUpdateMessage& msg) {
if (self->cntx()) {
if (msg.username == self->cntx()->authed_username) {
self->cntx()->acl_commands = msg.commands;
self->cntx()->keys = msg.keys;
self->cntx()->pub_sub = msg.pub_sub;
self->cntx()->acl_db_idx = msg.db_indx;
}
}
}
void Connection::AsyncOperations::operator()(const PubMessage& pub_msg) {
RedisReplyBuilder* rbuilder = (RedisReplyBuilder*)builder;
if (pub_msg.should_unsubscribe) {
rbuilder->StartCollection(3, RedisReplyBuilder::CollectionType::PUSH);
rbuilder->SendBulkString("unsubscribe");
rbuilder->SendBulkString(pub_msg.channel);
rbuilder->SendLong(0);
auto* cntx = self->cntx();
cntx->Unsubscribe(pub_msg.channel);
return;
}
unsigned i = 0;
array<string_view, 4> arr;
if (pub_msg.pattern.empty()) {
arr[i++] = "message";
} else {
arr[i++] = "pmessage";
arr[i++] = pub_msg.pattern;
}
arr[i++] = pub_msg.channel;
arr[i++] = pub_msg.message;
rbuilder->SendBulkStrArr(absl::Span<string_view>{arr.data(), i},
RedisReplyBuilder::CollectionType::PUSH);
}
void Connection::AsyncOperations::operator()(Connection::PipelineMessage& msg) {
DVLOG(2) << "Dispatching pipeline: " << ToSV(msg.args.front());
self->service_->DispatchCommand(CmdArgList{msg.args.data(), msg.args.size()},
self->reply_builder_.get(), self->cc_.get());
self->last_interaction_ = time(nullptr);
self->skip_next_squashing_ = false;
}
void Connection::AsyncOperations::operator()(const MCPipelineMessage& msg) {
self->service_->DispatchMC(msg.cmd, msg.value,
static_cast<MCReplyBuilder*>(self->reply_builder_.get()),
self->cc_.get());
self->last_interaction_ = time(nullptr);
}
void Connection::AsyncOperations::operator()(const MigrationRequestMessage& msg) {
// no-op
}
void Connection::AsyncOperations::operator()(CheckpointMessage msg) {
VLOG(2) << "Decremented checkpoint at " << self->DebugInfo();
msg.bc->Dec();
}
void Connection::AsyncOperations::operator()(const InvalidationMessage& msg) {
RedisReplyBuilder* rbuilder = (RedisReplyBuilder*)builder;
DCHECK(rbuilder->IsResp3());
rbuilder->StartCollection(2, facade::RedisReplyBuilder::CollectionType::PUSH);
rbuilder->SendBulkString("invalidate");
if (msg.invalidate_due_to_flush) {
rbuilder->SendNull();
} else {
string_view keys[] = {msg.key};
rbuilder->SendBulkStrArr(keys);
}
}
namespace {
thread_local absl::flat_hash_map<string, uint64_t> g_libname_ver_map;
void UpdateLibNameVerMap(const string& name, const string& ver, int delta) {
string key = absl::StrCat(name, ":", ver);
uint64_t& val = g_libname_ver_map[key];
val += delta;
if (val == 0) {
g_libname_ver_map.erase(key);
}
}
} // namespace
void Connection::Init(unsigned io_threads) {
CHECK(thread_queue_backpressure == nullptr);
thread_queue_backpressure = new QueueBackpressure[io_threads];
for (unsigned i = 0; i < io_threads; ++i) {
auto& qbp = thread_queue_backpressure[i];
qbp.publish_buffer_limit = GetFlag(FLAGS_publish_buffer_limit);
qbp.pipeline_cache_limit = GetFlag(FLAGS_request_cache_limit);
qbp.pipeline_buffer_limit = GetFlag(FLAGS_pipeline_buffer_limit);
qbp.pipeline_queue_max_len = GetFlag(FLAGS_pipeline_queue_limit);
if (qbp.publish_buffer_limit == 0 || qbp.pipeline_cache_limit == 0 ||
qbp.pipeline_buffer_limit == 0 || qbp.pipeline_queue_max_len == 0) {
LOG(ERROR) << "pipeline flag limit is 0";
exit(-1);
}
}
}
void Connection::Shutdown() {
delete[] thread_queue_backpressure;
thread_queue_backpressure = nullptr;
}
Connection::Connection(Protocol protocol, util::HttpListenerBase* http_listener, SSL_CTX* ctx,
ServiceInterface* service)
: io_buf_(kMinReadSize),
protocol_(protocol),
http_listener_(http_listener),
ssl_ctx_(ctx),
service_(service),
flags_(0) {
static atomic_uint32_t next_id{1};
constexpr size_t kReqSz = sizeof(Connection::PipelineMessage);
static_assert(kReqSz <= 256 && kReqSz >= 200);
switch (protocol) {
case Protocol::REDIS:
redis_parser_.reset(new RedisParser(RedisParser::Mode::SERVER,
GetFlag(FLAGS_max_multi_bulk_len),
GetFlag(FLAGS_max_bulk_len)));
break;
case Protocol::MEMCACHE:
memcache_parser_.reset(new MemcacheParser);
break;
}
creation_time_ = time(nullptr);
last_interaction_ = creation_time_;
id_ = next_id.fetch_add(1, memory_order_relaxed);
migration_enabled_ = GetFlag(FLAGS_migrate_connections);
// Create shared_ptr with empty value and associate it with `this` pointer (aliasing constructor).
// We use it for reference counting and accessing `this` (without managing it).
self_ = {make_shared<std::monostate>(), this};
#ifdef DFLY_USE_SSL
// Increment reference counter so Listener won't free the context while we're
// still using it.
if (ctx) {
SSL_CTX_up_ref(ctx);
}
#endif
UpdateLibNameVerMap(lib_name_, lib_ver_, +1);
}
Connection::~Connection() {
#ifdef DFLY_USE_SSL
SSL_CTX_free(ssl_ctx_);
#endif
UpdateLibNameVerMap(lib_name_, lib_ver_, -1);
}
bool Connection::IsSending() const {
return reply_builder_ && reply_builder_->IsSendActive();
}
// Called from Connection::Shutdown() right after socket_->Shutdown call.
void Connection::OnShutdown() {
VLOG(1) << "Connection::OnShutdown";
BreakOnce(POLLHUP);
}
void Connection::OnPreMigrateThread() {
DVLOG(1) << "OnPreMigrateThread " << GetClientId();
CHECK(!cc_->conn_closing);
DCHECK(!migration_in_process_);
// CancelOnErrorCb is a preemption point, so we make sure the Migration start
// is marked beforehand.
migration_in_process_ = true;
socket_->CancelOnErrorCb();
DCHECK(!async_fb_.IsJoinable()) << GetClientId();
}
void Connection::OnPostMigrateThread() {
DVLOG(1) << "[" << id_ << "] OnPostMigrateThread";
// Once we migrated, we should rearm OnBreakCb callback.
if (breaker_cb_ && socket()->IsOpen()) {
socket_->RegisterOnErrorCb([this](int32_t mask) { this->OnBreakCb(mask); });
}
migration_in_process_ = false;
DCHECK(!async_fb_.IsJoinable());
// If someone had sent Async during the migration, we must create async_fb_.
if (!dispatch_q_.empty()) {
LaunchAsyncFiberIfNeeded();
}
stats_ = &tl_facade_stats->conn_stats;
IncrNumConns();
stats_->read_buf_capacity += io_buf_.Capacity();
}
void Connection::OnConnectionStart() {
ThisFiber::SetName("DflyConnection");
stats_ = &tl_facade_stats->conn_stats;
if (const Listener* lsnr = static_cast<Listener*>(listener()); lsnr) {
is_main_ = lsnr->IsMainInterface();
}
}
void Connection::HandleRequests() {
VLOG(1) << "[" << id_ << "] HandleRequests";
if (GetFlag(FLAGS_tcp_nodelay) && !socket_->IsUDS()) {
int val = 1;
int res = setsockopt(socket_->native_handle(), IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
DCHECK_EQ(res, 0);
}
auto remote_ep = RemoteEndpointStr();
#ifdef DFLY_USE_SSL
if (ssl_ctx_) {
const bool no_tls_on_admin_port = GetFlag(FLAGS_no_tls_on_admin_port);
if (!(IsPrivileged() && no_tls_on_admin_port)) {
// Must be done atomically before the premption point in Accept so that at any
// point in time, the socket_ is defined.
uint8_t buf[2];
auto read_sz = socket_->Read(io::MutableBytes(buf));
if (!read_sz || *read_sz < sizeof(buf)) {
VLOG(1) << "Error reading from peer " << remote_ep << " " << read_sz.error().message();
return;
}
if (buf[0] != 0x16 || buf[1] != 0x03) {
VLOG(1) << "Bad TLS header "
<< absl::StrCat(absl::Hex(buf[0], absl::kZeroPad2),
absl::Hex(buf[1], absl::kZeroPad2));
socket_->Write(
io::Buffer("-ERR Bad TLS header, double check "
"if you enabled TLS for your client.\r\n"));
}
{
FiberAtomicGuard fg;
unique_ptr<tls::TlsSocket> tls_sock = make_unique<tls::TlsSocket>(std::move(socket_));
tls_sock->InitSSL(ssl_ctx_, buf);
SetSocket(tls_sock.release());
}
FiberSocketBase::AcceptResult aresult = socket_->Accept();
if (!aresult) {
LOG(INFO) << "Error handshaking " << aresult.error().message();
return;
}
is_tls_ = 1;
VLOG(1) << "TLS handshake succeeded";
}
}
#endif
io::Result<bool> http_res{false};
http_res = CheckForHttpProto();
// We need to check if the socket is open because the server might be
// shutting down. During the shutdown process, the server iterates over
// the connections of each shard and shuts down their socket. Since the
// main listener dispatches the connection into the next proactor, we
// allow a schedule order that first shuts down the socket and then calls
// this function which triggers a DCHECK on the socket while it tries to
// RegisterOnErrorCb. Furthermore, we can get away with one check here
// because both Write and Recv internally check if the socket was shut
// down and return with an error accordingly.
if (http_res && socket_->IsOpen()) {
cc_.reset(service_->CreateContext(this));
if (*http_res) {
VLOG(1) << "HTTP1.1 identified";
is_http_ = true;
HttpConnection http_conn{http_listener_};
http_conn.SetSocket(socket_.get());
http_conn.set_user_data(cc_.get());
// We validate the http request using basic-auth inside HttpConnection::HandleSingleRequest.
cc_->authenticated = true;
auto ec = http_conn.ParseFromBuffer(io_buf_.InputBuffer());
io_buf_.ConsumeInput(io_buf_.InputLen());
if (!ec) {
http_conn.HandleRequests();
}
// Release the ownership of the socket from http_conn so it would stay with
// this connection.
http_conn.ReleaseSocket();
} else { // non-http
if (breaker_cb_) {
socket_->RegisterOnErrorCb([this](int32_t mask) { this->OnBreakCb(mask); });
}
switch (protocol_) {
case Protocol::REDIS:
reply_builder_.reset(new RedisReplyBuilder(socket_.get()));
break;
case Protocol::MEMCACHE:
reply_builder_.reset(new MCReplyBuilder(socket_.get()));
break;
default:
break;
}
ConnectionFlow();
socket_->CancelOnErrorCb(); // noop if nothing is registered.
VLOG(1) << "Closed connection for peer "
<< GetClientInfo(fb2::ProactorBase::me()->GetPoolIndex());
reply_builder_.reset();
}
cc_.reset();
}
}
void Connection::RegisterBreakHook(BreakerCb breaker_cb) {
breaker_cb_ = breaker_cb;
}
pair<string, string> Connection::GetClientInfoBeforeAfterTid() const {
if (!socket_) {
LOG(DFATAL) << "unexpected null socket_ "
<< " phase " << unsigned(phase_) << ", is_http: " << unsigned(is_http_);
return {};
}
CHECK_LT(unsigned(phase_), NUM_PHASES);
string before;
auto le = LocalBindStr();
auto re = RemoteEndpointStr();
time_t now = time(nullptr);
int cpu = 0;
socklen_t len = sizeof(cpu);
getsockopt(socket_->native_handle(), SOL_SOCKET, SO_INCOMING_CPU, &cpu, &len);
#ifdef __APPLE__
int my_cpu_id = -1; // __APPLE__ does not have sched_getcpu()
#else
int my_cpu_id = sched_getcpu();
#endif
static constexpr string_view PHASE_NAMES[] = {"setup", "readsock", "process", "shutting_down",
"preclose"};
static_assert(NUM_PHASES == ABSL_ARRAYSIZE(PHASE_NAMES));
static_assert(PHASE_NAMES[SHUTTING_DOWN] == "shutting_down");
absl::StrAppend(&before, "id=", id_, " addr=", re, " laddr=", le);
absl::StrAppend(&before, " fd=", socket_->native_handle());
if (is_http_) {
absl::StrAppend(&before, " http=true");
} else {
absl::StrAppend(&before, " name=", name_);
}
string after;
absl::StrAppend(&after, " irqmatch=", int(cpu == my_cpu_id));
if (dispatch_q_.size()) {
absl::StrAppend(&after, " pipeline=", dispatch_q_.size());
}
absl::StrAppend(&after, " age=", now - creation_time_, " idle=", now - last_interaction_);
string_view phase_name = PHASE_NAMES[phase_];
if (cc_) {
string cc_info = service_->GetContextInfo(cc_.get()).Format();
// reply_builder_ may be null if the connection is in the setup phase, for example.
if (reply_builder_ && reply_builder_->IsSendActive())
phase_name = "send";
absl::StrAppend(&after, " ", cc_info);
}
absl::StrAppend(&after, " phase=", phase_name);
return {std::move(before), std::move(after)};
}
string Connection::GetClientInfo(unsigned thread_id) const {
auto [before, after] = GetClientInfoBeforeAfterTid();
absl::StrAppend(&before, " tid=", thread_id);
absl::StrAppend(&before, after);
absl::StrAppend(&before, " lib-name=", lib_name_, " lib-ver=", lib_ver_);
return before;
}
string Connection::GetClientInfo() const {
auto [before, after] = GetClientInfoBeforeAfterTid();
absl::StrAppend(&before, after);
// The following are dummy fields and users should not rely on those unless
// we decide to implement them.
// This is only done because the redis pyclient parser for the field "client-info"
// for the command ACL LOG hardcodes the expected values. This behaviour does not
// conform to the actual expected values, since it's missing half of them.
// That is, even for redis-server, issuing an ACL LOG command via redis-cli and the pyclient
// will return different results! For example, the fields:
// addr=127.0.0.1:57275
// laddr=127.0.0.1:6379
// are missing from the pyclient.
absl::StrAppend(&before, " qbuf=0 ", "qbuf-free=0 ", "obl=0 ", "argv-mem=0 ");
absl::StrAppend(&before, "oll=0 ", "omem=0 ", "tot-mem=0 ", "multi=0 ");
absl::StrAppend(&before, "psub=0 ", "sub=0");
return before;
}
uint32_t Connection::GetClientId() const {
return id_;
}
bool Connection::IsPrivileged() const {
return static_cast<Listener*>(listener())->IsPrivilegedInterface();
}
bool Connection::IsMain() const {
return is_main_;
}
bool Connection::IsMainOrMemcache() const {
if (is_main_) {
return true;
}
const Listener* lsnr = static_cast<Listener*>(listener());
return lsnr && lsnr->protocol() == Protocol::MEMCACHE;
}
void Connection::SetName(string name) {
util::ThisFiber::SetName(absl::StrCat("DflyConnection_", name));
name_ = std::move(name);
}
void Connection::SetLibName(string name) {
UpdateLibNameVerMap(lib_name_, lib_ver_, -1);
lib_name_ = std::move(name);
UpdateLibNameVerMap(lib_name_, lib_ver_, +1);
}
void Connection::SetLibVersion(string version) {
UpdateLibNameVerMap(lib_name_, lib_ver_, -1);
lib_ver_ = std::move(version);
UpdateLibNameVerMap(lib_name_, lib_ver_, +1);
}
const absl::flat_hash_map<string, uint64_t>& Connection::GetLibStatsTL() {
return g_libname_ver_map;
}
io::Result<bool> Connection::CheckForHttpProto() {
if (!IsPrivileged() && !IsMain()) {
return false;
}
const bool primary_port_enabled = GetFlag(FLAGS_primary_port_http_enabled);
if (!primary_port_enabled && !IsPrivileged()) {
return false;
}
size_t last_len = 0;
auto* peer = socket_.get();
do {
auto buf = io_buf_.AppendBuffer();
DCHECK(!buf.empty());
::io::Result<size_t> recv_sz = peer->Recv(buf);
if (!recv_sz) {
return make_unexpected(recv_sz.error());
}
io_buf_.CommitWrite(*recv_sz);
string_view ib = ToSV(io_buf_.InputBuffer());
if (ib.size() >= 2 && ib[0] == 22 && ib[1] == 3) {
// We matched the TLS handshake raw data, which means "peer" is a TCP socket.
// Reject the connection.
return make_unexpected(make_error_code(errc::protocol_not_supported));
}
ib = ib.substr(last_len);
size_t pos = ib.find('\n');
if (pos != string_view::npos) {
ib = ToSV(io_buf_.InputBuffer().first(last_len + pos));
if (ib.size() < 10 || ib.back() != '\r')
return false;
ib.remove_suffix(1);
return MatchHttp11Line(ib);
}
last_len = io_buf_.InputLen();
UpdateIoBufCapacity(io_buf_, stats_, [&]() { io_buf_.EnsureCapacity(128); });
} while (last_len < 1024);
return false;
}