-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathserver_family.cc
3457 lines (2946 loc) · 125 KB
/
server_family.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 "server/server_family.h"
#include <absl/cleanup/cleanup.h>
#include <absl/random/random.h> // for master_replid_ generation.
#include <absl/strings/match.h>
#include <absl/strings/str_join.h>
#include <absl/strings/str_replace.h>
#include <absl/strings/strip.h>
#include <croncpp.h> // cron::cronexpr
#include <sys/resource.h>
#include <sys/utsname.h>
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <optional>
#include "absl/strings/ascii.h"
#include "facade/error.h"
#include "slowlog.h"
#include "util/fibers/synchronization.h"
extern "C" {
#include "redis/redis_aux.h"
}
#include "base/flags.h"
#include "base/logging.h"
#include "core/compact_object.h"
#include "facade/cmd_arg_parser.h"
#include "facade/dragonfly_connection.h"
#include "facade/reply_builder.h"
#include "io/file_util.h"
#include "io/proc_reader.h"
#include "search/doc_index.h"
#include "server/acl/acl_commands_def.h"
#include "server/command_registry.h"
#include "server/conn_context.h"
#include "server/debugcmd.h"
#include "server/detail/save_stages_controller.h"
#include "server/detail/snapshot_storage.h"
#include "server/dflycmd.h"
#include "server/engine_shard_set.h"
#include "server/error.h"
#include "server/generic_family.h"
#include "server/journal/journal.h"
#include "server/main_service.h"
#include "server/memory_cmd.h"
#include "server/multi_command_squasher.h"
#include "server/protocol_client.h"
#include "server/rdb_load.h"
#include "server/rdb_save.h"
#include "server/script_mgr.h"
#include "server/server_state.h"
#include "server/snapshot.h"
#include "server/tiered_storage.h"
#include "server/transaction.h"
#include "server/version.h"
#include "strings/human_readable.h"
#include "util/accept_server.h"
#include "util/aws/aws.h"
using namespace std;
struct ReplicaOfFlag {
string host;
string port;
bool has_value() const {
return !host.empty() && !port.empty();
}
};
static bool AbslParseFlag(std::string_view in, ReplicaOfFlag* flag, std::string* err);
static std::string AbslUnparseFlag(const ReplicaOfFlag& flag);
struct CronExprFlag {
static constexpr std::string_view kCronPrefix = "0 "sv;
std::optional<cron::cronexpr> cron_expr;
};
static bool AbslParseFlag(std::string_view in, CronExprFlag* flag, std::string* err);
static std::string AbslUnparseFlag(const CronExprFlag& flag);
ABSL_FLAG(string, dir, "", "working directory");
ABSL_FLAG(string, dbfilename, "dump-{timestamp}",
"the filename to save/load the DB, instead of/with {timestamp} can be used {Y}, {m}, and "
"{d} macros");
ABSL_FLAG(string, requirepass, "",
"password for AUTH authentication. "
"If empty can also be set with DFLY_PASSWORD environment variable.");
ABSL_FLAG(uint32_t, maxclients, 64000, "Maximum number of concurrent clients allowed.");
ABSL_FLAG(string, save_schedule, "", "the flag is deprecated, please use snapshot_cron instead");
ABSL_FLAG(CronExprFlag, snapshot_cron, {},
"cron expression for the time to save a snapshot, crontab style");
ABSL_FLAG(bool, df_snapshot_format, true,
"if true, save in dragonfly-specific snapshotting format");
ABSL_FLAG(int, epoll_file_threads, 0,
"thread size for file workers when running in epoll mode, default is hardware concurrent "
"threads");
ABSL_FLAG(ReplicaOfFlag, replicaof, ReplicaOfFlag{},
"Specifies a host and port which point to a target master "
"to replicate. "
"Format should be <IPv4>:<PORT> or host:<PORT> or [<IPv6>]:<PORT>");
ABSL_FLAG(int32_t, slowlog_log_slower_than, 10000,
"Add commands slower than this threshold to slow log. The value is expressed in "
"microseconds and if it's negative - disables the slowlog.");
ABSL_FLAG(uint32_t, slowlog_max_len, 20, "Slow log maximum length.");
ABSL_FLAG(string, s3_endpoint, "", "endpoint for s3 snapshots, default uses aws regional endpoint");
ABSL_FLAG(bool, s3_use_https, true, "whether to use https for s3 endpoints");
// Disable EC2 metadata by default, or if a users credentials are invalid the
// AWS client will spent 30s trying to connect to inaccessable EC2 endpoints
// to load the credentials.
ABSL_FLAG(bool, s3_ec2_metadata, false,
"whether to load credentials and configuration from EC2 metadata");
// Enables S3 payload signing over HTTP. This reduces the latency and resource
// usage when writing snapshots to S3, at the expense of security.
ABSL_FLAG(bool, s3_sign_payload, true,
"whether to sign the s3 request payload when uploading snapshots");
ABSL_FLAG(bool, info_replication_valkey_compatible, true,
"when true - output valkey compatible values for info-replication");
ABSL_FLAG(bool, managed_service_info, false,
"Hides some implementation details from users when true (i.e. in managed service env)");
ABSL_DECLARE_FLAG(int32_t, port);
ABSL_DECLARE_FLAG(bool, cache_mode);
ABSL_DECLARE_FLAG(uint32_t, hz);
ABSL_DECLARE_FLAG(bool, tls);
ABSL_DECLARE_FLAG(string, tls_ca_cert_file);
ABSL_DECLARE_FLAG(string, tls_ca_cert_dir);
ABSL_DECLARE_FLAG(int, replica_priority);
ABSL_DECLARE_FLAG(double, rss_oom_deny_ratio);
bool AbslParseFlag(std::string_view in, ReplicaOfFlag* flag, std::string* err) {
#define RETURN_ON_ERROR(cond, m) \
do { \
if ((cond)) { \
*err = m; \
LOG(WARNING) << "Error in parsing arguments for --replicaof: " << m; \
return false; \
} \
} while (0)
if (in.empty()) { // on empty flag "parse" nothing. If we return false then DF exists.
*flag = ReplicaOfFlag{};
return true;
}
auto pos = in.find_last_of(':');
RETURN_ON_ERROR(pos == string::npos, "missing ':'.");
string_view ip = in.substr(0, pos);
flag->port = in.substr(pos + 1);
RETURN_ON_ERROR(ip.empty() || flag->port.empty(), "IP/host or port are empty.");
// For IPv6: ip1.front == '[' AND ip1.back == ']'
// For IPv4: ip1.front != '[' AND ip1.back != ']'
// Together, this ip1.front == '[' iff ip1.back == ']', which can be implemented as XNOR (NOT XOR)
RETURN_ON_ERROR(((ip.front() == '[') ^ (ip.back() == ']')), "unclosed brackets.");
if (ip.front() == '[') {
// shortest possible IPv6 is '::1' (loopback)
RETURN_ON_ERROR(ip.length() <= 2, "IPv6 host name is too short");
flag->host = ip.substr(1, ip.length() - 2);
} else {
flag->host = ip;
}
VLOG(1) << "--replicaof: Received " << flag->host << " : " << flag->port;
return true;
#undef RETURN_ON_ERROR
}
std::string AbslUnparseFlag(const ReplicaOfFlag& flag) {
return (flag.has_value()) ? absl::StrCat(flag.host, ":", flag.port) : "";
}
bool AbslParseFlag(std::string_view in, CronExprFlag* flag, std::string* err) {
if (in.empty()) {
flag->cron_expr = std::nullopt;
return true;
}
if (absl::StartsWith(in, "\"")) {
*err = absl::StrCat("Could it be that you put quotes in the flagfile?");
return false;
}
std::string raw_cron_expr = absl::StrCat(CronExprFlag::kCronPrefix, in);
try {
VLOG(1) << "creating cron from: '" << raw_cron_expr << "'";
flag->cron_expr = cron::make_cron(raw_cron_expr);
return true;
} catch (const cron::bad_cronexpr& ex) {
*err = ex.what();
}
return false;
}
std::string AbslUnparseFlag(const CronExprFlag& flag) {
if (flag.cron_expr) {
auto str_expr = to_cronstr(*flag.cron_expr);
DCHECK(absl::StartsWith(str_expr, CronExprFlag::kCronPrefix));
return str_expr.substr(CronExprFlag::kCronPrefix.size());
}
return "";
}
namespace dfly {
namespace fs = std::filesystem;
using absl::GetFlag;
using absl::StrCat;
using namespace facade;
using namespace util;
using detail::SaveStagesController;
using http::StringResponse;
using strings::HumanReadableNumBytes;
namespace {
const auto kRedisVersion = "7.4.0";
using EngineFunc = void (ServerFamily::*)(CmdArgList args, const CommandContext&);
inline CommandId::Handler3 HandlerFunc(ServerFamily* se, EngineFunc f) {
return [=](CmdArgList args, const CommandContext& cntx) { return (se->*f)(args, cntx); };
}
using CI = CommandId;
struct CmdArgListFormatter {
void operator()(std::string* out, MutableSlice arg) const {
out->append(absl::StrCat("`", std::string_view(arg.data(), arg.size()), "`"));
}
};
string UnknownCmd(string cmd, CmdArgList args) {
return absl::StrCat("unknown command '", cmd, "' with args beginning with: ",
absl::StrJoin(args.begin(), args.end(), ", ", CmdArgListFormatter()));
}
std::shared_ptr<detail::SnapshotStorage> CreateCloudSnapshotStorage(std::string_view uri) {
if (detail::IsS3Path(uri)) {
#ifdef WITH_AWS
shard_set->pool()->GetNextProactor()->Await([&] { util::aws::Init(); });
return std::make_shared<detail::AwsS3SnapshotStorage>(
absl::GetFlag(FLAGS_s3_endpoint), absl::GetFlag(FLAGS_s3_use_https),
absl::GetFlag(FLAGS_s3_ec2_metadata), absl::GetFlag(FLAGS_s3_sign_payload));
#else
LOG(ERROR) << "Compiled without AWS support";
exit(1);
#endif
} else if (detail::IsGCSPath(uri)) {
auto gcs = std::make_shared<detail::GcsSnapshotStorage>();
auto ec = shard_set->pool()->GetNextProactor()->Await([&] { return gcs->Init(3000); });
if (ec) {
LOG(ERROR) << "Failed to initialize GCS snapshot storage: " << ec.message();
exit(1);
}
return gcs;
} else {
LOG(ERROR) << "Uknown cloud storage " << uri;
exit(1);
}
}
// Check that if TLS is used at least one form of client authentication is
// enabled. That means either using a password or giving a root
// certificate for authenticating client certificates which will
// be required.
bool ValidateServerTlsFlags() {
if (!absl::GetFlag(FLAGS_tls)) {
return true;
}
bool has_auth = false;
if (!dfly::GetPassword().empty()) {
has_auth = true;
}
if (!(absl::GetFlag(FLAGS_tls_ca_cert_file).empty() &&
absl::GetFlag(FLAGS_tls_ca_cert_dir).empty())) {
has_auth = true;
}
if (!has_auth) {
LOG(ERROR) << "TLS configured but no authentication method is used!";
return false;
}
return true;
}
template <typename T> void UpdateMax(T* maxv, T current) {
*maxv = std::max(*maxv, current);
}
void SetMasterFlagOnAllThreads(bool is_master) {
auto cb = [is_master](unsigned, auto*) { ServerState::tlocal()->is_master = is_master; };
shard_set->pool()->AwaitBrief(cb);
}
std::optional<cron::cronexpr> InferSnapshotCronExpr() {
string save_time = GetFlag(FLAGS_save_schedule);
auto cron_expr = GetFlag(FLAGS_snapshot_cron);
if (!save_time.empty()) {
LOG(ERROR) << "save_schedule flag is deprecated, please use snapshot_cron instead";
exit(1);
}
if (cron_expr.cron_expr) {
return std::move(cron_expr.cron_expr);
}
return std::nullopt;
}
void ClientSetName(CmdArgList args, SinkReplyBuilder* builder, ConnectionContext* cntx) {
if (args.size() == 1) {
cntx->conn()->SetName(string{ArgS(args, 0)});
return builder->SendOk();
} else {
return builder->SendError(facade::kSyntaxErr);
}
}
void ClientGetName(CmdArgList args, SinkReplyBuilder* builder, ConnectionContext* cntx) {
if (!args.empty()) {
return builder->SendError(facade::kSyntaxErr);
}
auto* rb = static_cast<RedisReplyBuilder*>(builder);
if (auto name = cntx->conn()->GetName(); !name.empty()) {
return rb->SendBulkString(name);
} else {
return rb->SendNull();
}
}
void ClientList(CmdArgList args, absl::Span<facade::Listener*> listeners, SinkReplyBuilder* builder,
ConnectionContext* cntx) {
if (!args.empty()) {
return builder->SendError(facade::kSyntaxErr);
}
vector<string> client_info;
absl::base_internal::SpinLock mu;
// we can not preempt the connection traversal, so we need to use a spinlock.
// alternatively we could lock when mutating the connection list, but it seems not important.
auto cb = [&](unsigned thread_index, util::Connection* conn) {
facade::Connection* dcon = static_cast<facade::Connection*>(conn);
string info = dcon->GetClientInfo(thread_index);
absl::base_internal::SpinLockHolder l(&mu);
client_info.push_back(std::move(info));
};
for (auto* listener : listeners) {
listener->TraverseConnections(cb);
}
string result = absl::StrJoin(client_info, "\n");
result.append("\n");
auto* rb = static_cast<RedisReplyBuilder*>(builder);
return rb->SendVerbatimString(result);
}
void ClientTracking(CmdArgList args, SinkReplyBuilder* builder, ConnectionContext* cntx) {
auto* rb = static_cast<RedisReplyBuilder*>(builder);
if (!rb->IsResp3())
return builder->SendError(
"Client tracking is currently not supported for RESP2. Please use RESP3.");
CmdArgParser parser{args};
if (!parser.HasAtLeast(1) || args.size() > 3)
return builder->SendError(kSyntaxErr);
bool is_on = false;
using Tracking = ConnectionState::ClientTracking;
Tracking::Options option = Tracking::NONE;
if (parser.Check("ON")) {
is_on = true;
} else if (!parser.Check("OFF")) {
return builder->SendError(kSyntaxErr);
}
bool noloop = false;
if (parser.HasNext()) {
if (parser.Check("OPTIN")) {
option = Tracking::OPTIN;
} else if (parser.Check("OPTOUT")) {
option = Tracking::OPTOUT;
} else if (parser.Check("NOLOOP")) {
noloop = true;
} else {
return builder->SendError(kSyntaxErr);
}
}
if (parser.HasNext()) {
if (!noloop && parser.Check("NOLOOP")) {
noloop = true;
} else {
return builder->SendError(kSyntaxErr);
}
}
if (is_on) {
++cntx->subscriptions;
}
cntx->conn_state.tracking_info_.SetClientTracking(is_on);
cntx->conn_state.tracking_info_.SetOption(option);
cntx->conn_state.tracking_info_.SetNoLoop(noloop);
return builder->SendOk();
}
void ClientCaching(CmdArgList args, SinkReplyBuilder* builder, Transaction* tx,
ConnectionContext* cntx) {
auto* rb = static_cast<RedisReplyBuilder*>(builder);
if (!rb->IsResp3())
return builder->SendError(
"Client caching is currently not supported for RESP2. Please use RESP3.");
if (args.size() != 1) {
return builder->SendError(kSyntaxErr);
}
using Tracking = ConnectionState::ClientTracking;
CmdArgParser parser{args};
if (parser.Check("YES")) {
if (!cntx->conn_state.tracking_info_.HasOption(Tracking::OPTIN)) {
return builder->SendError(
"ERR CLIENT CACHING YES is only valid when tracking is enabled in OPTIN mode");
}
} else if (parser.Check("NO")) {
if (!cntx->conn_state.tracking_info_.HasOption(Tracking::OPTOUT)) {
return builder->SendError(
"ERR CLIENT CACHING NO is only valid when tracking is enabled in OPTOUT mode");
}
cntx->conn_state.tracking_info_.ResetCachingSequenceNumber();
} else {
return builder->SendError(kSyntaxErr);
}
bool is_multi = tx && tx->IsMulti();
cntx->conn_state.tracking_info_.SetCachingSequenceNumber(is_multi);
builder->SendOk();
}
void ClientSetInfo(CmdArgList args, SinkReplyBuilder* builder, ConnectionContext* cntx) {
if (args.size() != 2) {
return builder->SendError(kSyntaxErr);
}
auto* conn = cntx->conn();
if (conn == nullptr) {
return builder->SendError("No connection");
}
string type = absl::AsciiStrToUpper(ArgS(args, 0));
string_view val = ArgS(args, 1);
if (type == "LIB-NAME") {
conn->SetLibName(string(val));
} else if (type == "LIB-VER") {
conn->SetLibVersion(string(val));
} else {
return builder->SendError(kSyntaxErr);
}
builder->SendOk();
}
void ClientId(CmdArgList args, SinkReplyBuilder* builder, ConnectionContext* cntx) {
if (args.size() != 0) {
return builder->SendError(kSyntaxErr);
}
return builder->SendLong(cntx->conn()->GetClientId());
}
void ClientKill(CmdArgList args, absl::Span<facade::Listener*> listeners, SinkReplyBuilder* builder,
ConnectionContext* cntx) {
std::function<bool(facade::Connection * conn)> evaluator;
if (args.size() == 1) {
string_view ip_port = ArgS(args, 0);
if (ip_port.find(':') != ip_port.npos) {
evaluator = [ip_port](facade::Connection* conn) {
return conn->RemoteEndpointStr() == ip_port;
};
}
} else if (args.size() == 2) {
string filter_type = absl::AsciiStrToUpper(ArgS(args, 0));
string_view filter_value = ArgS(args, 1);
if (filter_type == "ADDR") {
evaluator = [filter_value](facade::Connection* conn) {
return conn->RemoteEndpointStr() == filter_value;
};
} else if (filter_type == "LADDR") {
evaluator = [filter_value](facade::Connection* conn) {
return conn->LocalBindStr() == filter_value;
};
} else if (filter_type == "ID") {
uint32_t id;
if (absl::SimpleAtoi(filter_value, &id)) {
evaluator = [id](facade::Connection* conn) { return conn->GetClientId() == id; };
}
}
// TODO: Add support for KILL USER/TYPE/SKIPME
}
if (!evaluator) {
return builder->SendError(kSyntaxErr);
}
const bool is_admin_request = cntx->conn()->IsPrivileged();
atomic<uint32_t> killed_connections = 0;
atomic<uint32_t> kill_errors = 0;
auto cb = [&](unsigned thread_index, util::Connection* conn) {
facade::Connection* dconn = static_cast<facade::Connection*>(conn);
if (evaluator(dconn)) {
if (is_admin_request || !dconn->IsPrivileged()) {
dconn->ShutdownSelf();
killed_connections.fetch_add(1);
} else {
kill_errors.fetch_add(1);
}
}
};
for (auto* listener : listeners) {
listener->TraverseConnections(cb);
}
if (kill_errors.load() == 0) {
return builder->SendLong(killed_connections.load());
} else {
return builder->SendError(absl::StrCat("Killed ", killed_connections.load(),
" client(s), but unable to kill ", kill_errors.load(),
" admin client(s)."));
}
}
std::string_view GetOSString() {
// Call uname() only once since it can be expensive. Cache the final result in a static string.
static string os_string = []() {
utsname os_name;
uname(&os_name);
return StrCat(os_name.sysname, " ", os_name.release, " ", os_name.machine);
}();
return os_string;
}
string_view GetRedisMode() {
return IsClusterEnabledOrEmulated() ? "cluster"sv : "standalone"sv;
}
struct ReplicaOfArgs {
string host;
uint16_t port;
std::optional<cluster::SlotRange> slot_range;
static optional<ReplicaOfArgs> FromCmdArgs(CmdArgList args, SinkReplyBuilder* builder);
bool IsReplicaOfNoOne() const {
return port == 0;
}
friend std::ostream& operator<<(std::ostream& os, const ReplicaOfArgs& args) {
if (args.IsReplicaOfNoOne()) {
return os << "NO ONE";
}
os << args.host << ":" << args.port;
if (args.slot_range.has_value()) {
os << " SLOTS [" << args.slot_range.value().start << "-" << args.slot_range.value().end
<< "]";
}
return os;
}
};
optional<ReplicaOfArgs> ReplicaOfArgs::FromCmdArgs(CmdArgList args, SinkReplyBuilder* builder) {
ReplicaOfArgs replicaof_args;
CmdArgParser parser(args);
if (parser.Check("NO")) {
parser.ExpectTag("ONE");
replicaof_args.port = 0;
} else {
replicaof_args.host = parser.Next<string>();
replicaof_args.port = parser.Next<uint16_t>();
if (auto err = parser.Error(); err || replicaof_args.port < 1) {
builder->SendError("port is out of range");
return nullopt;
}
if (parser.HasNext()) {
auto [slot_start, slot_end] = parser.Next<SlotId, SlotId>();
replicaof_args.slot_range = cluster::SlotRange{slot_start, slot_end};
if (auto err = parser.Error(); err || !replicaof_args.slot_range->IsValid()) {
builder->SendError("Invalid slot range");
return nullopt;
}
}
}
if (auto err = parser.Error(); err) {
builder->SendError(err->MakeReply());
return nullopt;
}
return replicaof_args;
}
uint64_t GetDelayMs(uint64_t ts) {
uint64_t now_ns = fb2::ProactorBase::GetMonotonicTimeNs();
uint64_t delay_ns = 0;
if (ts < now_ns - 1000000) { // if more than 1ms has passed between ts and now_ns
delay_ns = (now_ns - ts) / 1000000;
}
return delay_ns;
}
} // namespace
void SlowLogGet(dfly::CmdArgList args, std::string_view sub_cmd, util::ProactorPool* pp,
SinkReplyBuilder* builder) {
size_t requested_slow_log_length = UINT32_MAX;
size_t argc = args.size();
if (argc >= 3) {
builder->SendError(facade::UnknownSubCmd(sub_cmd, "SLOWLOG"), facade::kSyntaxErrType);
return;
} else if (argc == 2) {
string_view length = facade::ArgS(args, 1);
int64_t num;
if ((!absl::SimpleAtoi(length, &num)) || (num < -1)) {
builder->SendError("count should be greater than or equal to -1");
return;
}
if (num >= 0) {
requested_slow_log_length = num;
}
}
// gather all the individual slowlogs from all the fibers and sort them by their timestamp
std::vector<boost::circular_buffer<SlowLogEntry>> entries(pp->size());
pp->AwaitFiberOnAll([&](auto index, auto* context) {
auto shard_entries = ServerState::tlocal()->GetSlowLog().Entries();
entries[index] = shard_entries;
});
std::vector<std::pair<SlowLogEntry, unsigned>> merged_slow_log;
for (size_t i = 0; i < entries.size(); ++i) {
for (const auto& log_item : entries[i]) {
merged_slow_log.emplace_back(log_item, i);
}
}
std::sort(merged_slow_log.begin(), merged_slow_log.end(), [](const auto& e1, const auto& e2) {
return e1.first.unix_ts_usec > e2.first.unix_ts_usec;
});
requested_slow_log_length = std::min(merged_slow_log.size(), requested_slow_log_length);
auto* rb = static_cast<facade::RedisReplyBuilder*>(builder);
rb->StartArray(requested_slow_log_length);
for (size_t i = 0; i < requested_slow_log_length; ++i) {
const auto& entry = merged_slow_log[i].first;
const auto& args = entry.cmd_args;
rb->StartArray(6);
rb->SendLong(entry.entry_id * pp->size() + merged_slow_log[i].second);
rb->SendLong(entry.unix_ts_usec / 1000000);
rb->SendLong(entry.exec_time_usec);
// if we truncated the args, there is one pseudo-element containing the number of truncated
// args that we must add, so the result length is increased by 1
size_t len = args.size() + int(args.size() < entry.original_length);
rb->StartArray(len);
for (const auto& arg : args) {
if (arg.second > 0) {
auto suffix = absl::StrCat("... (", arg.second, " more bytes)");
auto cmd_arg = arg.first.substr(0, kMaximumSlowlogArgLength - suffix.length());
rb->SendBulkString(absl::StrCat(cmd_arg, suffix));
} else {
rb->SendBulkString(arg.first);
}
}
// if we truncated arguments - add a special string to indicate that.
if (args.size() < entry.original_length) {
rb->SendBulkString(
absl::StrCat("... (", entry.original_length - args.size(), " more arguments)"));
}
rb->SendBulkString(entry.client_ip);
rb->SendBulkString(entry.client_name);
}
}
std::optional<fb2::Fiber> Pause(std::vector<facade::Listener*> listeners, Namespace* ns,
facade::Connection* conn, ClientPause pause_state,
std::function<bool()> is_pause_in_progress,
std::function<void()> maybe_cleanup) {
// Track connections and set pause state to be able to wait untill all running transactions read
// the new pause state. Exlude already paused commands from the busy count. Exlude tracking
// blocked connections because: a) If the connection is blocked it is puased. b) We read pause
// state after waking from blocking so if the trasaction was waken by another running
// command that did not pause on the new state yet we will pause after waking up.
DispatchTracker tracker{std::move(listeners), conn, true /* ignore paused commands */,
true /*ignore blocking*/};
shard_set->pool()->AwaitFiberOnAll([&tracker, pause_state](unsigned, util::ProactorBase*) {
// Commands don't suspend before checking the pause state, so
// it's impossible to deadlock on waiting for a command that will be paused.
tracker.TrackOnThread();
ServerState::tlocal()->SetPauseState(pause_state, true);
});
// Wait for all busy commands to finish running before replying to guarantee
// that no more (write) operations will occur.
const absl::Duration kDispatchTimeout = absl::Seconds(1);
if (!tracker.Wait(kDispatchTimeout)) {
LOG(WARNING) << "Couldn't wait for commands to finish dispatching in " << kDispatchTimeout;
shard_set->pool()->AwaitBrief([pause_state](unsigned, util::ProactorBase*) {
ServerState::tlocal()->SetPauseState(pause_state, false);
});
return std::nullopt;
}
// We should not expire/evict keys while clients are paused.
shard_set->RunBriefInParallel(
[ns](EngineShard* shard) { ns->GetDbSlice(shard->shard_id()).SetExpireAllowed(false); });
return fb2::Fiber("client_pause",
[is_pause_in_progress, pause_state, ns, maybe_cleanup]() mutable {
// On server shutdown we sleep 10ms to make sure all running task finish,
// therefore 10ms steps ensure this fiber will not left hanging .
constexpr auto step = 10ms;
while (is_pause_in_progress()) {
ThisFiber::SleepFor(step);
}
ServerState& etl = *ServerState::tlocal();
if (etl.gstate() != GlobalState::SHUTTING_DOWN) {
shard_set->pool()->AwaitFiberOnAll([pause_state](util::ProactorBase* pb) {
ServerState::tlocal()->SetPauseState(pause_state, false);
});
shard_set->RunBriefInParallel([ns](EngineShard* shard) {
ns->GetDbSlice(shard->shard_id()).SetExpireAllowed(true);
});
}
if (maybe_cleanup) {
maybe_cleanup();
}
});
}
ServerFamily::ServerFamily(Service* service) : service_(*service) {
start_time_ = time(NULL);
last_save_info_.save_time = start_time_;
script_mgr_.reset(new ScriptMgr());
journal_.reset(new journal::Journal());
{
absl::InsecureBitGen eng;
master_replid_ = GetRandomHex(eng, CONFIG_RUN_ID_SIZE);
DCHECK_EQ(CONFIG_RUN_ID_SIZE, master_replid_.size());
}
if (auto ec =
detail::ValidateFilename(GetFlag(FLAGS_dbfilename), GetFlag(FLAGS_df_snapshot_format));
ec) {
LOG(ERROR) << ec.Format();
exit(1);
}
if (!ValidateServerTlsFlags()) {
exit(1);
}
ValidateClientTlsFlags();
dfly_cmd_ = make_unique<DflyCmd>(this);
}
ServerFamily::~ServerFamily() {
}
void SetMaxClients(std::vector<facade::Listener*>& listeners, uint32_t maxclients) {
for (auto* listener : listeners) {
if (!listener->IsPrivilegedInterface()) {
listener->socket()->proactor()->Await(
[listener, maxclients]() { listener->SetMaxClients(maxclients); });
}
}
}
void SetSlowLogMaxLen(util::ProactorPool& pool, uint32_t val) {
pool.AwaitFiberOnAll(
[&val](auto index, auto* context) { ServerState::tlocal()->GetSlowLog().ChangeLength(val); });
}
void SetSlowLogThreshold(util::ProactorPool& pool, int32_t val) {
pool.AwaitFiberOnAll([val](auto index, auto* context) {
ServerState::tlocal()->log_slower_than_usec = val < 0 ? UINT32_MAX : uint32_t(val);
});
}
void ServerFamily::Init(util::AcceptServer* acceptor, std::vector<facade::Listener*> listeners) {
CHECK(acceptor_ == nullptr);
acceptor_ = acceptor;
listeners_ = std::move(listeners);
auto os_string = GetOSString();
LOG_FIRST_N(INFO, 1) << "Host OS: " << os_string << " with " << shard_set->pool()->size()
<< " threads";
SetMaxClients(listeners_, absl::GetFlag(FLAGS_maxclients));
config_registry.RegisterSetter<uint32_t>(
"maxclients", [this](uint32_t val) { SetMaxClients(listeners_, val); });
SetSlowLogThreshold(service_.proactor_pool(), absl::GetFlag(FLAGS_slowlog_log_slower_than));
config_registry.RegisterMutable("slowlog_log_slower_than",
[this](const absl::CommandLineFlag& flag) {
auto res = flag.TryGet<int32_t>();
if (res.has_value())
SetSlowLogThreshold(service_.proactor_pool(), res.value());
return res.has_value();
});
SetSlowLogMaxLen(service_.proactor_pool(), absl::GetFlag(FLAGS_slowlog_max_len));
config_registry.RegisterSetter<uint32_t>(
"slowlog_max_len", [this](uint32_t val) { SetSlowLogMaxLen(service_.proactor_pool(), val); });
// We only reconfigure TLS when the 'tls' config key changes. Therefore to
// update TLS certs, first update tls_cert_file, then set 'tls true'.
config_registry.RegisterMutable("tls", [this](const absl::CommandLineFlag& flag) {
if (!ValidateServerTlsFlags()) {
return false;
}
for (facade::Listener* l : listeners_) {
// Must reconfigure in the listener proactor to avoid a race.
if (!l->socket()->proactor()->Await([l] { return l->ReconfigureTLS(); })) {
return false;
}
}
return true;
});
config_registry.RegisterMutable("tls_cert_file");
config_registry.RegisterMutable("tls_key_file");
config_registry.RegisterMutable("tls_ca_cert_file");
config_registry.RegisterMutable("tls_ca_cert_dir");
config_registry.RegisterMutable("replica_priority");
config_registry.RegisterMutable("lua_undeclared_keys_shas");
pb_task_ = shard_set->pool()->GetNextProactor();
if (pb_task_->GetKind() == ProactorBase::EPOLL) {
fq_threadpool_.reset(new fb2::FiberQueueThreadPool(absl::GetFlag(FLAGS_epoll_file_threads)));
}
string flag_dir = GetFlag(FLAGS_dir);
if (detail::IsCloudPath(flag_dir)) {
snapshot_storage_ = CreateCloudSnapshotStorage(flag_dir);
} else if (fq_threadpool_) {
snapshot_storage_ = std::make_shared<detail::FileSnapshotStorage>(fq_threadpool_.get());
} else {
snapshot_storage_ = std::make_shared<detail::FileSnapshotStorage>(nullptr);
}
// check for '--replicaof' before loading anything
if (ReplicaOfFlag flag = GetFlag(FLAGS_replicaof); flag.has_value()) {
service_.proactor_pool().GetNextProactor()->Await(
[this, &flag]() { this->Replicate(flag.host, flag.port); });
} else { // load from snapshot only if --replicaof is empty
LoadFromSnapshot();
}
const auto create_snapshot_schedule_fb = [this] {
snapshot_schedule_fb_ =
service_.proactor_pool().GetNextProactor()->LaunchFiber([this] { SnapshotScheduling(); });
};
config_registry.RegisterMutable(
"snapshot_cron", [this, create_snapshot_schedule_fb](const absl::CommandLineFlag& flag) {
JoinSnapshotSchedule();
create_snapshot_schedule_fb();
return true;
});
create_snapshot_schedule_fb();
}
void ServerFamily::LoadFromSnapshot() {
{
util::fb2::LockGuard lk{loading_stats_mu_};
loading_stats_.restore_count++;
}
const auto load_path_result =
snapshot_storage_->LoadPath(GetFlag(FLAGS_dir), GetFlag(FLAGS_dbfilename));
if (load_path_result) {
const std::string load_path = *load_path_result;
if (!load_path.empty()) {
auto future = Load(load_path, LoadExistingKeys::kFail);
load_fiber_ = service_.proactor_pool().GetNextProactor()->LaunchFiber([future]() mutable {
// Wait for load to finish in a dedicated fiber.
// Failure to load on start causes Dragonfly to exit with an error code.
if (!future.has_value() || future->Get()) {
// Error was already printed to log at this point.
exit(1);
}
});
}
} else {
if (std::error_code(load_path_result.error()) == std::errc::no_such_file_or_directory) {
LOG(WARNING) << "Load snapshot: No snapshot found";
} else {
util::fb2::LockGuard lk{loading_stats_mu_};
loading_stats_.failed_restore_count++;
LOG(ERROR) << "Failed to load snapshot: " << load_path_result.error().Format();
}
}
}
void ServerFamily::JoinSnapshotSchedule() {
schedule_done_.Notify();
snapshot_schedule_fb_.JoinIfNeeded();
schedule_done_.Reset();
}
void ServerFamily::Shutdown() {
VLOG(1) << "ServerFamily::Shutdown";
load_fiber_.JoinIfNeeded();
JoinSnapshotSchedule();
bg_save_fb_.JoinIfNeeded();
if (save_on_shutdown_ && !absl::GetFlag(FLAGS_dbfilename).empty()) {
shard_set->pool()->GetNextProactor()->Await([this]() ABSL_LOCKS_EXCLUDED(loading_stats_mu_) {
GenericError ec = DoSave();
util::fb2::LockGuard lk{loading_stats_mu_};
loading_stats_.backup_count++;
if (ec) {
loading_stats_.failed_backup_count++;
LOG(WARNING) << "Failed to perform snapshot " << ec.Format();
}
});
}
client_pause_ec_.await([this] { return active_pauses_.load() == 0; });
pb_task_->Await([this] {
auto ec = journal_->Close();
LOG_IF(ERROR, ec) << "Error closing journal " << ec;
util::fb2::LockGuard lk(replicaof_mu_);
if (replica_) {
replica_->Stop();
}
StopAllClusterReplicas();
dfly_cmd_->Shutdown();
DebugCmd::Shutdown();
});
}
bool ServerFamily::HasPrivilegedInterface() {
for (auto* listener : listeners_) {
if (listener->IsPrivilegedInterface()) {
return true;
}
}
return false;
}
void ServerFamily::UpdateMemoryGlobalStats() {
ShardId sid = EngineShard::tlocal()->shard_id();
if (sid != 0) { // This function is executed periodicaly on all shards. To ensure the logic
// bellow runs only on one shard we return is the shard is not 0.
return;
}
uint64_t mem_current = used_mem_current.load(std::memory_order_relaxed);
if (mem_current > used_mem_peak.load(memory_order_relaxed)) {