forked from Expensify/Bedrock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BedrockServer.cpp
2296 lines (2038 loc) · 115 KB
/
BedrockServer.cpp
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
// Manages connections to a single instance of the bedrock server.
#include "BedrockServer.h"
#include <arpa/inet.h>
#include <iomanip>
#include <sys/resource.h>
#include <sys/time.h>
#include <signal.h>
#include <bedrockVersion.h>
#include <BedrockCore.h>
#include <BedrockPlugin.h>
#include <libstuff/libstuff.h>
#include <libstuff/SRandom.h>
set<string>BedrockServer::_blacklistedParallelCommands;
shared_timed_mutex BedrockServer::_blacklistedParallelCommandMutex;
thread_local atomic<SQLiteNode::State> BedrockServer::_nodeStateSnapshot = SQLiteNode::UNKNOWN;
void BedrockServer::acceptCommand(SQLiteCommand&& command, bool isNew) {
acceptCommand(make_unique<SQLiteCommand>(move(command)), isNew);
}
void BedrockServer::acceptCommand(unique_ptr<SQLiteCommand>&& command, bool isNew) {
// If the sync node tells us that a command causes a crash, we immediately save that.
if (SIEquals(command->request.methodLine, "CRASH_COMMAND")) {
SData request;
request.deserialize(command->request.content);
// Take a unique lock so nobody else can read from this table while we update it.
unique_lock<decltype(_crashCommandMutex)> lock(_crashCommandMutex);
// Add the blacklisted command to the map.
_crashCommands[request.methodLine].insert(request.nameValueMap);
size_t totalCount = 0;
for (const auto& s : _crashCommands) {
totalCount += s.second.size();
}
SALERT("Blacklisting command (now have " << totalCount << " blacklisted commands): " << request.serialize());
} else {
unique_ptr<BedrockCommand> newCommand(nullptr);
if (SIEquals(command->request.methodLine, "BROADCAST_COMMAND")) {
SData newRequest;
newRequest.deserialize(command->request.content);
newCommand = getCommandFromPlugins(move(newRequest));
newCommand->initiatingClientID = -1;
newCommand->initiatingPeerID = 0;
} else {
// If we already have an existing BedrockCommand (as opposed to a base class SQLiteCommand) this is
// something that we've already constructed (most likely, a response from leader), so no need to ask the
// plugins to build it over again from scratch (this also preserves the existing state of the command).
BedrockCommand* isABedrockCommand = dynamic_cast<BedrockCommand*>(command.get());
if (isABedrockCommand) {
newCommand = unique_ptr<BedrockCommand>(isABedrockCommand);
command.release();
} else {
newCommand = getCommandFromPlugins(move(command));
}
SAUTOPREFIX(newCommand->request);
SINFO("Accepted command " << newCommand->request.methodLine << " from plugin " << newCommand->getName());
}
SAUTOPREFIX(newCommand->request);
if (newCommand->writeConsistency != SQLiteNode::QUORUM
&& _syncCommands.find(newCommand->request.methodLine) != _syncCommands.end()) {
newCommand->writeConsistency = SQLiteNode::QUORUM;
_lastQuorumCommandTime = STimeNow();
SINFO("Forcing QUORUM consistency for command " << newCommand->request.methodLine);
}
SINFO("Queued new '" << newCommand->request.methodLine << "' command from bedrock node, with " << _commandQueue.size()
<< " commands already queued.");
_commandQueue.push(move(newCommand));
}
}
void BedrockServer::cancelCommand(const string& commandID) {
// TODO: Unimplemented (but never called, anyway)
}
bool BedrockServer::canStandDown() {
// Here's all the commands in existence.
size_t count = BedrockCommand::getCommandCount();
size_t standDownQueueSize = _standDownQueue.size();
// If we have any commands anywhere but the stand-down queue, let's log that.
if (count && count != standDownQueueSize) {
size_t mainQueueSize = _commandQueue.size();
size_t blockingQueueSize = _blockingCommandQueue.size();
size_t syncNodeQueueSize = _syncNodeQueuedCommands.size();
size_t completedCommandsSize = _completedCommands.size();
// These two aren't all nicely packaged so we need to lock them ourselves.
size_t outstandingHTTPSCommandsSize = 0;
{
lock_guard<decltype(_httpsCommandMutex)> lock(_httpsCommandMutex);
outstandingHTTPSCommandsSize = _outstandingHTTPSCommands.size();
}
size_t futureCommitCommandsSize = 0;
{
lock_guard<decltype(_futureCommitCommandMutex)> lock(_futureCommitCommandMutex);
futureCommitCommandsSize = _futureCommitCommands.size();
}
SINFO("Can't stand down with " << count << " commands remaining. Queue sizes are: "
<< "mainQueueSize: " << mainQueueSize << ", "
<< "blockingQueueSize: " << blockingQueueSize << ", "
<< "syncNodeQueueSize: " << syncNodeQueueSize << ", "
<< "completedCommandsSize: " << completedCommandsSize << ", "
<< "outstandingHTTPSCommandsSize: " << outstandingHTTPSCommandsSize << ", "
<< "futureCommitCommandsSize: " << futureCommitCommandsSize << ", "
<< "standDownQueueSize: " << standDownQueueSize << ".");
return false;
} else {
SINFO("Can stand down now.");
return true;
}
}
void BedrockServer::syncWrapper(const SData& args,
atomic<SQLiteNode::State>& replicationState,
atomic<string>& leaderVersion,
BedrockTimeoutCommandQueue& syncNodeQueuedCommands,
BedrockServer& server)
{
// Initialize the thread.
SInitialize(_syncThreadName);
while(true) {
// If the server's set to be detached, we wait until that flag is unset, and then start the sync thread.
if (server._detach) {
// If we're set detached, we assume we'll be re-attached eventually, and then be `RUNNING`.
SINFO("Bedrock server entering detached state.");
server._shutdownState.store(RUNNING);
// Detach any plugins now
for (auto plugin : server.plugins) {
plugin.second->onDetach();
}
server._pluginsDetached = true;
while (server._detach) {
if (server.shutdownWhileDetached) {
SINFO("Bedrock server exiting from detached state.");
return;
}
// Just wait until we're attached.
SINFO("Bedrock server sleeping in detached state.");
sleep(1);
}
SINFO("Bedrock server entering attached state.");
server._resetServer();
}
sync(args, replicationState, leaderVersion, syncNodeQueuedCommands, server);
// Now that we've run the sync thread, we can exit if it hasn't set _detach again.
if (!server._detach) {
break;
}
}
}
void BedrockServer::sync(const SData& args,
atomic<SQLiteNode::State>& replicationState,
atomic<string>& leaderVersion,
BedrockTimeoutCommandQueue& syncNodeQueuedCommands,
BedrockServer& server)
{
// Parse out the number of worker threads we'll use. The DB needs to know this because it will expect a
// corresponding number of journal tables. "-readThreads" exists only for backwards compatibility.
int workerThreads = args.calc("-workerThreads");
// TODO: remove when nothing uses readThreads.
workerThreads = workerThreads ? workerThreads : args.calc("-readThreads");
// If still no value, use the number of cores on the machine, if available.
workerThreads = workerThreads ? workerThreads : max(1u, thread::hardware_concurrency());
// A minumum of *2* worker threads are required. One for blocking writes, one for other commands.
if (workerThreads < 2) {
workerThreads = 2;
}
// Initialize the DB.
int64_t mmapSizeGB = args.isSet("-mmapSizeGB") ? stoll(args["-mmapSizeGB"]) : 0;
// We use fewer FDs on test machines that have other resource restrictions in place.
int fdLimit = args.isSet("-live") ? 25'000 : 250;
SINFO("Setting dbPool size to: " << fdLimit);
SQLitePool dbPool(fdLimit, args["-db"], args.calc("-cacheSize"), args.calc("-maxJournalSize"), workerThreads, args["-synchronous"], mmapSizeGB, args.test("-pageLogging"));
SQLite& db = dbPool.getBase();
// Initialize the command processor.
BedrockCore core(db, server);
// And the sync node.
uint64_t firstTimeout = STIME_US_PER_M * 2 + SRandom::rand64() % STIME_US_PER_S * 30;
// Initialize the shared pointer to our sync node object.
atomic_store(&server._syncNode, make_shared<SQLiteNode>(server, dbPool, args["-nodeName"], args["-nodeHost"],
args["-peerList"], args.calc("-priority"), firstTimeout,
server._version, args.test("-parallelReplication")));
// This should be empty anyway, but let's make sure.
if (server._completedCommands.size()) {
SWARN("_completedCommands not empty at startup of sync thread.");
}
// The node is now coming up, and should eventually end up in a `LEADING` or `FOLLOWING` state. We can start adding
// our worker threads now. We don't wait until the node is `LEADING` or `FOLLOWING`, as it's state can change while
// it's running, and our workers will have to maintain awareness of that state anyway.
SINFO("Starting " << workerThreads << " worker threads.");
list<thread> workerThreadList;
for (int threadId = 0; threadId < workerThreads; threadId++) {
workerThreadList.emplace_back(worker,
ref(dbPool),
ref(replicationState),
ref(leaderVersion),
ref(syncNodeQueuedCommands),
ref(server._completedCommands),
ref(server),
threadId);
}
// Now we jump into our main command processing loop.
uint64_t nextActivity = STimeNow();
unique_ptr<BedrockCommand> command(nullptr);
bool committingCommand = false;
// Timer for S_poll performance logging. Created outside the loop because it's cumulative.
AutoTimer pollTimer("sync thread poll");
AutoTimer postPollTimer("sync thread PostPoll");
AutoTimer escalateLoopTimer("sync thread escalate loop");
do {
// Make sure the existing command prefix is still valid since they're reset when SAUTOPREFIX goes out of scope.
if (command) {
SAUTOPREFIX(command->request);
}
// If there were commands waiting on our commit count to come up-to-date, we'll move them back to the main
// command queue here. There's no place in particular that's best to do this, so we do it at the top of this
// main loop, as that prevents it from ever getting skipped in the event that we `continue` early from a loop
// iteration.
// We also move all commands back to the main queue here if we're shutting down, just to make sure they don't
// end up lost in the ether.
{
SAUTOLOCK(server._futureCommitCommandMutex);
// First, see if anything has timed out, and move that back to the main queue.
if (server._futureCommitCommandTimeouts.size()) {
uint64_t now = STimeNow();
auto it = server._futureCommitCommandTimeouts.begin();
while (it != server._futureCommitCommandTimeouts.end() && it->first < now) {
// Find commands depending on this commit.
auto itPair = server._futureCommitCommands.equal_range(it->second);
for (auto cmdIt = itPair.first; cmdIt != itPair.second; cmdIt++) {
// Check for one with this timeout.
if (cmdIt->second->timeout() == it->first) {
// This command has the right commit count *and* timeout, return it.
SINFO("Returning command (" << cmdIt->second->request.methodLine << ") waiting on commit " << cmdIt->first
<< " to queue, timed out at: " << now << ", timeout was: " << it->first << ".");
// Goes back to the main queue, where it will hit it's timeout in a worker thread.
server._commandQueue.push(move(cmdIt->second));
// And delete it, it's gone.
server._futureCommitCommands.erase(cmdIt);
// Done.
break;
}
}
it++;
}
// And remove everything we just iterated through.
if (it != server._futureCommitCommandTimeouts.begin()) {
server._futureCommitCommandTimeouts.erase(server._futureCommitCommandTimeouts.begin(), it);
}
}
// Anything that hasn't timed out might be ready to return because the commit count is up-to-date.
if (!server._futureCommitCommands.empty()) {
uint64_t commitCount = db.getCommitCount();
auto it = server._futureCommitCommands.begin();
while (it != server._futureCommitCommands.end() && (it->first <= commitCount || server._shutdownState.load() != RUNNING)) {
// Save the timeout since we'll be moving the command, thus making this inaccessible.
uint64_t commandTimeout = it->second->timeout();
SINFO("Returning command (" << it->second->request.methodLine << ") waiting on commit " << it->first
<< " to queue, now have commit " << commitCount);
server._commandQueue.push(move(it->second));
// Remove it from the timed out list as well.
auto itPair = server._futureCommitCommandTimeouts.equal_range(commandTimeout);
for (auto timeoutIt = itPair.first; timeoutIt != itPair.second; timeoutIt++) {
if (timeoutIt->second == it->first) {
server._futureCommitCommandTimeouts.erase(timeoutIt);
break;
}
}
it++;
}
if (it != server._futureCommitCommands.begin()) {
server._futureCommitCommands.erase(server._futureCommitCommands.begin(), it);
}
}
}
// If we're in a state where we can initialize shutdown, then go ahead and do so.
// Having responded to all clients means there are no *local* clients, but it doesn't mean there are no
// escalated commands. This is fine though - if we're following, there can't be any escalated commands, and if
// we're leading, then the next update() loop will set us to standing down, and then we won't accept any new
// commands, and we'll shortly run through the existing queue.
if (server._shutdownState.load() == CLIENTS_RESPONDED) {
// The total time we'll wait for the sync node is whatever we haven't already waited from the original
// timeout, minus 5 seconds to allow to clean up afterward.
int64_t timeAllowed = server._gracefulShutdownTimeout.alarmDuration.load() - server._gracefulShutdownTimeout.elapsed();
timeAllowed -= 5'000'000;
server._syncNode->beginShutdown(max(timeAllowed, (int64_t)1));
}
// The fd_map contains a list of all file descriptors (eg, sockets, Unix pipes) that poll will wait on for
// activity. Once any of them has activity (or the timeout ends), poll will return.
fd_map fdm;
// Prepare our plugins for `poll` (for instance, in case they're making HTTP requests).
server._prePollPlugins(fdm);
// Pre-process any sockets the sync node is managing (i.e., communication with peer nodes).
server._syncNode->prePoll(fdm);
// Add our command queues to our fd_map.
syncNodeQueuedCommands.prePoll(fdm);
server._completedCommands.prePoll(fdm);
// Wait for activity on any of those FDs, up to a timeout.
const uint64_t now = STimeNow();
{
AutoTimerTime pollTime(pollTimer);
S_poll(fdm, max(nextActivity, now) - now);
}
// And set our next timeout for 1 second from now.
nextActivity = STimeNow() + STIME_US_PER_S;
// Process any network traffic that happened. Scope this so that we can change the log prefix and have it
// auto-revert when we're finished.
{
// Set the default log prefix.
SAUTOPREFIX(SData());
// Process any activity in our plugins.
AutoTimerTime postPollTime(postPollTimer);
server._postPollPlugins(fdm, nextActivity);
server._syncNode->postPoll(fdm, nextActivity);
syncNodeQueuedCommands.postPoll(fdm);
server._completedCommands.postPoll(fdm);
}
// Ok, let the sync node to it's updating for as many iterations as it requires. We'll update the replication
// state when it's finished.
SQLiteNode::State preUpdateState = server._syncNode->getState();
while (server._syncNode->update()) {}
SQLiteNode::State nodeState = server._syncNode->getState();
replicationState.store(nodeState);
leaderVersion.store(server._syncNode->getLeaderVersion());
// If anything was in the stand down queue, move it back to the main queue.
if (nodeState != SQLiteNode::STANDINGDOWN) {
while (server._standDownQueue.size()) {
server._commandQueue.push(server._standDownQueue.pop());
}
} else if (preUpdateState != SQLiteNode::STANDINGDOWN) {
// Otherwise,if we just started standing down, discard any commands that had been scheduled in the future.
// In theory, it should be fine to keep these, as they shouldn't have sockets associated with them, and
// they could be re-escalated to leader in the future, but there's not currently a way to decide if we've
// run through all of the commands that might need peer responses before standing down aside from seeing if
// the entire queue is empty.
server._commandQueue.abandonFutureCommands(5000);
}
// If we were LEADING, but we've transitioned, then something's gone wrong (perhaps we got disconnected
// from the cluster). Reset some state and try again.
if ((preUpdateState == SQLiteNode::LEADING || preUpdateState == SQLiteNode::STANDINGDOWN) &&
(nodeState != SQLiteNode::LEADING && nodeState != SQLiteNode::STANDINGDOWN)) {
// If we bailed out while doing a upgradeDB, clear state
if (server._upgradeInProgress) {
server._upgradeInProgress = false;
if (committingCommand) {
db.rollback();
committingCommand = false;
}
}
// We should give up an any commands, and let them be re-escalated. If commands were initiated locally,
// we can just re-queue them, they will get re-checked once things clear up, and then they'll get
// processed here, or escalated to the new leader. Commands initiated on followers just get dropped,
// they will need to be re-escalated, potentially to a different leader.
int requeued = 0;
int dropped = 0;
try {
while (true) {
// Reset this to blank. This releases the existing command and allows it to get cleaned up.
command = unique_ptr<BedrockCommand>(nullptr);
command = syncNodeQueuedCommands.pop();
if (command->initiatingClientID) {
// This one came from a local client, so we can save it for later.
server._commandQueue.push(move(command));
}
}
} catch (const out_of_range& e) {
SWARN("Abruptly stopped LEADING. Re-queued " << requeued << " commands, Dropped " << dropped << " commands.");
// command will be null here, we should be able to restart the loop.
continue;
}
}
// Now that we've cleared any state associated with switching away from leading, we can bail out and try again
// until we're either leading or following.
if (nodeState != SQLiteNode::LEADING && nodeState != SQLiteNode::FOLLOWING && nodeState != SQLiteNode::STANDINGDOWN) {
continue;
}
// If we've just switched to the leading state, we want to upgrade the DB. We set a global `upgradeInProgress`
// flag to prevent workers from trying to use the DB while we do this.
// It's also possible for the upgrade to fail on the first try, in the case that our followers weren't ready to
// receive the transaction when we started. In this case, we'll try the upgrade again if we were already
// leading, and the upgrade is still in progress (because the first try failed), and we're not currently
// attempting to commit it.
if ((preUpdateState != SQLiteNode::LEADING && nodeState == SQLiteNode::LEADING) ||
(nodeState == SQLiteNode::LEADING && server._upgradeInProgress && !committingCommand)) {
// Store this before we start writing to the DB, which can take a while depending on what changes were made
// (for instance, adding an index).
server._upgradeInProgress = true;
if (!server._syncNode->hasQuorum()) {
// We are now "upgrading" but we won't actually start the commit until the cluster is sufficiently
// connected. This is because if we need to roll back the commit, it disconnects the entire cluster,
// which is more likely to trigger the same thing to happen again, making cluster startup take
// significantly longer. In this case we'll just loop again, like if the upgrade failed.
SINFO("Waiting for quorum availability before running UpgradeDB.");
continue;
}
if (server._upgradeDB(db)) {
committingCommand = true;
server._syncNode->startCommit(SQLiteNode::QUORUM);
server._lastQuorumCommandTime = STimeNow();
SDEBUG("Finished sending distributed transaction for db upgrade.");
// As it's a quorum commit, we'll need to read from peers. Let's start the next loop iteration.
continue;
} else {
// If we're not doing an upgrade, we don't need to keep suppressing multi-write, and we're done with
// the upgradeInProgress flag.
server._upgradeInProgress = false;
SINFO("UpgradeDB skipped, done.");
}
}
// If we started a commit, and one's not in progress, then we've finished it and we'll take that command and
// stick it back in the appropriate queue.
if (committingCommand && !server._syncNode->commitInProgress()) {
// Record the time spent, unless we were upgrading, in which case, there's no command to write to.
if (command) {
command->stopTiming(BedrockCommand::COMMIT_SYNC);
}
committingCommand = false;
// If we were upgrading, there's no response to send, we're just done.
if (server._upgradeInProgress) {
if (server._syncNode->commitSucceeded()) {
server._upgradeInProgress = false;
SINFO("UpgradeDB succeeded, done.");
} else {
SINFO("UpgradeDB failed, trying again.");
}
continue;
}
if (server._syncNode->commitSucceeded()) {
if (command) {
SINFO("[performance] Sync thread finished committing command " << command->request.methodLine);
// Otherwise, save the commit count, mark this command as complete, and reply.
command->response["commitCount"] = to_string(db.getCommitCount());
command->complete = true;
if (command->initiatingPeerID) {
// This is a command that came from a peer. Have the sync node send the response back to the peer.
server._finishPeerCommand(command);
} else {
// The only other option is this came from a client, so respond via the server.
server._reply(command);
}
} else {
SINFO("Sync thread finished committing non-command");
}
} else {
// This should only happen if the cluster becomes largely disconnected while we were in the process of
// committing a QUORUM command - if we no longer have enough peers to reach QUORUM, we'll fall out of
// leading. This code won't actually run until the node comes back up in a LEADING or FOLLOWING
// state, because this loop is skipped except when LEADING, FOLLOWING, or STANDINGDOWN. It's also
// theoretically feasible for this to happen if a follower fails to commit a transaction, but that
// probably indicates a bug (or a follower disk failure).
if (command) {
SINFO("requeueing command " << command->request.methodLine
<< " after failed sync commit. Sync thread has " << syncNodeQueuedCommands.size()
<< " queued commands.");
syncNodeQueuedCommands.push(move(command));
} else {
SERROR("Unexpected sync thread commit state.");
}
}
}
// We're either leading, standing down, or following. There could be a commit in progress on `command`, but
// there could also be other finished work to handle while we wait for that to complete. Let's see if we can
// handle any of that work.
try {
// If there are any completed commands to respond to, we'll do that first.
try {
while (true) {
unique_ptr<BedrockCommand> completedCommand = server._completedCommands.pop();
SAUTOPREFIX(completedCommand->request);
SASSERT(completedCommand->complete);
SASSERT(completedCommand->initiatingPeerID);
SASSERT(!completedCommand->initiatingClientID);
server._finishPeerCommand(completedCommand);
}
} catch (const out_of_range& e) {
// when _completedCommands.pop() throws for running out of commands, we fall out of the loop.
}
// We don't start processing a new command until we've completed any existing ones.
if (committingCommand) {
continue;
}
// Don't escalate, leader can't handle the command anyway. Don't even dequeue the command, just leave it
// until one of these states changes. This prevents an endless loop of escalating commands, having
// SQLiteNode re-queue them because leader is standing down, and then escalating them again until leader
// sorts itself out.
if (nodeState == SQLiteNode::FOLLOWING && server._syncNode->leaderState() == SQLiteNode::STANDINGDOWN) {
continue;
}
// We want to run through all of the commands in our queue. However, we set a maximum limit. This list is
// potentially infinite, as we can add new commands to the list as we iterate across it (coming from
// workers), and we will need to break and read from the network to see what to do next at some point.
// Additionally, in exceptional cases, if we get stuck in this loop for more than 64k commands, we can hit
// the internal limit of the buffer for the pipe inside syncNodeQueuedCommands, and writes there will
// block, and this can cause deadlocks in various places. This is cleared every time we run `postPoll` for
// syncNodeQueuedCommands, which occurs when break out of this loop, so we do so periodically to avoid
// this.
// TODO: We could potentially make writes to the pipe in the queue non-blocking and help to mitigate that
// part of this issue as well.
size_t escalateCount = 0;
while (++escalateCount < 1000) {
AutoTimerTime escalateTime(escalateLoopTimer);
// Reset this to blank. This releases the existing command and allows it to get cleaned up.
command = unique_ptr<BedrockCommand>(nullptr);
// Get the next sync node command to work on.
command = syncNodeQueuedCommands.pop();
// We got a command to work on! Set our log prefix to the request ID.
SAUTOPREFIX(command->request);
SINFO("Sync thread dequeued command " << command->request.methodLine << ". Sync thread has "
<< syncNodeQueuedCommands.size() << " queued commands.");
if (command->timeout() < STimeNow()) {
SINFO("Command '" << command->request.methodLine << "' timed out in sync thread queue, sending back to main queue.");
server._commandQueue.push(move(command));
break;
}
// Set the function that will be called if this thread's signal handler catches an unrecoverable error,
// like a segfault. Note that it's possible we're in the middle of sending a message to peers when we call
// this, which would probably make this message malformed. This is the best we can do.
SSetSignalHandlerDieFunc([&](){
server._syncNode->broadcast(_generateCrashMessage(command));
});
// And now we'll decide how to handle it.
if (nodeState == SQLiteNode::LEADING || nodeState == SQLiteNode::STANDINGDOWN) {
db.waitForCheckpoint();
// We peek commands here in the sync thread to be able to run peek and process as part of the same
// transaction. This guarantees that any checks made in peek are still valid in process, as the DB can't
// have changed in the meantime.
// IMPORTANT: This check is omitted for commands with an HTTPS request object, because we don't want to
// risk duplicating that request. If your command creates an HTTPS request, it needs to explicitly
// re-verify that any checks made in peek are still valid in process.
if (!command->httpsRequests.size()) {
BedrockCore::RESULT result = core.peekCommand(command, true);
if (result == BedrockCore::RESULT::COMPLETE) {
// This command completed in peek, respond to it appropriately, either directly or by sending it
// back to the sync thread.
SASSERT(command->complete);
if (command->initiatingPeerID) {
server._finishPeerCommand(command);
} else {
server._reply(command);
}
break;
} else if (result == BedrockCore::RESULT::SHOULD_PROCESS) {
// This is sort of the "default" case after checking if this command was complete above. If so,
// we'll fall through to calling processCommand below.
} else if (result == BedrockCore::RESULT::ABANDONED_FOR_CHECKPOINT) {
SINFO("[checkpoint] Re-queuing abandoned command (from peek) in sync thread");
server._commandQueue.push(move(command));
break;
} else {
SERROR("peekCommand (" << command->request.getVerb() << ") returned invalid result code: " << (int)result);
}
// If we just started a new HTTPS request, save it for later.
if (command->httpsRequests.size()) {
server.waitForHTTPS(move(command));
// Move on to the next command until this one finishes.
core.rollback();
break;
}
}
BedrockCore::RESULT result = core.processCommand(command, true);
if (result == BedrockCore::RESULT::NEEDS_COMMIT) {
// The processor says we need to commit this, so let's start that process.
committingCommand = true;
SINFO("[performance] Sync thread beginning committing command " << command->request.methodLine);
// START TIMING.
command->startTiming(BedrockCommand::COMMIT_SYNC);
server._syncNode->startCommit(command->writeConsistency);
// And we'll start the next main loop.
// NOTE: This will cause us to read from the network again. This, in theory, is fine, but we saw
// performance problems in the past trying to do something similar on every commit. This may be
// alleviated now that we're only doing this on *sync* commits instead of all commits, which should
// be a much smaller fraction of all our traffic. We set nextActivity here so that there's no
// timeout before we'll give up on poll() if there's nothing to read.
nextActivity = STimeNow();
break;
} else if (result == BedrockCore::RESULT::NO_COMMIT_REQUIRED) {
// Otherwise, the command doesn't need a commit (maybe it was an error, or it didn't have any work
// to do). We'll just respond.
if (command->initiatingPeerID) {
server._finishPeerCommand(command);
} else {
server._reply(command);
}
} else if (result == BedrockCore::RESULT::ABANDONED_FOR_CHECKPOINT) {
SINFO("[checkpoint] Re-queuing abandoned command (from process) in sync thread");
server._commandQueue.push(move(command));
break;
} else {
SERROR("processCommand (" << command->request.getVerb() << ") returned invalid result code: " << (int)result);
}
// When we're leading, we'll try and handle one command and then stop.
break;
} else if (nodeState == SQLiteNode::FOLLOWING) {
// If we're following, we just escalate directly to leader without peeking. We can only get an incomplete
// command on the follower sync thread if a follower worker thread peeked it unsuccessfully, so we don't
// bother peeking it again.
auto it = command->request.nameValueMap.find("Connection");
bool forget = it != command->request.nameValueMap.end() && SIEquals(it->second, "forget");
server._syncNode->escalateCommand(move(command), forget);
}
}
if (escalateCount == 1000) {
SINFO("Escalated 1000 commands without hitting the end of the queue. Breaking.");
}
} catch (const out_of_range& e) {
// syncNodeQueuedCommands had no commands to work on, we'll need to re-poll for some.
continue;
}
} while (!server._syncNode->shutdownComplete() && !server._gracefulShutdownTimeout.ringing());
SSetSignalHandlerDieFunc([](){SWARN("Dying in shutdown");});
// If we forced a shutdown mid-transaction (this can happen, if, for instance, we hit our graceful timeout between
// getting a `BEGIN_TRANSACTION` and `COMMIT_TRANSACTION`) then we need to roll back the existing transaction and
// release the lock.
if (server._syncNode->commitInProgress()) {
SWARN("Shutting down mid-commit. Rolling back.");
db.rollback();
}
// We've finished shutting down the sync node, tell the workers that it's finished.
server._shutdownState.store(DONE);
SINFO("Sync thread finished with commands.");
// We just fell out of the loop where we were waiting for shutdown to complete. Update the state one last time when
// the writing replication thread exits.
replicationState.store(server._syncNode->getState());
if (replicationState.load() > SQLiteNode::WAITING) {
// This is because the graceful shutdown timer fired and syncNode.shutdownComplete() returned `true` above, but
// the server still thinks it's in some other state. We can only exit if we're in state <= SQLC_SEARCHING,
// (per BedrockServer::shutdownComplete()), so we force that state here to allow the shutdown to proceed.
SWARN("Sync thread exiting in state " << replicationState.load() << ". Setting to SEARCHING.");
replicationState.store(SQLiteNode::SEARCHING);
} else {
SINFO("Sync thread exiting, setting state to: " << replicationState.load());
}
// Wait for the worker threads to finish.
int threadId = 0;
for (auto& workerThread : workerThreadList) {
SINFO("Joining worker thread '" << "worker" << threadId << "'");
threadId++;
workerThread.join();
}
// If there's anything left in the command queue here, we'll discard it, because we have no way of processing it.
if (server._commandQueue.size()) {
SWARN("Sync thread shut down with " << server._commandQueue.size() << " queued commands. Commands were: "
<< SComposeList(server._commandQueue.getRequestMethodLines()) << ". Clearing.");
server._commandQueue.clear();
}
// Same for the blocking queue.
if (server._blockingCommandQueue.size()) {
SWARN("Sync thread shut down with " << server._blockingCommandQueue.size() << " blocking queued commands. Commands were: "
<< SComposeList(server._blockingCommandQueue.getRequestMethodLines()) << ". Clearing.");
server._blockingCommandQueue.clear();
}
// Release our handle to this pointer. Any other functions that are still using it will keep the object alive
// until they return.
atomic_store(&server._syncNode, shared_ptr<SQLiteNode>(nullptr));
// We're really done, store our flag so main() can be aware.
server._syncThreadComplete.store(true);
}
void BedrockServer::worker(SQLitePool& dbPool,
atomic<SQLiteNode::State>& replicationState,
atomic<string>& leaderVersion,
BedrockTimeoutCommandQueue& syncNodeQueuedCommands,
BedrockTimeoutCommandQueue& syncNodeCompletedCommands,
BedrockServer& server,
int threadId)
{
// Worker 0 is the "blockingCommit" thread.
SInitialize(threadId ? "worker" + to_string(threadId) : "blockingCommit");
// Get a DB handle to work on. This will automatically be returned when dbScope goes out of scope.
SQLiteScopedHandle dbScope(dbPool, dbPool.getIndex());
SQLite& db = dbScope.db();
BedrockCore core(db, server);
// Command to work on. This default command is replaced when we find work to do.
unique_ptr<BedrockCommand> command(nullptr);
// Which command queue do we use? The blockingCommit thread special and does blocking commits from the blocking queue.
BedrockCommandQueue& commandQueue = threadId ? server._commandQueue : server._blockingCommandQueue;
// We just run this loop looking for commands to process forever. There's a check for appropriate exit conditions
// at the bottom, which will cause our loop and thus this thread to exit when that becomes true.
while (true) {
try {
// Set a signal handler function that we can call even if we die early with no command.
SSetSignalHandlerDieFunc([&](){
SWARN("Die function called early with no command, probably died in `commandQueue.get`.");
});
// Reset this to blank. This releases the existing command and allows it to get cleaned up.
command = unique_ptr<BedrockCommand>(nullptr);
// And get another one.
command = commandQueue.get(1000000);
SAUTOPREFIX(command->request);
SINFO("Dequeued command " << command->request.methodLine << " in worker, "
<< commandQueue.size() << " commands in " << (threadId ? "" : "blocking") << " queue.");
// Set the function that lets the signal handler know which command caused a problem, in case that happens.
// If a signal is caught on this thread, which should only happen for unrecoverable, yet synchronous
// signals, like SIGSEGV, this function will be called.
SSetSignalHandlerDieFunc([&](){
server._syncNode->broadcast(_generateCrashMessage(command));
});
// If we dequeue a status or control command, handle it immediately.
if (server._handleIfStatusOrControlCommand(command)) {
continue;
}
// If the command has already timed out when we get it, we can return early here without peeking it.
// We'd also catch that the command timed out in `peek`, but this can cause some weird side-effects. For
// instance, we saw QUORUM commands that make HTTPS requests time out in the sync thread, which caused them
// to be returned to the main queue, where they would have timed out in `peek`, but it was never called
// because the commands already had a HTTPS request attached, and then they were immediately re-sent to the
// sync queue, because of the QUORUM consistency requirement, resulting in an endless loop.
if (core.isTimedOut(command)) {
if (command->initiatingPeerID) {
// Escalated command. Give it back to the sync thread to respond.
syncNodeCompletedCommands.push(move(command));
} else {
server._reply(command);
}
continue;
}
// Check if this command would be likely to cause a crash
if (server._wouldCrash(command)) {
// If so, make a lot of noise, and respond 500 without processing it.
SALERT("CRASH-INDUCING COMMAND FOUND: " << command->request.methodLine);
command->response.methodLine = "500 Refused";
command->complete = true;
if (command->initiatingPeerID) {
// Escalated command. Give it back to the sync thread to respond.
syncNodeCompletedCommands.push(move(command));
} else {
server._reply(command);
}
continue;
}
// If this was a command initiated by a peer as part of a cluster operation, then we process it separately
// and respond immediately. This allows SQLiteNode to offload read-only operations to worker threads.
if (SQLiteNode::peekPeerCommand(server._syncNode, db, *command)) {
// Move on to the next command.
continue;
}
// We just spin until the node looks ready to go. Typically, this doesn't happen expect briefly at startup.
while (server._upgradeInProgress ||
(replicationState.load() != SQLiteNode::LEADING &&
replicationState.load() != SQLiteNode::FOLLOWING &&
replicationState.load() != SQLiteNode::STANDINGDOWN)
) {
// Make sure that the node isn't shutting down, leaving us in an endless loop.
if (server._shutdownState.load() != RUNNING) {
SWARN("Sync thread shut down while were waiting for it to come up. Discarding command '"
<< command->request.methodLine << "'.");
return;
}
// This sleep call is pretty ugly, but it should almost never happen. We're accepting the potential
// looping sleep call for the general case where we just check some bools and continue, instead of
// avoiding the sleep call but having every thread lock a mutex here on every loop.
usleep(10000);
}
// OK, so this is the state right now, which isn't necessarily anything in particular, because the sync
// node can change it at any time, and we're not synchronizing on it. We're going to go ahead and assume
// it's something reasonable, because in most cases, that's pretty safe. If we think we're anything but
// LEADING, we'll just peek this command and return it's result, which should be harmless. If we think
// we're leading, we'll go ahead and start a `process` for the command, but we'll synchronously verify
// our state right before we commit.
SQLiteNode::State state = replicationState.load();
// If we're following, any incomplete commands can be immediately escalated to leader. This saves the work
// of a `peek` operation, but more importantly, it skips any delays that might be introduced by waiting in
// the `_futureCommitCommands` queue.
if (state == SQLiteNode::FOLLOWING && command->escalateImmediately && !command->complete) {
SINFO("Immediately escalating " << command->request.methodLine << " to leader. Sync thread has " << syncNodeQueuedCommands.size() << " queued commands.");
syncNodeQueuedCommands.push(move(command));
continue;
}
// If we find that we've gotten a command with an initiatingPeerID, but we're not in a leading or
// standing down state, we'll have no way of returning this command to the caller, so we discard it. The
// original caller will need to re-send the request. This can happen if we're leading, and receive a
// request from a peer, but then we stand down from leading. The SQLiteNode should have already told its
// peers that their outstanding requests were being canceled at this point.
if (command->initiatingPeerID && !(state == SQLiteNode::LEADING || state == SQLiteNode::STANDINGDOWN)) {
SWARN("Found " << (command->complete ? "" : "in") << "complete " << "command "
<< command->request.methodLine << " from peer, but not leading. Too late for it, discarding.");
// If the command was processed, tell the plugin we couldn't send the response.
command->handleFailedReply();
continue;
}
// If this command is already complete, then we should be a follower, and the sync node got a response back
// from a command that had been escalated to leader, and queued it for a worker to respond to. We'll send
// that response now.
if (command->complete) {
// If this command is already complete, we can return it to the caller.
// If it has an initiator, it should have been returned to a peer by a sync node instead, but if we've
// just switched states out of leading, we might have an old command in the queue. All we can do here
// is note that and discard it, as we have nobody to deliver it to.
if (command->initiatingPeerID) {
// Let's note how old this command is.
uint64_t ageSeconds = (STimeNow() - command->creationTime) / STIME_US_PER_S;
SWARN("Found unexpected complete command " << command->request.methodLine
<< " from peer in worker thread. Discarding (command was " << ageSeconds << "s old).");
continue;
}
// Make sure we have an initiatingClientID at this point. If we do, but it's negative, it's for a
// client that we can't respond to, so we don't bother sending the response.
SASSERT(command->initiatingClientID);
if (command->initiatingClientID > 0) {
server._reply(command);
}
// This command is done, move on to the next one.
continue;
}
// If this command is dependent on a commitCount newer than what we have (maybe it's a follow-up to a
// command that was escalated to leader), we'll set it aside for later processing. When the sync node
// finishes its update loop, it will re-queue any of these commands that are no longer blocked on our
// updated commit count.
uint64_t commitCount = db.getCommitCount();
uint64_t commandCommitCount = command->request.calcU64("commitCount");
if (commandCommitCount > commitCount) {
SAUTOLOCK(server._futureCommitCommandMutex);
auto newQueueSize = server._futureCommitCommands.size() + 1;
SINFO("Command (" << command->request.methodLine << ") depends on future commit (" << commandCommitCount
<< "), Currently at: " << commitCount << ", storing for later. Queue size: " << newQueueSize);
server._futureCommitCommandTimeouts.insert(make_pair(command->timeout(), commandCommitCount));
server._futureCommitCommands.insert(make_pair(commandCommitCount, move(command)));
// Don't count this as `in progress`, it's just sitting there.
if (newQueueSize > 100) {
SHMMM("server._futureCommitCommands.size() == " << newQueueSize);
}
continue;
}
if (command->request.isSet("mockRequest")) {
SINFO("mockRequest set for command '" << command->request.methodLine << "'.");
}
// See if this is a feasible command to write parallel. If not, then be ready to forward it to the sync
// thread, if it doesn't finish in peek.
bool canWriteParallel = server._multiWriteEnabled.load();
if (canWriteParallel) {
// If multi-write is enabled, then we need to make sure the command isn't blacklisted.
shared_lock<decltype(_blacklistedParallelCommandMutex)> lock(_blacklistedParallelCommandMutex);
canWriteParallel =
(_blacklistedParallelCommands.find(command->request.methodLine) == _blacklistedParallelCommands.end());
}
// More checks for parallel writing.
canWriteParallel = canWriteParallel && (state == SQLiteNode::LEADING);
canWriteParallel = canWriteParallel && (command->writeConsistency == SQLiteNode::ASYNC);
// If all the other checks have passed, and we haven't sent a quorum command to the sync thread in a while,
// auto-promote one.
if (canWriteParallel) {
uint64_t now = STimeNow();
if (now > (server._lastQuorumCommandTime + (server._quorumCheckpointSeconds * 1'000'000))) {
SINFO("Forcing QUORUM for command '" << command->request.methodLine << "'.");
server._lastQuorumCommandTime = now;
command->writeConsistency = SQLiteNode::QUORUM;
canWriteParallel = false;
}
}
// We'll retry on conflict up to this many times.
int retry = server._maxConflictRetries.load();
while (retry) {
// Block if a checkpoint is happening so we don't interrupt it.
db.waitForCheckpoint();
// If the command has any httpsRequests from a previous `peek`, we won't peek it again unless the
// command has specifically asked for that.
// If peek succeeds, then it's finished, and all we need to do is respond to the command at the bottom.
bool calledPeek = false;
BedrockCore::RESULT peekResult = BedrockCore::RESULT::INVALID;
if (command->repeek || !command->httpsRequests.size()) {
peekResult = core.peekCommand(command, threadId == 0);
calledPeek = true;
}
// This drops us back to the top of the loop.
if (peekResult == BedrockCore::RESULT::ABANDONED_FOR_CHECKPOINT) {
SINFO("[checkpoint] Re-trying abandoned command (from peek) in worker thread");
continue;
}
if (!calledPeek || peekResult == BedrockCore::RESULT::SHOULD_PROCESS) {
// We've just unsuccessfully peeked a command, which means we're in a state where we might want to
// write it. We'll flag that here, to keep the node from falling out of LEADING/STANDINGDOWN
// until we're finished with this command.
if (command->httpsRequests.size()) {
// This *should* be impossible, but previous bugs have existed where it's feasible that we call
// `peekCommand` while leading, and by the time we're done, we're FOLLOWING, so we check just
// in case we ever introduce another similar bug.
if (state != SQLiteNode::LEADING && state != SQLiteNode::STANDINGDOWN) {
SALERT("Not leading or standing down (" << SQLiteNode::stateName(state)
<< ") but have outstanding HTTPS command: " << command->request.methodLine
<< ", returning 500.");
command->response.methodLine = "500 STANDDOWN TIMEOUT";
server._reply(command);
core.rollback();
break;
}
// If the command isn't complete, we'll re-queue it.
if (command->repeek || !command->areHttpsRequestsComplete()) {