/
master_slave.cpp
1471 lines (1302 loc) · 52.3 KB
/
master_slave.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
/**
* Copyright (C) 2008-2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
/* Collections we use:
local.sources - indicates what sources we pull from as a "slave", and the last update of
each
local.oplog.$main - our op log as "master"
local.dbinfo.<dbname> - no longer used???
local.pair.startup - [deprecated] can contain a special value indicating for a pair that we
have the master copy.
used when replacing other half of the pair which has permanently failed.
local.pair.sync - [deprecated] { initialsynccomplete: 1 }
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kReplication
#include "mongo/platform/basic.h"
#include "mongo/db/repl/master_slave.h"
#include <pcrecpp.h>
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/catalog/database_catalog_entry.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/client.h"
#include "mongo/db/cloner.h"
#include "mongo/db/commands.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/ops/update.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/repl/handshake_args.h"
#include "mongo/db/repl/oplog.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/replication_coordinator_global.h"
#include "mongo/db/repl/sync_tail.h"
#include "mongo/db/server_parameters.h"
#include "mongo/db/service_context.h"
#include "mongo/db/storage/storage_options.h"
#include "mongo/stdx/thread.h"
#include "mongo/util/exit.h"
#include "mongo/util/log.h"
#include "mongo/util/quick_exit.h"
using std::cout;
using std::endl;
using std::max;
using std::min;
using std::set;
using std::stringstream;
using std::unique_ptr;
using std::vector;
namespace mongo {
namespace repl {
namespace {
time_t lastForcedResync = 0;
const int forceReconnect = -1;
const int restartSync = 0;
const int restartSyncAfterSleep = 1;
} // namespace
void pretouchOperation(OperationContext* txn, const BSONObj& op);
void pretouchN(vector<BSONObj>&, unsigned a, unsigned b);
/* if 1 sync() is running */
volatile int syncing = 0;
volatile int relinquishSyncingSome = 0;
/* output by the web console */
const char* replInfo = "";
struct ReplInfo {
ReplInfo(const char* msg) {
replInfo = msg;
}
~ReplInfo() {
replInfo = "?";
}
};
ReplSource::ReplSource(OperationContext* txn) {
nClonedThisPass = 0;
ensureMe(txn);
}
ReplSource::ReplSource(OperationContext* txn, BSONObj o) : nClonedThisPass(0) {
only = o.getStringField("only");
hostName = o.getStringField("host");
_sourceName = o.getStringField("source");
uassert(10118, "'host' field not set in sources collection object", !hostName.empty());
uassert(10119, "only source='main' allowed for now with replication", sourceName() == "main");
BSONElement e = o.getField("syncedTo");
if (!e.eoo()) {
uassert(10120,
"bad sources 'syncedTo' field value",
e.type() == Date || e.type() == bsonTimestamp);
Timestamp tmp(e.date());
syncedTo = tmp;
}
BSONObj dbsObj = o.getObjectField("dbsNextPass");
if (!dbsObj.isEmpty()) {
BSONObjIterator i(dbsObj);
while (1) {
BSONElement e = i.next();
if (e.eoo())
break;
addDbNextPass.insert(e.fieldName());
}
}
dbsObj = o.getObjectField("incompleteCloneDbs");
if (!dbsObj.isEmpty()) {
BSONObjIterator i(dbsObj);
while (1) {
BSONElement e = i.next();
if (e.eoo())
break;
incompleteCloneDbs.insert(e.fieldName());
}
}
ensureMe(txn);
}
/* Turn our C++ Source object into a BSONObj */
BSONObj ReplSource::jsobj() {
BSONObjBuilder b;
b.append("host", hostName);
b.append("source", sourceName());
if (!only.empty())
b.append("only", only);
if (!syncedTo.isNull())
b.append("syncedTo", syncedTo);
BSONObjBuilder dbsNextPassBuilder;
int n = 0;
for (set<std::string>::iterator i = addDbNextPass.begin(); i != addDbNextPass.end(); i++) {
n++;
dbsNextPassBuilder.appendBool(*i, 1);
}
if (n)
b.append("dbsNextPass", dbsNextPassBuilder.done());
BSONObjBuilder incompleteCloneDbsBuilder;
n = 0;
for (set<std::string>::iterator i = incompleteCloneDbs.begin(); i != incompleteCloneDbs.end();
i++) {
n++;
incompleteCloneDbsBuilder.appendBool(*i, 1);
}
if (n)
b.append("incompleteCloneDbs", incompleteCloneDbsBuilder.done());
return b.obj();
}
void ReplSource::ensureMe(OperationContext* txn) {
std::string myname = getHostName();
// local.me is an identifier for a server for getLastError w:2+
bool exists = Helpers::getSingleton(txn, "local.me", _me);
if (!exists || !_me.hasField("host") || _me["host"].String() != myname) {
ScopedTransaction transaction(txn, MODE_IX);
Lock::DBLock dblk(txn->lockState(), "local", MODE_X);
WriteUnitOfWork wunit(txn);
// clean out local.me
Helpers::emptyCollection(txn, "local.me");
// repopulate
BSONObjBuilder b;
b.appendOID("_id", 0, true);
b.append("host", myname);
_me = b.obj();
Helpers::putSingleton(txn, "local.me", _me);
wunit.commit();
}
_me = _me.getOwned();
}
void ReplSource::save(OperationContext* txn) {
BSONObjBuilder b;
verify(!hostName.empty());
b.append("host", hostName);
// todo: finish allowing multiple source configs.
// this line doesn't work right when source is null, if that is allowed as it is now:
// b.append("source", _sourceName);
BSONObj pattern = b.done();
BSONObj o = jsobj();
LOG(1) << "Saving repl source: " << o << endl;
{
OldClientContext ctx(txn, "local.sources", false);
const NamespaceString requestNs("local.sources");
UpdateRequest request(requestNs);
request.setQuery(pattern);
request.setUpdates(o);
request.setUpsert();
UpdateResult res = update(txn, ctx.db(), request);
verify(!res.modifiers);
verify(res.numMatched == 1 || !res.upserted.isEmpty());
}
}
static void addSourceToList(OperationContext* txn,
ReplSource::SourceVector& v,
ReplSource& s,
ReplSource::SourceVector& old) {
if (!s.syncedTo.isNull()) { // Don't reuse old ReplSource if there was a forced resync.
for (ReplSource::SourceVector::iterator i = old.begin(); i != old.end();) {
if (s == **i) {
v.push_back(*i);
old.erase(i);
return;
}
i++;
}
}
v.push_back(std::shared_ptr<ReplSource>(new ReplSource(s)));
}
/* we reuse our existing objects so that we can keep our existing connection
and cursor in effect.
*/
void ReplSource::loadAll(OperationContext* txn, SourceVector& v) {
const char* localSources = "local.sources";
OldClientContext ctx(txn, localSources, false);
SourceVector old = v;
v.clear();
const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings();
if (!replSettings.getSource().empty()) {
// --source <host> specified.
// check that no items are in sources other than that
// add if missing
int n = 0;
unique_ptr<PlanExecutor> exec(InternalPlanner::collectionScan(
txn, localSources, ctx.db()->getCollection(localSources), PlanExecutor::YIELD_MANUAL));
BSONObj obj;
PlanExecutor::ExecState state;
while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
n++;
ReplSource tmp(txn, obj);
if (tmp.hostName != replSettings.getSource()) {
log() << "--source " << replSettings.getSource() << " != " << tmp.hostName
<< " from local.sources collection" << endl;
log() << "for instructions on changing this slave's source, see:" << endl;
log() << "http://dochub.mongodb.org/core/masterslave" << endl;
log() << "terminating mongod after 30 seconds" << endl;
sleepsecs(30);
quickExit(EXIT_REPLICATION_ERROR);
}
if (tmp.only != replSettings.getOnly()) {
log() << "--only " << replSettings.getOnly() << " != " << tmp.only
<< " from local.sources collection" << endl;
log() << "terminating after 30 seconds" << endl;
sleepsecs(30);
quickExit(EXIT_REPLICATION_ERROR);
}
}
uassert(17065, "Internal error reading from local.sources", PlanExecutor::IS_EOF == state);
uassert(10002, "local.sources collection corrupt?", n < 2);
if (n == 0) {
// source missing. add.
ReplSource s(txn);
s.hostName = replSettings.getSource();
s.only = replSettings.getOnly();
s.save(txn);
}
} else {
try {
massert(10384, "--only requires use of --source", replSettings.getOnly().empty());
} catch (...) {
quickExit(EXIT_BADOPTIONS);
}
}
unique_ptr<PlanExecutor> exec(InternalPlanner::collectionScan(
txn, localSources, ctx.db()->getCollection(localSources), PlanExecutor::YIELD_MANUAL));
BSONObj obj;
PlanExecutor::ExecState state;
while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
ReplSource tmp(txn, obj);
if (tmp.syncedTo.isNull()) {
DBDirectClient c(txn);
BSONObj op = c.findOne("local.oplog.$main",
QUERY("op" << NE << "n").sort(BSON("$natural" << -1)));
if (!op.isEmpty()) {
tmp.syncedTo = op["ts"].timestamp();
}
}
addSourceToList(txn, v, tmp, old);
}
uassert(17066, "Internal error reading from local.sources", PlanExecutor::IS_EOF == state);
}
bool ReplSource::throttledForceResyncDead(OperationContext* txn, const char* requester) {
if (time(0) - lastForcedResync > 600) {
forceResyncDead(txn, requester);
lastForcedResync = time(0);
return true;
}
return false;
}
void ReplSource::forceResyncDead(OperationContext* txn, const char* requester) {
if (!replAllDead)
return;
SourceVector sources;
ReplSource::loadAll(txn, sources);
for (SourceVector::iterator i = sources.begin(); i != sources.end(); ++i) {
log() << requester << " forcing resync from " << (*i)->hostName << endl;
(*i)->forceResync(txn, requester);
}
replAllDead = 0;
}
class HandshakeCmd : public Command {
public:
void help(stringstream& h) const {
h << "internal";
}
HandshakeCmd() : Command("handshake") {}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
virtual bool slaveOk() const {
return true;
}
virtual bool adminOnly() const {
return false;
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::internal);
out->push_back(Privilege(ResourcePattern::forClusterResource(), actions));
}
virtual bool run(OperationContext* txn,
const std::string& ns,
BSONObj& cmdObj,
int options,
std::string& errmsg,
BSONObjBuilder& result) {
HandshakeArgs handshake;
Status status = handshake.initialize(cmdObj);
if (!status.isOK()) {
return appendCommandStatus(result, status);
}
ReplClientInfo::forClient(txn->getClient()).setRemoteID(handshake.getRid());
status = getGlobalReplicationCoordinator()->processHandshake(txn, handshake);
return appendCommandStatus(result, status);
}
} handshakeCmd;
bool replHandshake(DBClientConnection* conn, const OID& myRID) {
std::string myname = getHostName();
BSONObjBuilder cmd;
cmd.append("handshake", myRID);
BSONObj res;
bool ok = conn->runCommand("admin", cmd.obj(), res);
// ignoring for now on purpose for older versions
LOG(ok ? 1 : 0) << "replHandshake result: " << res << endl;
return true;
}
bool ReplSource::_connect(OplogReader* reader, const HostAndPort& host, const OID& myRID) {
if (reader->conn()) {
return true;
}
if (!reader->connect(host)) {
return false;
}
if (_doHandshake && !replHandshake(reader->conn(), myRID)) {
return false;
}
return true;
}
void ReplSource::forceResync(OperationContext* txn, const char* requester) {
BSONObj info;
{
// This is always a GlobalWrite lock (so no ns/db used from the context)
invariant(txn->lockState()->isW());
Lock::TempRelease tempRelease(txn->lockState());
if (!_connect(&oplogReader,
HostAndPort(hostName),
getGlobalReplicationCoordinator()->getMyRID())) {
msgassertedNoTrace(14051, "unable to connect to resync");
}
/* todo use getDatabaseNames() method here */
bool ok = oplogReader.conn()->runCommand(
"admin", BSON("listDatabases" << 1), info, QueryOption_SlaveOk);
massert(10385, "Unable to get database list", ok);
}
BSONObjIterator i(info.getField("databases").embeddedObject());
while (i.moreWithEOO()) {
BSONElement e = i.next();
if (e.eoo())
break;
std::string name = e.embeddedObject().getField("name").valuestr();
if (!e.embeddedObject().getBoolField("empty")) {
if (name != "local") {
if (only.empty() || only == name) {
resyncDrop(txn, name);
}
}
}
}
syncedTo = Timestamp();
addDbNextPass.clear();
save(txn);
}
Status ReplSource::_updateIfDoneWithInitialSync() {
const auto usedToDoHandshake = _doHandshake;
if (!usedToDoHandshake && addDbNextPass.empty() && incompleteCloneDbs.empty()) {
_doHandshake = true;
oplogReader.resetConnection();
const auto myRID = getGlobalReplicationCoordinator()->getMyRID();
if (!_connect(&oplogReader, HostAndPort{hostName}, myRID)) {
return {ErrorCodes::MasterSlaveConnectionFailure,
str::stream() << "could not connect to " << hostName << " with rid: "
<< myRID.toString()};
} else {
return {ErrorCodes::Interrupted, "Initial Sync is done."};
}
}
return Status::OK();
}
void ReplSource::resyncDrop(OperationContext* txn, const std::string& dbName) {
log() << "resync: dropping database " << dbName;
invariant(txn->lockState()->isW());
Database* const db = dbHolder().get(txn, dbName);
if (!db) {
log() << "resync: dropping database " << dbName
<< " - database does not exist. nothing to do.";
return;
}
Database::dropDatabase(txn, db);
}
/* grab initial copy of a database from the master */
void ReplSource::resync(OperationContext* txn, const std::string& dbName) {
const std::string db(dbName); // need local copy of the name, we're dropping the original
resyncDrop(txn, db);
{
log() << "resync: cloning database " << db << " to get an initial copy" << endl;
ReplInfo r("resync: cloning a database");
CloneOptions cloneOptions;
cloneOptions.fromDB = db;
cloneOptions.slaveOk = true;
cloneOptions.useReplAuth = true;
cloneOptions.snapshot = true;
Cloner cloner;
Status status = cloner.copyDb(txn, db, hostName.c_str(), cloneOptions, NULL);
if (!status.isOK()) {
if (status.code() == ErrorCodes::DatabaseDifferCase) {
resyncDrop(txn, db);
log() << "resync: database " << db
<< " not valid on the master due to a name conflict, dropping.";
return;
} else {
log() << "resync of " << db << " from " << hostName
<< " failed due to: " << redact(status);
throw SyncException();
}
}
}
log() << "resync: done with initial clone for db: " << db << endl;
}
static DatabaseIgnorer ___databaseIgnorer;
void DatabaseIgnorer::doIgnoreUntilAfter(const std::string& db, const Timestamp& futureOplogTime) {
if (futureOplogTime > _ignores[db]) {
_ignores[db] = futureOplogTime;
}
}
bool DatabaseIgnorer::ignoreAt(const std::string& db, const Timestamp& currentOplogTime) {
if (_ignores[db].isNull()) {
return false;
}
if (_ignores[db] >= currentOplogTime) {
return true;
} else {
// The ignore state has expired, so clear it.
_ignores.erase(db);
return false;
}
}
bool ReplSource::handleDuplicateDbName(OperationContext* txn,
const BSONObj& op,
const char* ns,
const char* db) {
// We are already locked at this point
if (dbHolder().get(txn, ns) != NULL) {
// Database is already present.
return true;
}
BSONElement ts = op.getField("ts");
if ((ts.type() == Date || ts.type() == bsonTimestamp) &&
___databaseIgnorer.ignoreAt(db, ts.timestamp())) {
// Database is ignored due to a previous indication that it is
// missing from master after optime "ts".
return false;
}
if (dbHolder().getNamesWithConflictingCasing(db).empty()) {
// No duplicate database names are present.
return true;
}
Timestamp lastTime;
bool dbOk = false;
{
// This is always a GlobalWrite lock (so no ns/db used from the context)
invariant(txn->lockState()->isW());
Lock::TempRelease tempRelease(txn->lockState());
// We always log an operation after executing it (never before), so
// a database list will always be valid as of an oplog entry generated
// before it was retrieved.
BSONObj last =
oplogReader.findOne(this->ns().c_str(), Query().sort(BSON("$natural" << -1)));
if (!last.isEmpty()) {
BSONElement ts = last.getField("ts");
massert(14032,
"Invalid 'ts' in remote log",
ts.type() == Date || ts.type() == bsonTimestamp);
lastTime = Timestamp(ts.date());
}
BSONObj info;
bool ok = oplogReader.conn()->runCommand("admin", BSON("listDatabases" << 1), info);
massert(14033, "Unable to get database list", ok);
BSONObjIterator i(info.getField("databases").embeddedObject());
while (i.more()) {
BSONElement e = i.next();
const char* name = e.embeddedObject().getField("name").valuestr();
if (strcasecmp(name, db) != 0)
continue;
if (strcmp(name, db) == 0) {
// The db exists on master, still need to check that no conflicts exist there.
dbOk = true;
continue;
}
// The master has a db name that conflicts with the requested name.
dbOk = false;
break;
}
}
if (!dbOk) {
___databaseIgnorer.doIgnoreUntilAfter(db, lastTime);
incompleteCloneDbs.erase(db);
addDbNextPass.erase(db);
return false;
}
// Check for duplicates again, since we released the lock above.
auto duplicates = dbHolder().getNamesWithConflictingCasing(db);
// The database is present on the master and no conflicting databases
// are present on the master. Drop any local conflicts.
for (set<std::string>::const_iterator i = duplicates.begin(); i != duplicates.end(); ++i) {
___databaseIgnorer.doIgnoreUntilAfter(*i, lastTime);
incompleteCloneDbs.erase(*i);
addDbNextPass.erase(*i);
AutoGetDb autoDb(txn, *i, MODE_X);
Database::dropDatabase(txn, autoDb.getDb());
}
massert(14034,
"Duplicate database names present after attempting to delete duplicates",
dbHolder().getNamesWithConflictingCasing(db).empty());
return true;
}
void ReplSource::applyCommand(OperationContext* txn, const BSONObj& op) {
try {
Status status = applyCommand_inlock(txn, op, true);
uassert(28639, "Failure applying initial sync command", status.isOK());
} catch (UserException& e) {
log() << "sync: caught user assertion " << redact(e) << " while applying op: " << redact(op)
<< endl;
;
} catch (DBException& e) {
log() << "sync: caught db exception " << redact(e) << " while applying op: " << redact(op)
<< endl;
;
}
}
void ReplSource::applyOperation(OperationContext* txn, Database* db, const BSONObj& op) {
try {
Status status = applyOperation_inlock(txn, db, op);
if (!status.isOK()) {
uassert(15914,
"Failure applying initial sync operation",
status == ErrorCodes::UpdateOperationFailed);
// In initial sync, update operations can cause documents to be missed during
// collection cloning. As a result, it is possible that a document that we need to
// update is not present locally. In that case we fetch the document from the
// sync source.
SyncTail sync(nullptr, SyncTail::MultiSyncApplyFunc());
sync.setHostname(hostName);
sync.fetchAndInsertMissingDocument(txn, op);
}
} catch (UserException& e) {
log() << "sync: caught user assertion " << redact(e) << " while applying op: " << redact(op)
<< endl;
;
} catch (DBException& e) {
log() << "sync: caught db exception " << redact(e) << " while applying op: " << redact(op)
<< endl;
;
}
}
/* local.$oplog.main is of the form:
{ ts: ..., op: <optype>, ns: ..., o: <obj> , o2: <extraobj>, b: <boolflag> }
...
see logOp() comments.
@param alreadyLocked caller already put us in write lock if true
*/
void ReplSource::_sync_pullOpLog_applyOperation(OperationContext* txn,
BSONObj& op,
bool alreadyLocked) {
LOG(6) << "processing op: " << redact(op) << endl;
if (op.getStringField("op")[0] == 'n')
return;
char dbName[MaxDatabaseNameLen];
const char* ns = op.getStringField("ns");
nsToDatabase(ns, dbName);
if (*ns == '.') {
log() << "skipping bad op in oplog: " << redact(op) << endl;
return;
} else if (*ns == 0) {
/*if( op.getStringField("op")[0] != 'n' )*/ {
log() << "halting replication, bad op in oplog:\n " << redact(op) << endl;
replAllDead = "bad object in oplog";
throw SyncException();
}
// ns = "local.system.x";
// nsToDatabase(ns, clientName);
}
if (!only.empty() && only != dbName)
return;
// Push the CurOp stack for "txn" so each individual oplog entry application is separately
// reported.
CurOp individualOp(txn);
txn->setReplicatedWrites(false);
const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings();
if (replSettings.getPretouch() &&
!alreadyLocked /*doesn't make sense if in write lock already*/) {
if (replSettings.getPretouch() > 1) {
/* note: this is bad - should be put in ReplSource. but this is first test... */
static int countdown;
verify(countdown >= 0);
if (countdown > 0) {
countdown--; // was pretouched on a prev pass
} else {
const int m = 4;
if (tp.get() == 0) {
int nthr = min(8, replSettings.getPretouch());
nthr = max(nthr, 1);
tp.reset(new OldThreadPool(nthr));
}
vector<BSONObj> v;
oplogReader.peek(v, replSettings.getPretouch());
unsigned a = 0;
while (1) {
if (a >= v.size())
break;
unsigned b = a + m - 1; // v[a..b]
if (b >= v.size())
b = v.size() - 1;
tp->schedule(pretouchN, v, a, b);
DEV cout << "pretouch task: " << a << ".." << b << endl;
a += m;
}
// we do one too...
pretouchOperation(txn, op);
tp->join();
countdown = v.size();
}
} else {
pretouchOperation(txn, op);
}
}
unique_ptr<Lock::GlobalWrite> lk(alreadyLocked ? 0 : new Lock::GlobalWrite(txn->lockState()));
if (replAllDead) {
// hmmm why is this check here and not at top of this function? does it get set between top
// and here?
log() << "replAllDead, throwing SyncException: " << replAllDead << endl;
throw SyncException();
}
if (!handleDuplicateDbName(txn, op, ns, dbName)) {
return;
}
// special case apply for commands to avoid implicit database creation
if (*op.getStringField("op") == 'c') {
applyCommand(txn, op);
return;
}
// This code executes on the slaves only, so it doesn't need to be sharding-aware since
// mongos will not send requests there. That's why the last argument is false (do not do
// version checking).
OldClientContext ctx(txn, ns, false);
bool empty = !ctx.db()->getDatabaseCatalogEntry()->hasUserData();
bool incompleteClone = incompleteCloneDbs.count(dbName) != 0;
LOG(6) << "ns: " << ns << ", justCreated: " << ctx.justCreated() << ", empty: " << empty
<< ", incompleteClone: " << incompleteClone << endl;
if (ctx.justCreated() || empty || incompleteClone) {
// we must add to incomplete list now that setClient has been called
incompleteCloneDbs.insert(dbName);
if (nClonedThisPass) {
/* we only clone one database per pass, even if a lot need done. This helps us
avoid overflowing the master's transaction log by doing too much work before going
back to read more transactions. (Imagine a scenario of slave startup where we try to
clone 100 databases in one pass.)
*/
addDbNextPass.insert(dbName);
} else {
if (incompleteClone) {
log() << "An earlier initial clone of '" << dbName
<< "' did not complete, now resyncing." << endl;
}
save(txn);
OldClientContext ctx(txn, ns, false);
nClonedThisPass++;
resync(txn, ctx.db()->name());
addDbNextPass.erase(dbName);
incompleteCloneDbs.erase(dbName);
}
save(txn);
} else {
applyOperation(txn, ctx.db(), op);
addDbNextPass.erase(dbName);
}
}
void ReplSource::syncToTailOfRemoteLog() {
std::string _ns = ns();
BSONObjBuilder b;
if (!only.empty()) {
b.appendRegex("ns", std::string("^") + pcrecpp::RE::QuoteMeta(only));
}
BSONObj last = oplogReader.findOne(_ns.c_str(), Query(b.done()).sort(BSON("$natural" << -1)));
if (!last.isEmpty()) {
BSONElement ts = last.getField("ts");
massert(10386,
"non Date ts found: " + last.toString(),
ts.type() == Date || ts.type() == bsonTimestamp);
syncedTo = Timestamp(ts.date());
}
}
std::atomic<int> replApplyBatchSize(1); // NOLINT
class ReplApplyBatchSize
: public ExportedServerParameter<int, ServerParameterType::kStartupAndRuntime> {
public:
ReplApplyBatchSize()
: ExportedServerParameter<int, ServerParameterType::kStartupAndRuntime>(
ServerParameterSet::getGlobal(), "replApplyBatchSize", &replApplyBatchSize) {}
virtual Status validate(const int& potentialNewValue) {
if (potentialNewValue < 1 || potentialNewValue > 1024) {
return Status(ErrorCodes::BadValue, "replApplyBatchSize has to be >= 1 and <= 1024");
}
const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings();
if (replSettings.getSlaveDelaySecs() != Seconds(0) && potentialNewValue > 1) {
return Status(ErrorCodes::BadValue, "can't use a batch size > 1 with slavedelay");
}
if (!replSettings.isSlave()) {
return Status(ErrorCodes::BadValue,
"can't set replApplyBatchSize on a non-slave machine");
}
return Status::OK();
}
} replApplyBatchSizeServerParameter;
/* slave: pull some data from the master's oplog
note: not yet in db mutex at this point.
@return -1 error
0 ok, don't sleep
1 ok, sleep
*/
int ReplSource::_sync_pullOpLog(OperationContext* txn, int& nApplied) {
int okResultCode = restartSyncAfterSleep;
std::string ns = std::string("local.oplog.$") + sourceName();
LOG(2) << "sync_pullOpLog " << ns << " syncedTo:" << syncedTo.toStringLong() << '\n';
bool tailing = true;
oplogReader.tailCheck();
bool initial = syncedTo.isNull();
if (!oplogReader.haveCursor() || initial) {
if (initial) {
// Important to grab last oplog timestamp before listing databases.
syncToTailOfRemoteLog();
BSONObj info;
bool ok = oplogReader.conn()->runCommand("admin", BSON("listDatabases" << 1), info);
massert(10389, "Unable to get database list", ok);
BSONObjIterator i(info.getField("databases").embeddedObject());
while (i.moreWithEOO()) {
BSONElement e = i.next();
if (e.eoo())
break;
std::string name = e.embeddedObject().getField("name").valuestr();
if (!e.embeddedObject().getBoolField("empty")) {
if (name != "local") {
if (only.empty() || only == name) {
LOG(2) << "adding to 'addDbNextPass': " << name << endl;
addDbNextPass.insert(name);
}
}
}
}
// obviously global isn't ideal, but non-repl set is old so
// keeping it simple
ScopedTransaction transaction(txn, MODE_X);
Lock::GlobalWrite lk(txn->lockState());
save(txn);
}
BSONObjBuilder gte;
gte.append("$gte", syncedTo);
BSONObjBuilder query;
query.append("ts", gte.done());
if (!only.empty()) {
// note we may here skip a LOT of data table scanning, a lot of work for the master.
// maybe append "\\." here?
query.appendRegex("ns", std::string("^") + pcrecpp::RE::QuoteMeta(only));
}
BSONObj queryObj = query.done();
// e.g. queryObj = { ts: { $gte: syncedTo } }
oplogReader.tailingQuery(ns.c_str(), queryObj);
tailing = false;
} else {
LOG(2) << "tailing=true\n";
}
if (!oplogReader.haveCursor()) {
log() << "dbclient::query returns null (conn closed?)" << endl;
oplogReader.resetConnection();
return forceReconnect;
}
// show any deferred database creates from a previous pass
{
set<std::string>::iterator i = addDbNextPass.begin();
if (i != addDbNextPass.end()) {
BSONObjBuilder b;
b.append("ns", *i + '.');
b.append("op", "db");
BSONObj op = b.done();
_sync_pullOpLog_applyOperation(txn, op, false);
}
}
auto status = _updateIfDoneWithInitialSync();
if (!status.isOK()) {
switch (status.code()) {
case ErrorCodes::Interrupted: {
return restartSync; // don't sleep;
}
default: {
error() << redact(status);
return forceReconnect; // causes reconnect.
}
}
}
if (!oplogReader.more()) {
if (tailing) {
LOG(2) << "tailing & no new activity\n";
okResultCode = restartSync; // don't sleep
} else {
log() << ns << " oplog is empty" << endl;
}
{
ScopedTransaction transaction(txn, MODE_X);
Lock::GlobalWrite lk(txn->lockState());
save(txn);
}
return okResultCode;
}
Timestamp nextOpTime;
{
BSONObj op = oplogReader.nextSafe();
BSONElement ts = op.getField("ts");
if (ts.type() != Date && ts.type() != bsonTimestamp) {
std::string err = op.getStringField("$err");
if (!err.empty()) {
// 13051 is "tailable cursor requested on non capped collection"
if (op.getIntField("code") == 13051) {
log() << "trying to slave off of a non-master" << '\n';
massert(13344, "trying to slave off of a non-master", false);
} else {
error() << "$err reading remote oplog: " + redact(err) << '\n';
massert(10390, "got $err reading remote oplog", false);
}
} else {
error() << "bad object read from remote oplog: " << redact(op) << '\n';
massert(10391, "bad object read from remote oplog", false);
}
}
nextOpTime = Timestamp(ts.date());