-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathserver.cc
More file actions
2212 lines (1889 loc) · 81.9 KB
/
server.cc
File metadata and controls
2212 lines (1889 loc) · 81.9 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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "server.h"
#include <rocksdb/convenience.h>
#include <rocksdb/statistics.h>
#include <sys/resource.h>
#include <sys/statvfs.h>
#include <sys/utsname.h>
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <jsoncons/json.hpp>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <utility>
#include "commands/command_parser.h"
#include "commands/commander.h"
#include "common/string_util.h"
#include "config/config.h"
#include "fmt/format.h"
#include "logging.h"
#include "redis_connection.h"
#include "redis_reply.h"
#include "rocksdb/version.h"
#include "storage/compaction_checker.h"
#include "storage/redis_db.h"
#include "storage/scripting.h"
#include "storage/storage.h"
#include "thread_util.h"
#include "time_util.h"
#include "version.h"
#include "worker.h"
Server::Server(engine::Storage *storage, Config *config)
: stats(config->histogram_bucket_boundaries),
storage(storage),
indexer(storage),
index_mgr(&indexer, storage),
start_time_secs_(util::GetTimeStamp()),
config_(config),
namespace_(storage) {
// init commands stats here to prevent concurrent insert, and cause core
auto commands = redis::CommandTable::GetOriginal();
for (const auto &iter : *commands) {
stats.commands_stats[iter.first].calls = 0;
stats.commands_stats[iter.first].latency = 0;
if (stats.bucket_boundaries.size() > 0) {
// NB: Extra index for the last bucket (Inf)
for (std::size_t i{0}; i <= stats.bucket_boundaries.size(); ++i) {
stats.commands_histogram[iter.first].buckets.push_back(std::make_unique<std::atomic<uint64_t>>(0));
}
stats.commands_histogram[iter.first].calls = 0;
stats.commands_histogram[iter.first].sum = 0;
}
}
// init cursor_dict_
cursor_dict_ = std::make_unique<CursorDictType>();
#ifdef ENABLE_OPENSSL
// init ssl context
if (config->tls_port || config->tls_replication) {
ssl_ctx = CreateSSLContext(config);
if (!ssl_ctx) {
exit(1);
}
}
#endif
// Init cluster
cluster = std::make_unique<Cluster>(this, config_->binds, config_->port);
// init shard pub/sub channels
pubsub_shard_channels_.resize(config->cluster_enabled ? HASH_SLOTS_SIZE : 1);
for (int i = 0; i < config->workers; i++) {
auto worker = std::make_unique<Worker>(this, config);
// multiple workers can't listen to the same unix socket, so
// listen unix socket only from a single worker - the first one
if (!config->unixsocket.empty() && i == 0) {
Status s = worker->ListenUnixSocket(config->unixsocket, config->unixsocketperm, config->backlog);
if (!s.IsOK()) {
ERROR("[server] Failed to listen on unix socket: {}. Error: {}", config->unixsocket, s.Msg());
exit(1);
}
INFO("[server] Listening on unix socket: {}", config->unixsocket);
}
worker_threads_.emplace_back(std::make_unique<WorkerThread>(std::move(worker)));
}
AdjustOpenFilesLimit();
slow_log_.SetMaxEntries(config->slowlog_max_len);
slow_log_.SetDumpToLogfileLevel(config->slowlog_dump_logfile_level);
perf_log_.SetMaxEntries(config->profiling_sample_record_max_len);
}
Server::~Server() {
DisconnectSlaves();
// Wait for all fetch file threads stop and exit and force destroy the server after 60s.
int counter = 0;
while (GetFetchFileThreadNum() != 0) {
usleep(100000);
if (++counter == 600) {
WARN("[server] Will force destroy the server after waiting 60s, leave {} fetch file threads are still running",
GetFetchFileThreadNum());
break;
}
}
for (auto &worker_thread : worker_threads_) {
worker_thread.reset();
}
cleanupExitedWorkerThreads(true /* force */);
CleanupExitedSlaves();
}
// Kvrocks threads list:
// - Work-thread: process client's connections and requests
// - Task-runner: one thread pool, handle some jobs that may freeze server if run directly
// - Cron-thread: server's crontab, clean backups, resize sst and memtable size
// - Compaction-checker: active compaction according to collected statistics
// - Replication-thread: replicate incremental stream from master if in slave role, there
// are some dynamic threads to fetch files when full sync.
// - fetch-file-thread: fetch SST files from master
// - Feed-slave-thread: feed data to slaves if having slaves, but there also are some dynamic
// threads when full sync, TODO(@shooterit) we should manage this threads uniformly.
// - feed-replica-data-info: generate checkpoint and send files list when full sync
// - feed-replica-file: send SST files when slaves ask for full sync
Status Server::Start() {
auto s = namespace_.LoadAndRewrite();
if (!s.IsOK()) {
return s;
}
if (!config_->master_host.empty()) {
s = AddMaster(config_->master_host, static_cast<uint32_t>(config_->master_port), false);
if (!s.IsOK()) return s;
} else {
// Generate new replication id if not a replica
engine::Context ctx(storage);
s = storage->ShiftReplId(ctx);
if (!s.IsOK()) {
return s.Prefixed("failed to shift replication id");
}
}
if (!config_->cluster_enabled) {
engine::Context no_txn_ctx = engine::Context::NoTransactionContext(storage);
GET_OR_RET(index_mgr.Load(no_txn_ctx, kDefaultNamespace));
for (const auto &[_, ns] : namespace_.List()) {
GET_OR_RET(index_mgr.Load(no_txn_ctx, ns));
}
}
if (config_->cluster_enabled) {
// Create objects used for slot migration
slot_migrator = std::make_unique<SlotMigrator>(this);
if (config_->persist_cluster_nodes_enabled) {
auto s = cluster->LoadClusterNodes(config_->NodesFilePath());
if (!s.IsOK()) {
return s.Prefixed("failed to load cluster nodes info");
}
}
auto s = slot_migrator->CreateMigrationThread();
if (!s.IsOK()) {
return s.Prefixed("failed to create migration thread");
}
slot_import = std::make_unique<SlotImport>(this);
}
for (const auto &worker : worker_threads_) {
worker->Start();
}
if (auto s = task_runner_.Start(); !s) {
WARN("Failed to start task runner: {}", s.Msg());
}
// setup server cron thread
cron_thread_ = GET_OR_RET(util::CreateThread("server-cron", [this] { this->cron(); }));
compaction_checker_thread_ = GET_OR_RET(util::CreateThread("compact-check", [this] {
uint64_t counter = 0;
int64_t last_compact_date = 0;
CompactionChecker compaction_checker{this->storage};
while (!stop_) {
// Sleep first
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// To guarantee accessing DB safely
auto guard = storage->ReadLockGuard();
if (storage->IsClosing()) continue;
if (!is_loading_ && ++counter % 600 == 0 // check every minute
&& config_->compaction_checker_cron.IsEnabled()) {
auto t_now = static_cast<time_t>(util::GetTimeStamp());
std::tm now{};
localtime_r(&t_now, &now);
if (config_->compaction_checker_cron.IsTimeMatch(&now)) {
const auto &column_family_list = engine::ColumnFamilyConfigs::ListAllColumnFamilies();
for (auto &column_family : column_family_list) {
compaction_checker.PickCompactionFilesForCf(column_family);
}
}
// compact once per day
auto now_hours = t_now / 3600;
if (now_hours != 0 && last_compact_date != now_hours / 24) {
last_compact_date = now_hours / 24;
compaction_checker.CompactPropagateAndPubSubFiles();
}
}
}
}));
memory_startup_use_.store(Stats::GetMemoryRSS(), std::memory_order_relaxed);
INFO("[server] Ready to accept connections");
return Status::OK();
}
void Server::Stop() {
stop_ = true;
slaveof_mu_.lock();
if (replication_thread_) replication_thread_->Stop();
slaveof_mu_.unlock();
for (const auto &worker : worker_threads_) {
worker->Stop(0 /* immediately terminate */);
}
task_runner_.Cancel();
}
void Server::Join() {
if (auto s = util::ThreadJoin(cron_thread_); !s) {
WARN("Cron thread operation failed: {}", s.Msg());
}
if (auto s = util::ThreadJoin(compaction_checker_thread_); !s) {
WARN("Compaction checker thread operation failed: {}", s.Msg());
}
if (auto s = task_runner_.Join(); !s) {
WARN("{}", s.Msg());
}
for (const auto &worker : worker_threads_) {
worker->Join();
}
}
Status Server::AddMaster(const std::string &host, uint32_t port, bool force_reconnect) {
std::lock_guard<std::mutex> guard(slaveof_mu_);
// Don't check host and port if 'force_reconnect' argument is set to true
if (!force_reconnect && !master_host_.empty() && master_host_ == host && master_port_ == port) {
return Status::OK();
}
// Master is changed
if (!master_host_.empty()) {
if (replication_thread_) replication_thread_->Stop();
replication_thread_ = nullptr;
}
// For master using old version, it uses replication thread to implement
// replication, and uses 'listen-port + 1' as thread listening port.
uint32_t master_listen_port = port;
if (GetConfig()->master_use_repl_port) master_listen_port += 1;
replication_thread_ = std::make_unique<ReplicationThread>(host, master_listen_port, this);
auto s = replication_thread_->Start([this]() { return PrepareRestoreDB(); },
[this]() {
this->is_loading_ = false;
if (auto s = task_runner_.Start(); !s) {
WARN("Failed to start task runner: {}", s.Msg());
}
});
if (s.IsOK()) {
master_host_ = host;
master_port_ = port;
config_->SetMaster(host, port);
} else {
replication_thread_ = nullptr;
}
return s;
}
Status Server::RemoveMaster() {
std::lock_guard<std::mutex> guard(slaveof_mu_);
if (!master_host_.empty()) {
master_host_.clear();
master_port_ = 0;
config_->ClearMaster();
if (replication_thread_) {
replication_thread_->Stop();
replication_thread_ = nullptr;
}
engine::Context ctx(storage);
return storage->ShiftReplId(ctx);
}
return Status::OK();
}
Status Server::AddSlave(redis::Connection *conn, rocksdb::SequenceNumber next_repl_seq) {
auto t = std::make_unique<FeedSlaveThread>(this, conn, next_repl_seq);
auto s = t->Start();
if (!s.IsOK()) {
return s;
}
std::unique_lock<std::shared_mutex> lg(slave_threads_mu_);
slave_threads_.emplace_back(std::move(t));
return Status::OK();
}
void Server::DisconnectSlaves() {
std::unique_lock<std::shared_mutex> lg(slave_threads_mu_);
for (auto &slave_thread : slave_threads_) {
if (!slave_thread->IsStopped()) slave_thread->Stop();
}
while (!slave_threads_.empty()) {
auto slave_thread = std::move(slave_threads_.front());
slave_threads_.pop_front();
slave_thread->Join();
}
}
void Server::CleanupExitedSlaves() {
std::unique_lock<std::shared_mutex> lg(slave_threads_mu_);
for (auto it = slave_threads_.begin(); it != slave_threads_.end();) {
if ((*it)->IsStopped()) {
auto thread = std::move(*it);
it = slave_threads_.erase(it);
thread->Join();
} else {
++it;
}
}
}
std::vector<std::string> Server::RedactSensitiveTokens(const std::vector<std::string> &tokens) {
if (tokens.empty()) return tokens;
std::string cmd = util::ToLower(tokens[0]);
if (cmd != "auth" && cmd != "hello") return tokens;
std::vector<std::string> redacted_tokens = tokens;
if (cmd == "auth" && tokens.size() >= 2) {
// AUTH password -> redact password (arg 1)
redacted_tokens[1] = "(redacted)";
} else if (cmd == "hello" && tokens.size() >= 3) {
// HELLO [version] [AUTH [username] password] [SETNAME name]
for (size_t i = 1; i < tokens.size(); ++i) {
std::string arg = util::ToLower(tokens[i]);
if (arg == "auth" && i + 1 < tokens.size()) {
size_t remaining_args = tokens.size() - i - 1;
if (remaining_args >= 2) {
// Check if this follows the pattern AUTH username password
// In this case, redact the password (arg i+2)
redacted_tokens[i + 2] = "(redacted)";
} else if (remaining_args == 1) {
// This follows the pattern AUTH password
// Redact the password (arg i+1)
redacted_tokens[i + 1] = "(redacted)";
}
break;
}
}
}
return redacted_tokens;
}
void Server::FeedMonitorConns(redis::Connection *conn, const std::vector<std::string> &tokens) {
if (monitor_clients_ <= 0) return;
auto now_us = util::GetTimeStampUS();
std::string output =
fmt::format("{}.{} [{} {}]", now_us / 1000000, now_us % 1000000, conn->GetNamespace(), conn->GetAddr());
auto redacted_tokens = RedactSensitiveTokens(tokens);
for (const auto &token : redacted_tokens) {
output += " \"";
output += util::EscapeString(token);
output += "\"";
}
for (const auto &worker_thread : worker_threads_) {
auto worker = worker_thread->GetWorker();
worker->FeedMonitorConns(conn, redis::SimpleString(output));
}
}
int Server::PublishMessage(const std::string &channel, const std::string &msg) {
int cnt = 0;
int index = 0;
pubsub_channels_mu_.lock();
std::vector<ConnContext> to_publish_conn_ctxs;
if (auto iter = pubsub_channels_.find(channel); iter != pubsub_channels_.end()) {
for (const auto &conn_ctx : iter->second) {
to_publish_conn_ctxs.emplace_back(conn_ctx);
}
}
// The patterns variable records the pattern of connections
std::vector<std::string> patterns;
std::vector<ConnContext> to_publish_patterns_conn_ctxs;
for (const auto &iter : pubsub_patterns_) {
if (util::StringMatch(iter.first, channel, false)) {
for (const auto &conn_ctx : iter.second) {
to_publish_patterns_conn_ctxs.emplace_back(conn_ctx);
patterns.emplace_back(iter.first);
}
}
}
pubsub_channels_mu_.unlock();
std::string channel_reply;
channel_reply.append(redis::MultiLen(3));
channel_reply.append(redis::BulkString("message"));
channel_reply.append(redis::BulkString(channel));
channel_reply.append(redis::BulkString(msg));
for (const auto &conn_ctx : to_publish_conn_ctxs) {
auto s = conn_ctx.owner->Reply(conn_ctx.fd, channel_reply);
if (s.IsOK()) {
cnt++;
}
}
// We should publish corresponding pattern and message for connections
for (const auto &conn_ctx : to_publish_patterns_conn_ctxs) {
std::string pattern_reply;
pattern_reply.append(redis::MultiLen(4));
pattern_reply.append(redis::BulkString("pmessage"));
pattern_reply.append(redis::BulkString(patterns[index++]));
pattern_reply.append(redis::BulkString(channel));
pattern_reply.append(redis::BulkString(msg));
auto s = conn_ctx.owner->Reply(conn_ctx.fd, pattern_reply);
if (s.IsOK()) {
cnt++;
}
}
return cnt;
}
void Server::SubscribeChannel(const std::string &channel, redis::Connection *conn) {
std::lock_guard<std::mutex> guard(pubsub_channels_mu_);
auto conn_ctx = ConnContext(conn->Owner(), conn->GetFD());
if (auto iter = pubsub_channels_.find(channel); iter == pubsub_channels_.end()) {
pubsub_channels_.emplace(channel, std::list<ConnContext>{conn_ctx});
} else {
iter->second.emplace_back(conn_ctx);
}
}
void Server::UnsubscribeChannel(const std::string &channel, redis::Connection *conn) {
std::lock_guard<std::mutex> guard(pubsub_channels_mu_);
auto iter = pubsub_channels_.find(channel);
if (iter == pubsub_channels_.end()) {
return;
}
for (const auto &conn_ctx : iter->second) {
if (conn->GetFD() == conn_ctx.fd && conn->Owner() == conn_ctx.owner) {
iter->second.remove(conn_ctx);
if (iter->second.empty()) {
pubsub_channels_.erase(iter);
}
break;
}
}
}
void Server::GetChannelsByPattern(const std::string &pattern, std::vector<std::string> *channels) {
std::lock_guard<std::mutex> guard(pubsub_channels_mu_);
for (const auto &iter : pubsub_channels_) {
if (pattern.empty() || util::StringMatch(pattern, iter.first, false)) {
channels->emplace_back(iter.first);
}
}
}
void Server::ListChannelSubscribeNum(const std::vector<std::string> &channels,
std::vector<ChannelSubscribeNum> *channel_subscribe_nums) {
std::lock_guard<std::mutex> guard(pubsub_channels_mu_);
for (const auto &chan : channels) {
if (auto iter = pubsub_channels_.find(chan); iter != pubsub_channels_.end()) {
channel_subscribe_nums->emplace_back(ChannelSubscribeNum{iter->first, iter->second.size()});
} else {
channel_subscribe_nums->emplace_back(ChannelSubscribeNum{chan, 0});
}
}
}
void Server::PSubscribeChannel(const std::string &pattern, redis::Connection *conn) {
std::lock_guard<std::mutex> guard(pubsub_channels_mu_);
auto conn_ctx = ConnContext(conn->Owner(), conn->GetFD());
if (auto iter = pubsub_patterns_.find(pattern); iter == pubsub_patterns_.end()) {
pubsub_patterns_.emplace(pattern, std::list<ConnContext>{conn_ctx});
} else {
iter->second.emplace_back(conn_ctx);
}
}
void Server::PUnsubscribeChannel(const std::string &pattern, redis::Connection *conn) {
std::lock_guard<std::mutex> guard(pubsub_channels_mu_);
auto iter = pubsub_patterns_.find(pattern);
if (iter == pubsub_patterns_.end()) {
return;
}
for (const auto &conn_ctx : iter->second) {
if (conn->GetFD() == conn_ctx.fd && conn->Owner() == conn_ctx.owner) {
iter->second.remove(conn_ctx);
if (iter->second.empty()) {
pubsub_patterns_.erase(iter);
}
break;
}
}
}
void Server::SSubscribeChannel(const std::string &channel, redis::Connection *conn, uint16_t slot) {
assert((config_->cluster_enabled && slot < HASH_SLOTS_SIZE) || slot == 0);
std::lock_guard<std::mutex> guard(pubsub_shard_channels_mu_);
auto conn_ctx = ConnContext(conn->Owner(), conn->GetFD());
if (auto iter = pubsub_shard_channels_[slot].find(channel); iter == pubsub_shard_channels_[slot].end()) {
pubsub_shard_channels_[slot].emplace(channel, std::list<ConnContext>{conn_ctx});
} else {
iter->second.emplace_back(conn_ctx);
}
}
void Server::SUnsubscribeChannel(const std::string &channel, redis::Connection *conn, uint16_t slot) {
assert((config_->cluster_enabled && slot < HASH_SLOTS_SIZE) || slot == 0);
std::lock_guard<std::mutex> guard(pubsub_shard_channels_mu_);
auto iter = pubsub_shard_channels_[slot].find(channel);
if (iter == pubsub_shard_channels_[slot].end()) {
return;
}
for (const auto &conn_ctx : iter->second) {
if (conn->GetFD() == conn_ctx.fd && conn->Owner() == conn_ctx.owner) {
iter->second.remove(conn_ctx);
if (iter->second.empty()) {
pubsub_shard_channels_[slot].erase(iter);
}
break;
}
}
}
void Server::GetSChannelsByPattern(const std::string &pattern, std::vector<std::string> *channels) {
std::lock_guard<std::mutex> guard(pubsub_shard_channels_mu_);
for (const auto &shard_channels : pubsub_shard_channels_) {
for (const auto &iter : shard_channels) {
if (pattern.empty() || util::StringMatch(pattern, iter.first, false)) {
channels->emplace_back(iter.first);
}
}
}
}
void Server::ListSChannelSubscribeNum(const std::vector<std::string> &channels,
std::vector<ChannelSubscribeNum> *channel_subscribe_nums) {
std::lock_guard<std::mutex> guard(pubsub_shard_channels_mu_);
for (const auto &chan : channels) {
uint16_t slot = config_->cluster_enabled ? GetSlotIdFromKey(chan) : 0;
if (auto iter = pubsub_shard_channels_[slot].find(chan); iter != pubsub_shard_channels_[slot].end()) {
channel_subscribe_nums->emplace_back(ChannelSubscribeNum{iter->first, iter->second.size()});
} else {
channel_subscribe_nums->emplace_back(ChannelSubscribeNum{chan, 0});
}
}
}
void Server::BlockOnKey(const std::string &key, redis::Connection *conn) {
std::lock_guard<std::mutex> guard(blocking_keys_mu_);
auto conn_ctx = ConnContext(conn->Owner(), conn->GetFD());
if (auto iter = blocking_keys_.find(key); iter == blocking_keys_.end()) {
blocking_keys_.emplace(key, std::list<ConnContext>{conn_ctx});
} else {
iter->second.emplace_back(conn_ctx);
}
IncrBlockedClientNum();
}
void Server::UnblockOnKey(const std::string &key, redis::Connection *conn) {
std::lock_guard<std::mutex> guard(blocking_keys_mu_);
auto iter = blocking_keys_.find(key);
if (iter == blocking_keys_.end()) {
return;
}
for (const auto &conn_ctx : iter->second) {
if (conn->GetFD() == conn_ctx.fd && conn->Owner() == conn_ctx.owner) {
iter->second.remove(conn_ctx);
if (iter->second.empty()) {
blocking_keys_.erase(iter);
}
break;
}
}
DecrBlockedClientNum();
}
void Server::BlockOnStreams(const std::vector<std::string> &keys, const std::vector<redis::StreamEntryID> &entry_ids,
redis::Connection *conn) {
std::lock_guard<std::mutex> guard(blocked_stream_consumers_mu_);
IncrBlockedClientNum();
for (size_t i = 0; i < keys.size(); ++i) {
auto consumer = std::make_shared<StreamConsumer>(conn->Owner(), conn->GetFD(), conn->GetNamespace(), entry_ids[i]);
if (auto iter = blocked_stream_consumers_.find(keys[i]); iter == blocked_stream_consumers_.end()) {
std::set<std::shared_ptr<StreamConsumer>> consumers;
consumers.insert(consumer);
blocked_stream_consumers_.emplace(keys[i], consumers);
} else {
iter->second.insert(consumer);
}
}
}
void Server::UnblockOnStreams(const std::vector<std::string> &keys, redis::Connection *conn) {
std::lock_guard<std::mutex> guard(blocked_stream_consumers_mu_);
DecrBlockedClientNum();
for (const auto &key : keys) {
auto iter = blocked_stream_consumers_.find(key);
if (iter == blocked_stream_consumers_.end()) {
continue;
}
for (auto it = iter->second.begin(); it != iter->second.end();) {
const auto &consumer = *it;
if (conn->GetFD() == consumer->fd && conn->Owner() == consumer->owner) {
iter->second.erase(it);
if (iter->second.empty()) {
blocked_stream_consumers_.erase(iter);
}
break;
}
++it;
}
}
}
void Server::WakeupBlockingConns(const std::string &key, size_t n_conns) {
std::lock_guard<std::mutex> guard(blocking_keys_mu_);
auto iter = blocking_keys_.find(key);
if (iter == blocking_keys_.end() || iter->second.empty()) {
return;
}
while (n_conns-- && !iter->second.empty()) {
auto conn_ctx = iter->second.front();
auto s = conn_ctx.owner->EnableWriteEvent(conn_ctx.fd);
if (!s.IsOK()) {
ERROR("[server] Failed to enable write event on blocked client {}: {}", conn_ctx.fd, s.Msg());
}
iter->second.pop_front();
}
}
void Server::OnEntryAddedToStream(const std::string &ns, const std::string &key, const redis::StreamEntryID &entry_id) {
std::lock_guard<std::mutex> guard(blocked_stream_consumers_mu_);
auto iter = blocked_stream_consumers_.find(key);
if (iter == blocked_stream_consumers_.end() || iter->second.empty()) {
return;
}
for (auto it = iter->second.begin(); it != iter->second.end();) {
auto consumer = *it;
if (consumer->ns == ns && entry_id > consumer->last_consumed_id) {
auto s = consumer->owner->EnableWriteEvent(consumer->fd);
if (!s.IsOK()) {
ERROR("[server] Failed to enable write event on blocked stream consumer {}: {}", consumer->fd, s.Msg());
}
it = iter->second.erase(it);
} else {
++it;
}
}
}
void Server::BlockOnWait(redis::Connection *conn, rocksdb::SequenceNumber target_seq, uint64_t num_replicas) {
std::unique_lock<std::shared_mutex> guard(wait_contexts_mu_);
wait_contexts_.emplace(target_seq, WaitContext(conn, target_seq, num_replicas));
IncrBlockedClientNum();
}
void Server::WakeupWaitConnections(rocksdb::SequenceNumber seq) {
std::unique_lock<std::shared_mutex> guard(wait_contexts_mu_);
// find the last entry with target_seq > seq, which cannot wakeup
auto end_it = wait_contexts_.upper_bound(seq);
for (auto it = wait_contexts_.begin(); it != end_it;) {
// Count how many replicas have reached the target sequence
size_t reached_replicas = GetReplicasReachedSequence(it->second.target_seq);
// If enough replicas have reached the target sequence, wake up the connection
if (reached_replicas >= it->second.num_replicas) {
// Send the response with the number of replicas that have reached the target sequence
it->second.conn->Reply(redis::Integer(reached_replicas));
auto s = it->second.conn->Owner()->EnableWriteEvent(it->second.conn->GetFD());
if (!s.IsOK()) {
ERROR("[server] Failed to enable write event on WAIT connection {}: {}", it->second.conn->GetFD(), s.Msg());
}
it = wait_contexts_.erase(it);
DecrBlockedClientNum();
continue;
}
++it;
}
}
void Server::WakeupWaitConnection(redis::Connection *conn, rocksdb::SequenceNumber seq) {
std::unique_lock<std::shared_mutex> guard(wait_contexts_mu_);
cleanupWaitConnection(conn);
size_t reached_replicas = GetReplicasReachedSequence(seq);
conn->Reply(redis::Integer(reached_replicas));
auto s = conn->Owner()->EnableWriteEvent(conn->GetFD());
if (!s.IsOK()) {
ERROR("[server] Failed to enable write event on WAIT connection {}: {}", conn->GetFD(), s.Msg());
}
}
void Server::CleanupWaitConnection(redis::Connection *conn) {
std::unique_lock<std::shared_mutex> guard(wait_contexts_mu_);
cleanupWaitConnection(conn);
}
void Server::cleanupWaitConnection(redis::Connection *conn) {
// Remove all wait contexts that match the given connection
auto it = wait_contexts_.begin();
int erased_count = 0;
while (it != wait_contexts_.end()) {
if (it->second.conn == conn) {
it = wait_contexts_.erase(it);
erased_count++;
// Technically only one client is unblocked, but we call IncrBlockedClientNum for each added wait context,
// so we need to call DecrBlockedClientNum for each erased wait context.
// Multiple wait contexts on the same connection should not happen, but we should be defensive.
DecrBlockedClientNum();
} else {
++it;
}
}
if (erased_count > 1) {
WARN("[server] {} wait contexts found for connection with fd {}, expect 1", erased_count, conn->GetFD());
}
}
size_t Server::GetReplicasReachedSequence(rocksdb::SequenceNumber target_seq) {
std::shared_lock<std::shared_mutex> slave_guard(slave_threads_mu_);
size_t reached_replicas = 0;
for (const auto &slave : slave_threads_) {
if (!slave->IsStopped() && slave->GetAckSeq() >= target_seq) {
reached_replicas++;
}
}
return reached_replicas;
}
rocksdb::SequenceNumber Server::LargestTargetSeqToWakeup(rocksdb::SequenceNumber seq) {
std::shared_lock<std::shared_mutex> guard(wait_contexts_mu_);
if (wait_contexts_.empty()) {
return 0;
}
// Use upper_bound to find the first entry with target_seq > seq
// the largest seq that can wakeup is the last element before it
auto it = wait_contexts_.upper_bound(seq);
// when wait_contexts_ is empty, it == wait_contexts_.begin().
// when all wait_contexts_.target_seq > seq, it == wait_contexts_.begin().
// both cases should return 0.
if (it == wait_contexts_.begin()) {
return 0;
}
// Return the largest target_seq that could potentially be unblocked
auto last_it = std::prev(it);
return last_it->second.target_seq;
}
void Server::updateCachedTime() { unix_time_secs.store(util::GetTimeStamp()); }
int Server::IncrClientNum() {
total_clients_.fetch_add(1, std::memory_order_relaxed);
return connected_clients_.fetch_add(1, std::memory_order_relaxed);
}
int Server::DecrClientNum() { return connected_clients_.fetch_sub(1, std::memory_order_relaxed); }
int Server::IncrMonitorClientNum() { return monitor_clients_.fetch_add(1, std::memory_order_relaxed); }
int Server::DecrMonitorClientNum() { return monitor_clients_.fetch_sub(1, std::memory_order_relaxed); }
int Server::IncrBlockedClientNum() { return blocked_clients_.fetch_add(1, std::memory_order_relaxed); }
int Server::DecrBlockedClientNum() { return blocked_clients_.fetch_sub(1, std::memory_order_relaxed); }
std::shared_lock<std::shared_mutex> Server::WorkConcurrencyGuard() {
return std::shared_lock(works_concurrency_rw_lock_);
}
std::unique_lock<std::shared_mutex> Server::WorkExclusivityGuard() {
return std::unique_lock(works_concurrency_rw_lock_);
}
uint64_t Server::GetClientID() { return client_id_.fetch_add(1, std::memory_order_relaxed); }
void Server::recordInstantaneousMetrics() {
auto rocksdb_stats = storage->GetDB()->GetDBOptions().statistics;
stats.TrackInstantaneousMetric(STATS_METRIC_COMMAND, stats.total_calls);
stats.TrackInstantaneousMetric(STATS_METRIC_NET_INPUT, stats.in_bytes);
stats.TrackInstantaneousMetric(STATS_METRIC_NET_OUTPUT, stats.out_bytes);
stats.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_PUT,
rocksdb_stats->getTickerCount(rocksdb::Tickers::NUMBER_KEYS_WRITTEN));
stats.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_GET,
rocksdb_stats->getTickerCount(rocksdb::Tickers::NUMBER_KEYS_READ));
stats.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_MULTIGET,
rocksdb_stats->getTickerCount(rocksdb::Tickers::NUMBER_MULTIGET_KEYS_READ));
stats.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_SEEK,
rocksdb_stats->getTickerCount(rocksdb::Tickers::NUMBER_DB_SEEK));
stats.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_NEXT,
rocksdb_stats->getTickerCount(rocksdb::Tickers::NUMBER_DB_NEXT));
stats.TrackInstantaneousMetric(STATS_METRIC_ROCKSDB_PREV,
rocksdb_stats->getTickerCount(rocksdb::Tickers::NUMBER_DB_PREV));
}
void Server::cron() {
uint64_t counter = 0;
while (!stop_) {
// Sleep first
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// To guarantee accessing DB safely
auto guard = storage->ReadLockGuard();
if (storage->IsClosing()) continue;
updateCachedTime();
counter++;
if (is_loading_) {
// We need to skip the cron operations since `is_loading_` means the db is restoring,
// and the db pointer will be modified after that. It will panic if we use the db pointer
// before the new db was reopened.
continue;
}
// check every 20s (use 20s instead of 60s so that cron will execute in critical condition)
if (counter != 0 && counter % 200 == 0) {
auto t = static_cast<time_t>(util::GetTimeStamp());
std::tm now{};
localtime_r(&t, &now);
// disable compaction cron when the compaction checker was enabled
if (!config_->compaction_checker_cron.IsEnabled() && config_->compact_cron.IsEnabled() &&
config_->compact_cron.IsTimeMatch(&now)) {
Status s = AsyncCompactDB();
INFO("[server] Schedule to compact the db, result: {}", s.Msg());
}
if (config_->bgsave_cron.IsEnabled() && config_->bgsave_cron.IsTimeMatch(&now)) {
Status s = AsyncBgSaveDB();
INFO("[server] Schedule to bgsave the db, result: {}", s.Msg());
}
if (config_->dbsize_scan_cron.IsEnabled() && config_->dbsize_scan_cron.IsTimeMatch(&now)) {
auto tokens = namespace_.List();
std::vector<std::string> namespaces;
// Number of namespaces (custom namespaces + default one)
namespaces.reserve(tokens.size() + 1);
for (auto &token : tokens) {
namespaces.emplace_back(token.second); // namespace
}
// add default namespace as fallback
namespaces.emplace_back(kDefaultNamespace);
for (auto &ns : namespaces) {
Status s = AsyncScanDBSize(ns);
INFO("[server] Schedule to recalculate the db size on namespace: {}, result: {}", ns, s.Msg());
}
}
}
// check every 10s
if (counter != 0 && counter % 100 == 0) {
Status s = AsyncPurgeOldBackups(config_->max_backup_to_keep, config_->max_backup_keep_hours);
// Purge backup if needed, it will cost much disk space if we keep backup and full sync
// checkpoints at the same time
if (config_->purge_backup_on_fullsync && (storage->ExistCheckpoint() || storage->ExistSyncCheckpoint())) {
s = AsyncPurgeOldBackups(0, 0);
}
}
// No replica uses this checkpoint, we can remove it.
if (counter != 0 && counter % 100 == 0) {
int64_t create_time_secs = storage->GetCheckpointCreateTimeSecs();
int64_t access_time_secs = storage->GetCheckpointAccessTimeSecs();
if (storage->ExistCheckpoint()) {
// TODO(shooterit): support to config the alive time of checkpoint
int64_t now_secs = util::GetTimeStamp<std::chrono::seconds>();
if ((GetFetchFileThreadNum() == 0 && now_secs - access_time_secs > 30) ||
(now_secs - create_time_secs > 24 * 60 * 60)) {
auto s = rocksdb::DestroyDB(config_->checkpoint_dir, rocksdb::Options());
if (!s.ok()) {
WARN("[server] Fail to clean checkpoint, error: {}", s.ToString());
} else {
INFO("[server] Clean checkpoint successfully");
}
}
}
}
// check if DB need to be resumed every minute
// Rocksdb has auto resume feature after retryable io error, earlier version(before v6.22.1) had
// bug when encounter no space error. The current version fixes the no space error issue, but it
// does not completely resolve, which still exists when encountered disk quota exceeded error.
// In order to properly handle all possible situations on rocksdb, we manually resume here
// when encountering no space error and disk quota exceeded error.
if (counter != 0 && counter % 600 == 0 && storage->IsDBInRetryableIOError()) {
auto s = storage->GetDB()->Resume();
if (s.ok()) {
WARN("[server] Successfully resumed DB after retryable IO error");
} else {
ERROR("[server] Failed to resume DB after retryable IO error: {}", s.ToString());
}
storage->SetDBInRetryableIOError(false);
}
// check if we need to clean up exited worker threads every 5s
if (counter != 0 && counter % 50 == 0) {
cleanupExitedWorkerThreads(false);
}
CleanupExitedSlaves();
recordInstantaneousMetrics();
}
}