-
Notifications
You must be signed in to change notification settings - Fork 85
/
BedrockServer.cpp
2426 lines (2138 loc) · 120 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 <csignal>
#include <cstring>
#include <fstream>
#include <sys/resource.h>
#include <sys/time.h>
#include <bedrockVersion.h>
#include <BedrockCore.h>
#include <BedrockPlugin.h>
#include <libstuff/libstuff.h>
#include <libstuff/SRandom.h>
#include <libstuff/AutoTimer.h>
#include <PageLockGuard.h>
#include <sqlitecluster/SQLitePeer.h>
set<string>BedrockServer::_blacklistedParallelCommands;
shared_timed_mutex BedrockServer::_blacklistedParallelCommandMutex;
thread_local atomic<SQLiteNodeState> BedrockServer::_nodeStateSnapshot = SQLiteNodeState::UNKNOWN;
void BedrockServer::syncWrapper()
{
// Initialize the thread.
SInitialize(_syncThreadName);
isSyncThread = true;
while(true) {
// If the server's set to be detached, we wait until that flag is unset, and then start the sync thread.
if (_detach) {
// If we're set detached, we assume we'll be re-attached eventually, and then be `RUNNING`.
SINFO("Bedrock server entering detached state.");
_shutdownState.store(RUNNING);
// Detach any plugins now
for (auto plugin : plugins) {
plugin.second->onDetach();
}
_pluginsDetached = true;
while (_detach) {
if (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.");
_resetServer();
}
sync();
// Now that we've run the sync thread, we can exit if it hasn't set _detach again.
if (!_detach) {
break;
}
}
// Break out of `poll` in main.cpp.
_notifyDone.push(true);
SINFO("Exiting syncWrapper");
}
shared_ptr<SQLitePool> BedrockServer::getDBPool() {
return _dbPool;
}
void BedrockServer::sync()
{
// 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.
SINFO("Note: thread::hardware_concurrency() is: " << thread::hardware_concurrency());
workerThreads = workerThreads ? workerThreads : max(1u, thread::hardware_concurrency());
// A minimum of *2* worker threads are required. One for blocking writes, one for other commands.
if (workerThreads < 2) {
workerThreads = 2;
}
size_t journalTables = workerThreads;
if (args.isSet("-journalTables")) {
journalTables = args.calcU64("-journalTables");
}
// 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.
SINFO("Setting dbPool size to: " << _dbPoolSize);
_dbPool = make_shared<SQLitePool>(_dbPoolSize, args["-db"], args.calc("-cacheSize"), args.calc("-maxJournalSize"), journalTables, mmapSizeGB, args.isSet("-hctree"));
SQLite& db = _dbPool->getBase();
// Initialize the command processor.
BedrockCore core(db, *this);
// 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(&_syncNode, make_shared<SQLiteNode>(*this, _dbPool, args["-nodeName"], args["-nodeHost"],
args["-peerList"], args.calc("-priority"), firstTimeout,
_version, args["-commandPortPrivate"]));
_clusterMessenger = make_shared<SQLiteClusterMessenger>(_syncNode);
// 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(&BedrockServer::worker, this, 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(_futureCommitCommandMutex);
// First, see if anything has timed out, and move that back to the main queue.
if (_futureCommitCommandTimeouts.size()) {
uint64_t now = STimeNow();
auto it = _futureCommitCommandTimeouts.begin();
while (it != _futureCommitCommandTimeouts.end() && it->first < now) {
// Find commands depending on this commit.
auto itPair = _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.
_commandQueue.push(move(cmdIt->second));
// And delete it, it's gone.
_futureCommitCommands.erase(cmdIt);
// Done.
break;
}
}
it++;
}
// And remove everything we just iterated through.
if (it != _futureCommitCommandTimeouts.begin()) {
_futureCommitCommandTimeouts.erase(_futureCommitCommandTimeouts.begin(), it);
}
}
// Anything that hasn't timed out might be ready to return because the commit count is up-to-date.
if (!_futureCommitCommands.empty()) {
uint64_t commitCount = db.getCommitCount();
auto it = _futureCommitCommands.begin();
while (it != _futureCommitCommands.end() && (it->first <= commitCount || _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);
_commandQueue.push(move(it->second));
// Remove it from the timed out list as well.
auto itPair = _futureCommitCommandTimeouts.equal_range(commandTimeout);
for (auto timeoutIt = itPair.first; timeoutIt != itPair.second; timeoutIt++) {
if (timeoutIt->second == it->first) {
_futureCommitCommandTimeouts.erase(timeoutIt);
break;
}
}
it++;
}
if (it != _futureCommitCommands.begin()) {
_futureCommitCommands.erase(_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 (_shutdownState.load() == COMMANDS_FINISHED) {
SINFO("All clients responded to, " << BedrockCommand::getCommandCount() << " commands remaining.");
if (_syncNode->beginShutdown()) {
SINFO("Beginning shuttdown of sync node.");
// This will cause us to skip the next `poll` iteration which avoids a 1 second wait.
_notifyDoneSync.push(true);
}
}
// 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;
// Pre-process any sockets the sync node is managing (i.e., communication with peer nodes).
_notifyDoneSync.prePoll(fdm);
_syncNode->prePoll(fdm);
// Add our command queues to our fd_map.
_syncNodeQueuedCommands.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);
if (SCheckSignal(SIGTERM)) {
_notifyDone.push(true);
}
}
// 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);
_syncNode->postPoll(fdm, nextActivity);
_syncNodeQueuedCommands.postPoll(fdm);
_notifyDoneSync.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.
SQLiteNodeState preUpdateState = _syncNode->getState();
if(command && committingCommand) {
void (*onPrepareHandler)(SQLite& db, int64_t tableID) = nullptr;
bool enabled = command->shouldEnableOnPrepareNotification(db, &onPrepareHandler);
if (enabled) {
_syncNode->onPrepareHandlerEnabled = enabled;
_syncNode->onPrepareHandler = onPrepareHandler;
}
} else {
_syncNode->onPrepareHandlerEnabled = false;
_syncNode->onPrepareHandler = nullptr;
}
while (_syncNode->update()) {}
_leaderVersion.store(_syncNode->getLeaderVersion());
// If we're not leading, move any commands from the blocking queue back to the main queue.
if (getState() != SQLiteNodeState::LEADING && getState() != preUpdateState) {
auto commands = _blockingCommandQueue.getAll();
SINFO("Moving " << commands.size() << " commands from blocking queue to main queue.");
for (auto& cmd : commands) {
_commandQueue.push(move(cmd));
}
}
// 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 == SQLiteNodeState::LEADING || preUpdateState == SQLiteNodeState::STANDINGDOWN) &&
(getState() != SQLiteNodeState::LEADING && getState() != SQLiteNodeState::STANDINGDOWN)) {
// If we bailed out while doing a upgradeDB, clear state
if (_upgradeInProgress) {
_upgradeInProgress = false;
if (committingCommand) {
db.rollback();
committingCommand = false;
}
}
// If we're not leading, we're not upgrading, but we will need to check for upgrades again next time we go leading, so be ready for that.
_upgradeCompleted = 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.
_commandQueue.push(move(command));
}
}
} catch (const out_of_range& e) {
if (dropped) {
SWARN("Abruptly stopped LEADING. Re-queued " << requeued << " commands, Dropped " << dropped << " commands.");
} else {
SINFO("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 (getState() != SQLiteNodeState::LEADING && getState() != SQLiteNodeState::FOLLOWING && getState() != SQLiteNodeState::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 != SQLiteNodeState::LEADING && getState() == SQLiteNodeState::LEADING) ||
(getState() == SQLiteNodeState::LEADING && _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).
_upgradeInProgress = true;
if (!_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 (_upgradeDB(db)) {
committingCommand = true;
_syncNode->startCommit(SQLiteNode::QUORUM);
_lastQuorumCommandTime = STimeNow();
// This interrupts the next poll loop immediately. This prevents a 1-second wait when running as a single server.
_notifyDoneSync.push(true);
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.
_upgradeInProgress = false;
_upgradeCompleted = true;
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 && !_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 (_upgradeInProgress) {
if (_syncNode->commitSucceeded()) {
_upgradeInProgress = false;
_upgradeCompleted = true;
SINFO("UpgradeDB succeeded, done.");
_notifyDone.push(true);
} else {
SINFO("UpgradeDB failed, trying again.");
}
continue;
}
if (command->shouldPostProcess() && command->response.methodLine == "200 OK") {
// PostProcess if the command should run postProcess, and there have been no errors thrown thus far.
core.postProcessCommand(command, false);
}
if (_syncNode->commitSucceeded()) {
if (command) {
SINFO("[performance] Sync thread finished committing command " << command->request.methodLine);
_conflictManager.recordTables(command->request.methodLine, db.getTablesUsed());
// Otherwise, save the commit count, mark this command as complete, and reply.
command->response["commitCount"] = to_string(db.getCommitCount());
command->complete = true;
_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 {
// 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 (getState() == SQLiteNodeState::FOLLOWING && _syncNode->leaderState() == SQLiteNodeState::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.");
_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([&](){
_clusterMessenger->runOnAll(_generateCrashMessage(command));
return addLogParams("CRASHING from BedrockServer::sync, command:" + command->request.methodLine, command->request.nameValueMap);
});
// And now we'll decide how to handle it.
if (getState() == SQLiteNodeState::LEADING || getState() == SQLiteNodeState::STANDINGDOWN) {
// 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()) {
if (command->shouldPrePeek() && !command->repeek) {
core.prePeekCommand(command, false);
}
// This command finsihed in prePeek, which likely means it threw.
// We'll respond to it now, either directly or by sending it back to the sync thread.
if (command->complete) {
SINFO("Command completed in prePeek, replying now.");
_reply(command);
break;
}
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);
_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 {
SERROR("peekCommand (" << command->request.getVerb() << ") returned invalid result code: " << (int)result);
}
// If this command attempted an HTTP request, kill it.
if (command->httpsRequests.size()) {
SWARN("Killing command " << command->request.methodLine << " that attempted HTTPS request in sync thread.");
command->response.clear();
command->response.methodLine = "500 Refused";
command->complete = true;
_reply(command);
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);
_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.
_reply(command);
} else if (result == BedrockCore::RESULT::SERVER_NOT_LEADING) {
SINFO("Server stopped leading, re-queueing commad");
_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 (getState() == SQLiteNodeState::FOLLOWING) {
SWARN("Sync thread has command when following. Re-queueing");
_commandQueue.push(move(command));
}
}
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 (!_syncNode->shutdownComplete() || BedrockCommand::getCommandCount());
SSetSignalHandlerDieFunc([](){
return "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 (_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.
_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.
if (getState() > SQLiteNodeState::WAITING) {
// This should no longer be possible with fast shutdown.
SWARN("Sync thread exiting in state " << SQLiteNode::stateName(getState()) << ".");
}
// 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 (_commandQueue.size()) {
SWARN("Sync thread shut down with " << _commandQueue.size() << " queued commands. Commands were: "
<< SComposeList(_commandQueue.getRequestMethodLines()) << ". Clearing.");
_commandQueue.clear();
}
// Same for the blocking queue.
if (_blockingCommandQueue.size()) {
SWARN("Sync thread shut down with " << _blockingCommandQueue.size() << " blocking queued commands. Commands were: "
<< SComposeList(_blockingCommandQueue.getRequestMethodLines()) << ". Clearing.");
_blockingCommandQueue.clear();
}
for (auto plugin : plugins) {
plugin.second->serverStopping();
}
// We clear this before the _syncNode that it references.
_clusterMessenger.reset();
// Release our handle to this pointer. Any other functions that are still using it will keep the object alive
// until they return.
atomic_store(&_syncNode, shared_ptr<SQLiteNode>(nullptr));
// If we're not detaching, save that we're shutting down.
if (!_detach) {
ofstream file("/var/log/bedrock_shutdown", std::ios::app);
if (file) {
file << "shutdown " << getpid() << " " << SComposeTime("%Y-%m-%dT%H:%M:%S", STimeNow()) << endl;
file.close();
}
}
// Release the current DB pool, and zero out our pointer. If any socket threads hold a handle to `_syncNode`, they will keep this in existence
// until they release it.
_dbPool = nullptr;
// We're really done, store our flag so main() can be aware.
_syncLoopShouldBeRunning.store(false);
}
void BedrockServer::worker(int threadId)
{
// Worker 0 is the "blockingCommit" thread.
SInitialize(threadId ? "worker" + to_string(threadId) : "blockingCommit");
// 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 ? _commandQueue : _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([&](){
return "Die function called early with no command, probably died in `commandQueue.get`.";
});
// Get the next one.
command = commandQueue.get(100000);
SAUTOPREFIX(command->request);
SINFO("Dequeued command " << command->request.methodLine << " (" << command->id << ") in worker, "
<< commandQueue.size() << " commands in " << (threadId ? "" : "blocking") << " queue.");
runCommand(move(command), threadId == 0, false);
} catch (const BedrockCommandQueue::timeout_error& e) {
// No commands to process after 1 second.
// If the sync node has shut down, we can return now, there will be no more work to do.
if (_shutdownState.load() == DONE) {
SINFO("No commands found in queue and DONE.");
return;
}
}
}
}
void BedrockServer::runCommand(unique_ptr<BedrockCommand>&& _command, bool isBlocking, bool hasDedicatedThread) {
// If there's no sync node (because we're detaching/attaching), we can only queue a command for later.
// Also,if this command is scheduled in the future, we can't just run it, we need to enqueue it to run at that point.
// This functionality will go away as we remove the queues from bedrock, and so this can be removed at that time.
{
auto _syncNodeCopy = atomic_load(&_syncNode);
if (!_syncNodeCopy || _command->request.calcU64("commandExecuteTime") > STimeNow()) {
_commandQueue.push(move(_command));
return;
}
}
// This takes ownership of the passed command. By calling the move constructor, the caller's unique_ptr is now empty, and so when the one here goes out of scope (i.e., this function
// returns), the command is destroyed.
unique_ptr<BedrockCommand> command(move(_command));
SAUTOPREFIX(command->request);
// 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([&](){
_clusterMessenger->runOnAll(_generateCrashMessage(command));
return addLogParams("CRASHING from BedrockServer::runCommand, command:" + command->request.methodLine, command->request.nameValueMap);
});
// If we dequeue a status or control command, handle it immediately.
if (_handleIfStatusOrControlCommand(command)) {
return;
}
// Check if this command would be likely to cause a crash
if (_wouldCrash(command)) {
// If so, make a lot of noise, and respond 500 without processing it.
SALERT("REJECTING CRASH-INDUCING COMMAND, command:" + command->request.methodLine, command->request.nameValueMap);
command->response.methodLine = "500 Refused";
command->complete = true;
_reply(command);
return;
}
// If we're following, we will automatically escalate any command that's:
// 1. Not already complete (complete commands are likely already returned from leader with legacy escalation)
// and is marked as `escalateImmediately` (which lets them skip the queue, which is particularly useful if they're waiting
// for a previous commit to be delivered to this follower);
// 2. Any commands if the current version of the code is not the same one as leader is executing.
if (getState() == SQLiteNodeState::FOLLOWING && !command->complete && (command->escalateImmediately || _version != _leaderVersion.load())) {
auto _clusterMessengerCopy = _clusterMessenger;
if (command->escalateImmediately && _clusterMessengerCopy && _clusterMessengerCopy->runOnPeer(*command, true)) {
// command->complete is now true for this command. It will get handled a few lines below.
SINFO("Immediately escalated " << command->request.methodLine << " to leader.");
} else if (_version != _leaderVersion.load() && _clusterMessengerCopy && _clusterMessengerCopy->runOnPeer(*command, false)) {
SINFO("Escalated " << command->request.methodLine << " to follower peer.");
} else {
SINFO("Couldn't escalate command " << command->request.methodLine << " to " << (command->escalateImmediately ? "leader" : "follower peer") << ", queuing it again.");
_commandQueue.push(move(command));
return;
}
}
// If we happen to be synchronizing but the command port is open, which is an uncommon but possible scenario (i.e., we were momentarily disconnected from leader and need to catch back
// up), we will forward commands to any other follower similar to if we were running as a different version from leader.
if (getState() == SQLiteNodeState::SYNCHRONIZING) {
auto _clusterMessengerCopy = _clusterMessenger;
bool result = _clusterMessengerCopy->runOnPeer(*command, false);
if (result) {
SINFO("Synchronizing while accepting commands; successfully forwarded the command to peer", {{"command", command->request.methodLine}});
} else {
SWARN("Synchronizing while accepting commands, but failed to forward the command to peer.", {{"command", command->request.methodLine}});
}
}
// 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.
// 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) {
_reply(command);
}
// This command is done, move on to the next one.
return;
}
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 = _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());
}
int64_t lastConflictPage = 0;
string lastConflictTable;
while (true) {
// We just spin until the node looks ready to go. Typically, this doesn't happen expect briefly at startup.
size_t waitCount = 0;
while (_upgradeInProgress || (getState() != SQLiteNodeState::LEADING && getState() != SQLiteNodeState::FOLLOWING)) {
// 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);
waitCount++;
}
if (waitCount) {
SINFO("Waited for " << waitCount << " loops for node to be ready.");
}
// More checks for parallel writing.
canWriteParallel = canWriteParallel && (getState() == SQLiteNodeState::LEADING);
canWriteParallel = canWriteParallel && (command->writeConsistency == SQLiteNode::ASYNC);
// If there are outstanding HTTPS requests on this command (from a previous call to `peek`) we process them here.
size_t networkLoopCount = 0;
uint64_t postPollCumulativeTime = 0;
while (!command->areHttpsRequestsComplete()) {
networkLoopCount++;
fd_map fdm;
command->prePoll(fdm);
// Determine how long we'll wait in `poll`.
uint64_t maxWaitUs = 0;
// The default case is to wait until the command will time out.
uint64_t now = STimeNow();
if (now < command->timeout()) {
maxWaitUs = command->timeout() - now;
} else {
// The command is already timed out. This will hit the check for core.isTimedOut(command) below.
break;
}
// We never wait more than 1 second in `poll`. There are two uses for this. One is that at shutdown, we want to kill any sockets that have are making no progress.
// We don't want these to be stuck sitting for 5 minutes doing nothing while thew server hangs, so we will interrupt every second to check on them.
// The other case is that there can be no sockets at all.
// Why would there be no sockets? It's because Auth::Stripe, as a rate-limiting feature, attaches sockets to requests after their made.
// This means a request can sit around with no actual socket attached to it for some length of time until it's turn to talk to Stripe comes up.
// If that happens though, and we're sitting in `poll` when it becomes our turn, we will wait the full five minute timeout of the original `poll`
// call before we time out and try again wit the newly-attached socket.
// Setting this to one second lets us try again more frequently.
maxWaitUs = min(maxWaitUs, 1'000'000ul);
bool shuttingDown = false;
auto _syncNodeCopy = atomic_load(&_syncNode);
if (_shutdownState.load() != RUNNING || (_syncNodeCopy && _syncNodeCopy->getState() == SQLiteNodeState::STANDINGDOWN)) {
shuttingDown = true;
}
// Ok, go ahead and `poll`.
S_poll(fdm, maxWaitUs);
// The 3rd parameter to `postPoll` here is the total allowed idle time on this connection. We will kill connections that do nothing at all after 5 minutes normally,
// or after only 5 seconds when we're shutting down so that we can clean up and move along.
uint64_t ignore{0};
auto start = STimeNow();
command->postPoll(fdm, ignore, shuttingDown ? 5'000 : 300'000);
postPollCumulativeTime += (STimeNow() - start);
}
if (networkLoopCount) {
SINFO("Completed HTTPS request in " << networkLoopCount << " loops with " << postPollCumulativeTime << "us total time in postPoll");
}
// Get a DB handle to work on. This will automatically be returned when dbScope goes out of scope.
if (!_dbPool) {
SERROR("Can't run a command with no DB pool");
}
{
SQLiteScopedHandle dbScope(*_dbPool, _dbPool->getIndex());
SQLite& db = dbScope.db();
BedrockCore core(db, *this);
// 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)) {
_reply(command);
return;
}
// 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(_futureCommitCommandMutex);
auto newQueueSize = _futureCommitCommands.size() + 1;
SINFO("Command (" << command->request.methodLine << ") depends on future commit (" << commandCommitCount
<< "), Currently at: " << commitCount << ", storing for later. Queue size: " << newQueueSize);
_futureCommitCommandTimeouts.insert(make_pair(command->timeout(), commandCommitCount));
_futureCommitCommands.insert(make_pair(commandCommitCount, move(command)));
// Don't count this as `in progress`, it's just sitting there.
if (newQueueSize > 100) {
SHMMM("_futureCommitCommands.size() == " << newQueueSize);
}
return;
}
// If we've changed out of leading, we need to notice that.
canWriteParallel = canWriteParallel && (getState() == SQLiteNodeState::LEADING);
// If the command should run prePeek, do that now .
if (!command->repeek && !command->httpsRequests.size() && command->shouldPrePeek()) {
core.prePeekCommand(command, isBlocking);
if (command->complete) {
_reply(command);
break;
}
}
auto *timer = new BedrockCore::AutoTimer(command, BedrockCommand::QUEUE_PAGE_LOCK);
uint64_t conflictLockStartTime = 0;
if (lastConflictPage) {
conflictLockStartTime = STimeNow();
}
{
PageLockGuard pageLock(lastConflictPage);
if (lastConflictPage) {
SINFO("Waited " << (STimeNow() - conflictLockStartTime) << "us for lock on db page " << lastConflictPage << ".");
}
delete timer;
// 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, isBlocking);
calledPeek = true;
}
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()) {
if (command->repeek || !command->areHttpsRequestsComplete()) {
// Roll back the existing transaction, but only if we are inside an transaction
if (calledPeek) {
core.rollback();
}
// Jump back to the top of our main `while (true)` loop and run the network activity loop again.
continue;
}
} else {
// If we haven't sent a quorum command to the sync thread in a while, auto-promote one.
uint64_t now = STimeNow();
if (now > (_lastQuorumCommandTime + (_quorumCheckpointSeconds * 1'000'000))) {
SINFO("Forcing QUORUM for command '" << command->request.methodLine << "'.");
_lastQuorumCommandTime = now;
command->writeConsistency = SQLiteNode::QUORUM;
canWriteParallel = false;
}
}
// Peek wasn't enough to handle this command. See if we think it should be writable in parallel.
if (!canWriteParallel) {
// Roll back the transaction, it'll get re-run in the sync thread.
core.rollback();
dbScope.release();
auto _clusterMessengerCopy = _clusterMessenger;
if (getState() == SQLiteNodeState::LEADING) {
// Limit the command timeout to 20s to avoid blocking the sync thread long enough to cause the cluster to give up and elect a new leader (causing a fork), which happens
// after 30s.
command->setTimeout(20'000);
SINFO("Sending non-parallel command " << command->request.methodLine
<< " to sync thread. Sync thread has " << _syncNodeQueuedCommands.size() << " queued commands.");
_syncNodeQueuedCommands.push(move(command));
} else if (_clusterMessengerCopy && _clusterMessengerCopy->runOnPeer(*command, true)) {
SINFO("Escalated " << command->request.methodLine << " to leader and complete, responding.");
_reply(command);
} else {
// TODO: Something less naive that considers how these failures happen rather than a simple
// endless loop of requeue and retry.
SINFO("Couldn't escalate command " << command->request.methodLine << " to leader. We are in state: " << SQLiteNode::stateName(getState()));
_commandQueue.push(move(command));
}
// Done with this command, look for the next one.
break;
}
// In this case, there's nothing blocking us from processing this in a worker, so let's try it.
BedrockCore::RESULT result = core.processCommand(command, isBlocking);
if (result == BedrockCore::RESULT::NEEDS_COMMIT) {
// If processCommand returned true, then we need to do a commit. Otherwise, the command is
// done, and we just need to respond. Before we commit, we need to grab the sync thread