-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathExtMsg.actor.cpp
More file actions
1454 lines (1216 loc) · 53.8 KB
/
ExtMsg.actor.cpp
File metadata and controls
1454 lines (1216 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ExtMsg.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* MongoDB is a registered trademark of MongoDB, Inc.
*/
#include "ExtMsg.actor.h"
#include "Ext.h"
#include "Cursor.h"
#include "ExtCmd.h"
#include "ExtOperator.h"
#include "ExtUtil.actor.h"
#include "MetadataManager.h"
#include "QLOperations.h"
#include "QLPlan.actor.h"
#include "QLPredicate.h"
#include "QLProjection.actor.h"
#include "QLTypes.h"
#include "bson.h"
#include "ordering.h"
#include "flow/Platform.h"
#include "flow/UnitTest.h"
#include "flow/actorcompiler.h" // This must be the last #include.
#include <string>
using namespace FDB;
REGISTER_MSG(ExtMsgQuery);
REGISTER_MSG(ExtMsgReply);
REGISTER_MSG(ExtMsgUpdate);
REGISTER_MSG(ExtMsgInsert);
REGISTER_MSG(ExtMsgGetMore);
REGISTER_MSG(ExtMsgDelete);
REGISTER_MSG(ExtMsgKillCursors);
ACTOR Future<Void> wrapError(Future<Void> actorThatCouldThrow) {
try {
wait(actorThatCouldThrow);
} catch (Error& e) {
TraceEvent(SevError, "BackgroundTask").error(e);
}
return Void();
}
// ns -> database.collection
Namespace getDBCollectionPair(const char* ns, std::pair<std::string, std::string> errMsg) {
const auto dotPtr = strchr(ns, '.');
if (dotPtr == nullptr) {
TraceEvent(SevWarn, "WireBadCollectionName").detail(errMsg.first, errMsg.second).suppressFor(1.0);
throw wire_protocol_mismatch();
}
return std::make_pair(std::string(ns, dotPtr - ns), std::string(dotPtr + 1));
}
/**
* query := { $bool_op : [ query* ], * (a predicate)
* path : literal_match, *
* path : value_query, * }
* value_query := { $value_op : param, * } (with the context of a path, a predicate)
*/
/**
* Converts a `value_query` in the above grammar, with the given path, to a predicate
* The predicate is returned by appending to `out_terms` zero or more predicates which,
* anded together, have the semantics of the given value_query.
*/
void valueQueryToPredicates(bson::BSONObj const& value_query,
std::string const& path,
std::vector<Reference<IPredicate>>& out_terms) {
std::string regex_options; // hacky special handling of { $option, $regex }
for (auto it = value_query.begin(); it.more();) {
auto sub = it.next();
if (std::string(sub.fieldName()) == "$options") {
regex_options = sub.String();
} else {
out_terms.push_back(ExtValueOperator::toPredicate(sub.fieldName(), path, sub));
}
}
// $options is applied to "$regex" so we don't have to create a Value Operator for it
// but we still need to find the predicate that is RegEx and apply the options
for (auto itCur = out_terms.rbegin(); !(itCur == out_terms.rend()); ++itCur) {
if (auto pAnyPredicate = dynamic_cast<AnyPredicate*>(itCur->getPtr())) {
if (auto pRegExPredicate = dynamic_cast<RegExPredicate*>(pAnyPredicate->pred.getPtr())) {
pRegExPredicate->setOptions(regex_options);
break;
}
}
}
}
/**
* Converts a `value_query` in the above grammar, with the given path, to a predicate.
*/
Reference<IPredicate> valueQueryToPredicate(bson::BSONObj const& query, std::string const& path) {
std::vector<Reference<IPredicate>> terms;
valueQueryToPredicates(query, path, terms);
return ref(new AndPredicate(terms));
}
/**
* Converts a mongo-like query document (query in the above grammar) into a corresponding
* QL predicate.
*/
Reference<IPredicate> queryToPredicate(bson::BSONObj const& query, bool toplevel) {
std::vector<Reference<IPredicate>> terms;
for (auto i = query.begin(); i.more();) {
auto el = i.next();
if (el.type() == bson::BSONType::RegEx) {
terms.push_back(re_predicate(el, el.fieldName()));
} else if (el.fieldName()[0] == '$') {
if (el.isABSONObj()) {
try {
terms.push_back(ExtBoolOperator::toPredicate(el.fieldName(), el.Obj()));
} catch (Error& e) {
if (e.code() == error_code_bad_dispatch)
throw fieldname_with_dollar();
else
throw;
}
} else {
throw fieldname_with_dollar();
}
} else if (el.isABSONObj() && !is_literal_match(el.Obj())) {
// If this is a top-level _id path then force use of elemMatch because _id can NOT be an array.
if (toplevel && strcmp(el.fieldName(), DocLayerConstants::ID_FIELD) == 0)
terms.push_back(ExtValueOperator::toPredicate("$elemMatch", el.fieldName(), el));
else
valueQueryToPredicates(el.Obj(), el.fieldName(), terms);
} else {
terms.push_back(eq_predicate(el, el.fieldName()));
}
}
return Reference<IPredicate>(new AndPredicate(terms));
}
Reference<Plan> planQuery(Reference<UnboundCollectionContext> cx, bson::BSONObj const& query) {
auto predicate = queryToPredicate(query, true);
auto simplifiedPredicate = predicate->simplify();
Reference<Plan> plan = Reference<Plan>(
FilterPlan::construct_filter_plan(cx, Reference<Plan>(new TableScanPlan(cx)), simplifiedPredicate));
if (verboseConsoleOutput) {
fprintf(stderr, "parsed predicate: %s\n", predicate->toString().c_str());
fprintf(stderr, " simplified to: %s\n\n", simplifiedPredicate->toString().c_str());
}
if (verboseLogging) {
TraceEvent("BD_GetMatchingDocs")
.detail("QueryPredicate", predicate->toString())
.detail("SimplifiedPredicate", predicate->toString())
.detail("Plan", plan->describe().toString());
}
if (slowQueryLogging && plan->hasScanOfType(PlanType::TableScan)) {
std::string collectionName = cx->collectionName();
if (!startsWith(collectionName.c_str(), "system."))
TraceEvent("SlowQuery")
.detail("Database", cx->databaseName())
.detail("Collection", collectionName)
.detail("Query", query.toString())
.detail("Plan", plan->describe().toString());
}
return plan;
}
Reference<Plan> planProjection(Reference<Plan> plan,
bson::BSONObj const& selector,
Optional<bson::BSONObj> const& ordering) {
return Reference<Plan>(new ProjectionPlan(parseProjection(selector), plan, ordering));
}
ExtMsgQuery::ExtMsgQuery(ExtMsgHeader* header, const uint8_t* body) : header(header) {
const uint8_t* ptr = body;
const uint8_t* eom = (uint8_t*)header + header->messageLength;
flags = *(int32_t*)ptr;
ptr += sizeof(int32_t);
const char* collName = (const char*)ptr;
ptr += strlen(collName) + 1;
numberToSkip = *(int32_t*)ptr;
ptr += sizeof(int32_t);
numberToReturn = *(int32_t*)ptr;
ptr += sizeof(int32_t);
query = bson::BSONObj((const char*)ptr);
ptr += query.objsize();
if (ptr != eom) {
returnFieldSelector = bson::BSONObj((const char*)ptr);
ptr += returnFieldSelector.objsize();
}
ns = getDBCollectionPair(collName, std::make_pair(DocLayerConstants::QUERY_FIELD, query.toString()));
if (ns.second == "$cmd") {
isCmd = true;
// Mark it empty for now, command would be responsible for setting collection name later.
ns.second = "";
} else {
isCmd = false;
}
/* We should have consumed all the bytes specified by header */
ASSERT(ptr == eom);
}
std::string ExtMsgQuery::toString() {
return format("QUERY: %s, collection=%s, flags=%d, numberToSkip=%d, numberToReturn=%d (%s)",
query.toString(false, true).c_str(), fullCollNameToString(ns).c_str(), flags, numberToSkip,
numberToReturn, header->toString().c_str());
}
ACTOR Future<Void> runCommand(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
PromiseStream<Reference<ExtMsgReply>> replyStream) {
state Reference<ExtMsgReply> errReply(new ExtMsgReply(query->header));
// For OP_QUERY commands, first elements field name is the command name. And the value contains
// the collection name if the command is at collection level.
auto firstElement = query->query.begin().next();
state std::string cmd = firstElement.fieldName();
std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
if (firstElement.isString()) {
query->ns.second = firstElement.String();
}
try {
Reference<ExtMsgReply> reply = wait(ExtCmd::call(cmd, nmc, query, errReply));
replyStream.send(reply);
} catch (Error& e) {
bson::BSONObjBuilder bob;
TraceEvent(SevWarn, "CmdFailed").error(e);
if (e.code() == error_code_bad_dispatch) {
bob.append("errmsg", format("no such cmd: %s", cmd.c_str()));
bob.append("$err", format("no such cmd: %s", cmd.c_str()));
} else {
bob.append("errmsg", format("command [%s] failed with err: %s", cmd.c_str(), e.what()));
bob.append("$err", format("command [%s] failed with err: %s", cmd.c_str(), e.what()));
}
bob.append("bad cmd", query->query.toString());
bob.append("ok", 0);
errReply->addDocument(bob.obj());
errReply->setResponseFlags(2);
replyStream.send(errReply);
}
replyStream.sendError(end_of_stream());
return Void();
}
// Set the shouldBeRead flag to false on Projections whose associated fields don't need to have their entire ranges
// read.
void Projection::filterUnneededReads(Reference<Projection> const& startingProjection, int maxReads) {
if (startingProjection->expandable() && startingProjection->fields.size() <= maxReads) {
startingProjection->shouldBeRead = false;
}
// SOMEDAY: If we enable the code path below, then we will need to account for the case that one of the filtered
// elements is an array (see SOMEDAY in projectDocument). That accounting will probably require an extra read
// latency, so it might be useful to enable the code path conditionally based on whether we believe the fields in
// question are not a part of an array.
/*std::priority_queue<Reference<Projection>, std::vector<Reference<Projection>>, Projection::SizeComparer>
projectionQueue; projectionQueue.push(startingProjection);
// Expand the projection with the smallest number of children into one projection per child until we've either
// hit our limit or there are none left to expand.
loop {
auto projection = projectionQueue.top();
if(projection->expandable() && projection->fields.size() + projectionQueue.size() - 1 <= maxReads) {
projection->shouldBeRead = false;
projectionQueue.pop();
for(auto child : projection->fields) {
projectionQueue.push(child.second);
}
}
else {
break;
}
}*/
}
ACTOR static Future<Reference<ExtMsgReply>> listCollections(Reference<ExtMsgQuery> query,
Reference<DocTransaction> tr,
Reference<DirectorySubspace> rootDirectory) {
state Reference<ExtMsgReply> reply = Reference<ExtMsgReply>(new ExtMsgReply(query->header, query->query));
state std::string databaseNameFromQuery = query->getDBName();
state Standalone<VectorRef<StringRef>> names;
try {
Standalone<VectorRef<StringRef>> _names = wait(rootDirectory->list(tr->tr, {StringRef(databaseNameFromQuery)}));
names = _names;
} catch (Error& e) {
return reply;
}
for (Standalone<StringRef> s : names) {
std::string str = databaseNameFromQuery + "." + s.toString();
reply->addDocument(BSON(DocLayerConstants::NAME_FIELD << str));
}
return reply;
}
ACTOR static Future<int32_t> addDocumentsFromCursor(Reference<Cursor> cursor,
Reference<ExtMsgReply> reply,
int32_t numberToReturn) {
state int32_t returned = 0;
state int32_t returnedSize = 0;
state bool stop = false;
state int32_t remaining = std::abs(numberToReturn);
while (!numberToReturn || remaining) {
try {
if ((returned <= DOCLAYER_KNOBS->MAX_RETURNABLE_DOCUMENTS ||
returnedSize <= DOCLAYER_KNOBS->DEFAULT_RETURNABLE_DATA_SIZE) &&
returnedSize <= DOCLAYER_KNOBS->MAX_RETURNABLE_DATA_SIZE) {
Reference<ScanReturnedContext> doc = waitNext(cursor->docs);
// Note that this call to get() is safe here but not in general, because we know
// that doc is wrapping a BsonContext, which means toDataValue() is synchronous.
bson::BSONObj obj = doc->toDataValue().get().getPackedObject().getOwned();
cursor->checkpoint->getDocumentFinishedLock()->release();
reply->addDocument(obj);
remaining--;
returned++;
cursor->returned++;
returnedSize += obj.objsize();
} else {
throw success();
}
} catch (Error& e) {
if (e.code() == error_code_end_of_stream) {
stop = true;
break;
}
if (e.code() == error_code_success) {
stop = false;
break;
}
TraceEvent(SevError, "BD_addDocumentsFromCursor").error(e);
throw;
}
}
// Reply with cursorID if requested or remove the cursor
if (numberToReturn >= 0 && !stop)
reply->replyHeader.cursorID = cursor->id;
else
Cursor::pluck(cursor);
return returned;
}
ACTOR static Future<Void> runQuery(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> msg,
PromiseStream<Reference<ExtMsgReply>> replyStream) {
state Reference<ExtMsgReply> reply;
state Reference<Cursor> cursor;
state Reference<DocTransaction> dtr = ec->getOperationTransaction();
bool sorted = (msg->query.hasField("orderby") || msg->query.hasField("$orderby"));
state Optional<bson::BSONObj> ordering = sorted ? msg->query.hasField("orderby")
? msg->query.getObjectField("orderby")
: msg->query.getObjectField("$orderby")
: Optional<bson::BSONObj>();
try {
// Return `listCollections()` if `ns` is like "name.system.namespaces"
if (msg->ns.second == DocLayerConstants::SYSTEM_NAMESPACES) {
Reference<ExtMsgReply> collections = wait(listCollections(msg, dtr, ec->docLayer->rootDirectory));
replyStream.send(collections);
throw end_of_stream();
}
state Reference<UnboundCollectionContext> cx = wait(ec->mm->getUnboundCollectionContext(dtr, msg->ns, true));
// The following is required by ambiguity in the wire protocol we are speaking
bson::BSONObj queryObject = msg->query.hasField(DocLayerConstants::QUERY_FIELD)
? msg->query.getObjectField(DocLayerConstants::QUERY_FIELD)
: msg->query.hasField(DocLayerConstants::QUERY_OPERATOR.c_str())
? msg->query.getObjectField(DocLayerConstants::QUERY_OPERATOR.c_str())
: msg->query;
// Plan needs to be state in case we have a sort plan, which in turn holds a reference to the actor that does
// the sorting
state Reference<Plan> plan = planQuery(cx, queryObject);
if (!ordering.present() && msg->numberToSkip)
plan = ref(new SkipPlan(msg->numberToSkip, plan));
plan = planProjection(plan, msg->returnFieldSelector, ordering);
plan = ec->wrapOperationPlan(plan, true, cx);
if (ordering.present()) {
plan = ref(new SortPlan(plan, ordering.get()));
if (msg->numberToSkip)
plan = ref(new SkipPlan(msg->numberToSkip, plan));
}
// return query plan explanation if `$explain` detected
if (msg->query.hasField("$explain")) {
reply = Reference<ExtMsgReply>(new ExtMsgReply(msg->header, msg->query));
reply->addDocument(BSON("explanation" << plan->describe()));
replyStream.send(reply);
throw end_of_stream();
}
Reference<PlanCheckpoint> outerCheckpoint(new PlanCheckpoint);
// Add a new cursor to the server's cursor collection
cursor = Cursor::add(
ec->cursors, Reference<Cursor>(new Cursor(plan->execute(outerCheckpoint.getPtr(), dtr), outerCheckpoint)));
state int replies = 0;
state bool exhaust = ((msg->flags & EXHAUST) != 0);
state int32_t lastRequestID = msg->header->requestID;
loop {
reply = Reference<ExtMsgReply>(new ExtMsgReply(msg->header, msg->query));
// Add requested documents to the reply from the cursor
int32_t toReturn = msg->numberToReturn;
// In Exhaust mode with numberToReturn == 0, the first reply will target 100 documents because
// this is the behavior observed in MongoDB.
if (exhaust && toReturn == 0 && replies == 0)
toReturn = 100;
// Mongo protocol states that 1 is to be treated as -1.
// See (http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol/#op-query)
if (toReturn == 1)
toReturn = -1;
int32_t returned = wait(addDocumentsFromCursor(cursor, reply, toReturn));
reply->addResponseFlag(8 /*0b1000*/);
// If no replies sent yet OR results were placed in reply, send them.
if (replies == 0 || returned > 0) {
// In Exhaust mode the server will generate RequestIDs for "get more" requests that never
// were sent by the client because this is the behavior observed in MongoDB.
if (exhaust) {
reply->replyHeader.responseTo = lastRequestID;
lastRequestID = ec->getNewRequestID();
reply->replyHeader.requestID = lastRequestID;
}
replyStream.send(reply);
}
// If EXHAUST not set OR it is but we got <=0 results, stop.
if (!exhaust || returned <= 0)
break;
++replies;
}
} catch (Error& e) {
if (e.code() != error_code_end_of_stream) {
reply = Reference<ExtMsgReply>(new ExtMsgReply(msg->header, msg->query));
reply->addDocument(BSON("$err" << e.what() << "code" << e.code() << "ok" << 1.0));
reply->setResponseFlags(2 /*0b0010*/);
replyStream.send(reply);
}
}
replyStream.sendError(end_of_stream());
return Void();
}
ACTOR static Future<Void> doRun(Reference<ExtMsgQuery> query, Reference<ExtConnection> ec) {
state PromiseStream<Reference<ExtMsgReply>> replyStream;
state Future<Void> x;
state uint64_t startTime = timer_int();
if (query->isCmd) {
// It's a command
x = runCommand(ec, query, replyStream);
} else {
// Run a query
x = runQuery(ec, query, replyStream);
}
state FutureStream<Reference<ExtMsgReply>> replies = replyStream.getFuture();
loop {
try {
Reference<ExtMsgReply> reply = waitNext(replies);
if (verboseLogging)
TraceEvent("BD_doRun").detail("Reply", reply->toString());
reply->write(ec);
} catch (Error& e) {
if (e.code() == error_code_end_of_stream)
break;
throw e;
}
}
uint64_t queryLatencyMicroSeconds = (timer_int() - startTime) / 1000;
DocumentLayer::metricReporter->captureTime(DocLayerConstants::MT_TIME_QUERY_LATENCY_US, queryLatencyMicroSeconds);
if (slowQueryLogging && queryLatencyMicroSeconds >= DOCLAYER_KNOBS->SLOW_QUERY_THRESHOLD_MICRO_SECONDS) {
TraceEvent(SevWarn, "SlowQuery")
.detail("ThresholdMicroSeconds", DOCLAYER_KNOBS->SLOW_QUERY_THRESHOLD_MICRO_SECONDS)
.detail("DurationMicroSeconds", queryLatencyMicroSeconds)
.detail("Query", query->toString());
}
return Void();
}
std::string ExtMsgQuery::getDBName() {
return ns.first;
}
Future<Void> ExtMsgQuery::run(Reference<ExtConnection> nmc) {
return doRun(Reference<ExtMsgQuery>::addRef(this), nmc);
}
ExtMsgReply::ExtMsgReply(ExtMsgHeader* header, const uint8_t* body) : header(nullptr) {
memcpy(&replyHeader, header, sizeof(ExtReplyHeader));
const uint8_t* ptr = (const uint8_t*)header + sizeof(ExtReplyHeader);
const uint8_t* eom = (const uint8_t*)header + header->messageLength;
while (ptr < eom) {
bson::BSONObj doc((const char*)ptr);
ptr += doc.objsize();
documents.push_back(doc);
}
ASSERT(ptr == eom);
}
ExtMsgReply::ExtMsgReply(ExtMsgHeader* header, bson::BSONObj const& query) : header(header), query(query) {
replyHeader.responseTo = header->requestID;
replyHeader.opCode = 1; // OP_REPLY
}
ExtMsgReply::ExtMsgReply(ExtMsgHeader* header) : header(header) {
replyHeader.responseTo = header->requestID;
replyHeader.opCode = 1; // OP_REPLY
}
std::string ExtMsgReply::toString() {
std::string buf = "REPLY: documents=[ ";
for (const auto& d : documents) {
buf += d.toString();
buf += " ";
}
buf += format("], responseFlags=%d, cursorID=%d, startingFrom=%d (%s)", replyHeader.responseFlags,
replyHeader.cursorID, replyHeader.startingFrom, replyHeader.toString().c_str());
return buf;
}
void ExtMsgReply::write(Reference<ExtConnection> nmc) {
replyHeader.messageLength = sizeof(replyHeader);
for (const auto& document : documents) {
replyHeader.messageLength += document.objsize();
}
if (verboseLogging)
TraceEvent("BD_msgReply").detail("Message", toString()).detail("connId", nmc->connectionId);
if (verboseConsoleOutput)
fprintf(stderr, "S -> C: %s\n\n", toString().c_str());
nmc->bc->write(StringRef((uint8_t*)&replyHeader, sizeof(replyHeader)));
for (const auto& doc : documents) {
nmc->bc->write(StringRef((const uint8_t*)doc.objdata(), doc.objsize()));
}
}
ExtMsgInsert::ExtMsgInsert(ExtMsgHeader* header, const uint8_t* body) : header(header) {
const uint8_t* ptr = body;
const uint8_t* eom = (const uint8_t*)header + header->messageLength;
flags = *(int32_t*)ptr;
ptr += sizeof(int32_t);
const char* collName = (const char*)ptr;
ptr += strlen(collName) + 1;
ns = getDBCollectionPair(collName, std::make_pair("msgType", "OP_INSERT"));
while (ptr < eom) {
bson::BSONObj doc = bson::BSONObj((const char*)ptr);
ptr += doc.objsize();
documents.push_back(doc);
}
ASSERT(ptr == eom);
}
std::string ExtMsgInsert::toString() {
std::string buf = "INSERT: documents=[ ";
for (const auto& d : documents) {
buf += d.toString();
buf += " ";
}
buf +=
format("], collection=%s, flags=%d (%s)", fullCollNameToString(ns).c_str(), flags, header->toString().c_str());
return buf;
}
ACTOR Future<Reference<IReadWriteContext>> insertDocument(Reference<CollectionContext> cx,
bson::BSONObj d,
Optional<IdInfo> encodedIds) {
state Standalone<StringRef> encodedId;
state Standalone<StringRef> valueEncodedId;
state Optional<bson::BSONObj> idObj;
state Reference<QueryContext> dcx;
if (!encodedIds.present()) {
encodedId = DataValue(bson::OID::gen()).encode_key_part();
valueEncodedId = encodedId;
idObj = Optional<bson::BSONObj>();
dcx = cx->cx->getSubContext(encodedId);
} else {
encodedId = encodedIds.get().keyEncoded;
valueEncodedId = encodedIds.get().valueEncoded;
idObj = encodedIds.get().objValue;
dcx = cx->cx->getSubContext(encodedId);
Optional<DataValue> existing =
wait(dcx->get(DataValue(DocLayerConstants::ID_FIELD, DVTypeCode::STRING).encode_key_part()));
if (existing.present())
throw duplicated_key_field();
}
// FIXME: abstraction violation out of laziness
Key prefix = StringRef(dcx->getPrefix().toString());
dcx->getTransaction()->tr->addWriteConflictRange(KeyRangeRef(prefix, strinc(prefix)));
dcx->set(LiteralStringRef(""), DataValue::subObject().encode_value());
int nrFDBKeys = 0;
for (auto i = d.begin(); i.more();) {
auto e = i.next();
nrFDBKeys += insertElementRecursive(e, dcx);
}
DocumentLayer::metricReporter->captureHistogram(DocLayerConstants::MT_HIST_KEYS_PER_DOCUMENT, nrFDBKeys);
DocumentLayer::metricReporter->captureHistogram(DocLayerConstants::MT_HIST_DOCUMENT_SZ, d.objsize());
if (idObj.present())
insertElementRecursive(DocLayerConstants::ID_FIELD, idObj.get(), dcx);
dcx->set(DataValue(DocLayerConstants::ID_FIELD, DVTypeCode::STRING).encode_key_part(), valueEncodedId);
return dcx;
}
struct ExtInsert : ConcreteInsertOp<ExtInsert> {
bson::BSONObj obj;
Optional<IdInfo> encodedIds;
ExtInsert(bson::BSONObj obj, Optional<IdInfo> encodedIds) : obj(obj), encodedIds(encodedIds) {}
std::string describe() override { return "Insert(" + obj.toString() + ")"; }
Future<Reference<IReadWriteContext>> insert(Reference<CollectionContext> cx) override {
return insertDocument(cx, obj, encodedIds);
}
};
struct ExtIndexInsert : ConcreteInsertOp<ExtIndexInsert> {
bson::BSONObj indexObj;
std::string ns;
UID build_id;
ExtIndexInsert(bson::BSONObj indexObj, UID build_id, std::string ns)
: indexObj(indexObj), build_id(build_id), ns(ns) {}
std::string describe() override { return "IndexInsert(" + indexObj.toString() + ")"; }
ACTOR static Future<Reference<IReadWriteContext>> indexInsertActor(ExtIndexInsert* self,
Reference<CollectionContext> cx) {
state Standalone<StringRef> encodedId;
state Standalone<StringRef> valueEncodedId;
state Optional<bson::BSONObj> idObj;
state Reference<QueryContext> dcx;
Optional<IdInfo> encodedIds = extractEncodedIds(self->indexObj);
if (!encodedIds.present()) {
encodedId = DataValue(bson::OID::gen()).encode_key_part();
valueEncodedId = encodedId;
idObj = Optional<bson::BSONObj>();
dcx = cx->cx->getSubContext(encodedId);
} else {
encodedId = encodedIds.get().keyEncoded;
valueEncodedId = encodedIds.get().valueEncoded;
idObj = encodedIds.get().objValue;
dcx = cx->cx->getSubContext(encodedId);
Optional<DataValue> existing =
wait(dcx->get(DataValue(DocLayerConstants::ID_FIELD, DVTypeCode::STRING).encode_key_part()));
if (existing.present())
throw duplicated_key_field();
}
// FIXME: abstraction violation out of laziness
Key prefix = StringRef(dcx->getPrefix().toString());
dcx->getTransaction()->tr->addWriteConflictRange(KeyRangeRef(prefix, strinc(prefix)));
dcx->set(LiteralStringRef(""), DataValue::subObject().encode_value());
dcx->set(DataValue(DocLayerConstants::NS_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(self->ns).encode_value());
dcx->set(
DataValue(DocLayerConstants::NAME_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(self->indexObj.getStringField(DocLayerConstants::NAME_FIELD), DVTypeCode::STRING).encode_value());
dcx->set(DataValue(DocLayerConstants::KEY_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(self->indexObj.getObjectField(DocLayerConstants::KEY_FIELD)).encode_value());
dcx->set(DataValue(DocLayerConstants::STATUS_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(DocLayerConstants::INDEX_STATUS_BUILDING, DVTypeCode::STRING).encode_value());
dcx->set(DataValue(DocLayerConstants::METADATA_VERSION_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(1).encode_value());
dcx->set(DataValue(DocLayerConstants::BUILD_ID_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(self->build_id.toString()).encode_value());
dcx->set(DataValue(DocLayerConstants::UNIQUE_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(self->indexObj.getBoolField(DocLayerConstants::UNIQUE_FIELD)).encode_value());
dcx->set(DataValue(DocLayerConstants::BACKGROUND_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(self->indexObj.getBoolField(DocLayerConstants::BACKGROUND_FIELD)).encode_value());
if (idObj.present())
insertElementRecursive(DocLayerConstants::ID_FIELD, idObj.get(), dcx);
dcx->set(DataValue(DocLayerConstants::ID_FIELD, DVTypeCode::STRING).encode_key_part(), valueEncodedId);
return dcx;
}
Future<Reference<IReadWriteContext>> insert(Reference<CollectionContext> cx) { return indexInsertActor(this, cx); }
};
ACTOR Future<WriteCmdResult> attemptIndexInsertion(bson::BSONObj indexObj,
Reference<ExtConnection> ec,
Reference<DocTransaction> tr,
Namespace ns) {
if (!indexObj.hasField(DocLayerConstants::NAME_FIELD))
throw no_index_name();
// It is legal to have index key to be simple string for simple value indexes.
if (indexObj.getField(DocLayerConstants::KEY_FIELD).isString()) {
bson::BSONObjBuilder builder;
for (auto it = indexObj.begin(); it.more();) {
auto el = it.next();
if (std::string(el.fieldName()) == DocLayerConstants::KEY_FIELD) {
builder.append(DocLayerConstants::KEY_FIELD, BSON(el.String() << 1));
} else {
builder.append(el);
}
}
indexObj = builder.obj();
}
if (!indexObj.getField(DocLayerConstants::KEY_FIELD).isABSONObj()) {
TraceEvent(SevWarn, "BadIndexSpec").detail("err_msg", "Bad key format");
throw bad_index_specification();
}
if (indexObj.getObjectField(DocLayerConstants::KEY_FIELD).nFields() == 1) {
auto keyEl = indexObj.getObjectField(DocLayerConstants::KEY_FIELD).firstElement();
if (!keyEl.isNumber() || !(keyEl.Number() == 1.0 || keyEl.Number() == -1.0)) {
(keyEl.isString() && keyEl.str() == "text") ? throw unsupported_index_type()
: throw bad_index_specification();
}
if (!strcmp(keyEl.fieldName(), DocLayerConstants::ID_FIELD)) {
return WriteCmdResult();
}
} else {
bool first = true;
bool ascending;
for (bson::BSONObjIterator i = indexObj.getObjectField(DocLayerConstants::KEY_FIELD).begin(); i.more();) {
auto el = i.next();
if (!el.isNumber()) {
(el.isString() && el.str() == "text") ? throw unsupported_index_type()
: throw bad_index_specification();
}
if (!strcmp(el.fieldName(), DocLayerConstants::ID_FIELD)) {
throw compound_id_index();
}
double direction = el.Number();
if (std::abs(direction) != 1.0) {
throw bad_index_specification();
}
if (first) {
ascending = (direction == 1.0);
first = false;
} else if (ascending != (direction == 1.0)) {
throw no_mixed_compound_index();
}
}
}
state bool background = indexObj.getBoolField(DocLayerConstants::BACKGROUND_FIELD);
if (indexObj.getBoolField(DocLayerConstants::UNIQUE_FIELD) && background) {
throw unique_index_background_construction();
}
// Let's add this index
state UID build_id = g_random->randomUniqueID();
Reference<IInsertOp> indexOp(new ExtIndexInsert(indexObj, build_id, ns.first + "." + ns.second));
Reference<Plan> plan = ec->isolatedWrapOperationPlan(ref(new IndexInsertPlan(indexOp, indexObj, ns, ec->mm)));
state std::pair<int64_t, Reference<ScanReturnedContext>> pair =
wait(executeUntilCompletionAndReturnLastTransactionally(plan, tr));
if (pair.first) {
Standalone<StringRef> id =
wait(pair.second->getKeyEncodedId()); // FIXME: Is this actually transactional? Safe? Maybe project it?
if (background)
ec->docLayer->backgroundTasks.add(wrapError(MetadataManager::buildIndex(indexObj, ns, id, ec, build_id)));
else
wait(MetadataManager::buildIndex(indexObj, ns, id, ec, build_id));
return WriteCmdResult(1);
} else {
return WriteCmdResult();
}
}
ACTOR Future<WriteCmdResult> doInsertCmd(Namespace ns,
std::list<bson::BSONObj>* documents,
Reference<ExtConnection> ec) {
state Reference<DocTransaction> tr = ec->getOperationTransaction();
state uint64_t startTime = timer_int();
if (ns.second == DocLayerConstants::SYSTEM_INDEXES) {
if (verboseLogging)
TraceEvent("BD_doInsertRun").detail("AttemptIndexInsertion", "");
if (documents->size() != 1) {
throw multiple_index_construction();
}
bson::BSONObj firstDoc = documents->front();
const char* collnsStr = firstDoc.getField(DocLayerConstants::NS_FIELD).String().c_str();
const auto collns = getDBCollectionPair(collnsStr, std::make_pair("msg", "Bad coll name in index insert"));
WriteCmdResult result = wait(attemptIndexInsertion(firstDoc.getOwned(), ec, tr, collns));
DocumentLayer::metricReporter->captureTime(DocLayerConstants::MT_TIME_INSERT_LATENCY_US,
(timer_int() - startTime) / 1000);
return result;
}
std::vector<Reference<IInsertOp>> inserts;
std::set<Standalone<StringRef>> ids;
int insertSize = 0;
for (const auto& d : *documents) {
const bson::BSONObj& obj = d;
Optional<IdInfo> encodedIds = extractEncodedIds(obj);
if (encodedIds.present()) {
if (!ids.insert(encodedIds.get().keyEncoded).second) {
throw duplicated_key_field();
}
}
inserts.push_back(Reference<IInsertOp>(new ExtInsert(obj, encodedIds)));
insertSize += obj.objsize();
}
DocumentLayer::metricReporter->captureHistogram(DocLayerConstants::MT_HIST_INSERT_SZ, insertSize);
DocumentLayer::metricReporter->captureHistogram(DocLayerConstants::MT_HIST_DOCS_PER_INSERT, documents->size());
Reference<Plan> plan = ec->isolatedWrapOperationPlan(ref(new InsertPlan(inserts, ec->mm, ns)));
int64_t i = wait(executeUntilCompletionTransactionally(plan, tr));
DocumentLayer::metricReporter->captureTime(DocLayerConstants::MT_TIME_INSERT_LATENCY_US,
(timer_int() - startTime) / 1000);
return WriteCmdResult(i);
}
ACTOR static Future<WriteResult> doInsertMsg(Future<Void> readyToWrite,
Reference<ExtMsgInsert> insert,
Reference<ExtConnection> ec) {
wait(readyToWrite);
WriteCmdResult cmdResult = wait(doInsertCmd(insert->ns, &insert->documents, ec));
return WriteResult(cmdResult, WriteType::INSERT);
}
Future<Void> ExtMsgInsert::run(Reference<ExtConnection> ec) {
return ec->afterWrite(doInsertMsg(ec->beforeWrite(documents.size()), Reference<ExtMsgInsert>::addRef(this), ec),
documents.size());
}
ExtMsgUpdate::ExtMsgUpdate(ExtMsgHeader* header, const uint8_t* body) : header(header) {
const uint8_t* ptr = body;
const uint8_t* eom = (const uint8_t*)header + header->messageLength;
ptr += sizeof(int32_t); // mongo OP_UPDATE begins with int32 ZERO, reserved for future use
const char* collName = (const char*)ptr;
ptr += strlen(collName) + 1;
ns = getDBCollectionPair(collName, std::make_pair("msgType", "OP_UPDATE"));
flags = *(int32_t*)ptr;
ptr += sizeof(int32_t);
upsert = ((flags & Flags::UPSERT) == Flags::UPSERT);
multi = ((flags & Flags::MULTI) == Flags::MULTI);
selector = bson::BSONObj((const char*)ptr);
ptr += selector.objsize();
update = bson::BSONObj((const char*)ptr);
ptr += update.objsize();
ASSERT(ptr == eom);
}
std::string ExtMsgUpdate::toString() {
return format("UPDATE: selector=%s, update=%s, collection=%s, flags=%d (%s)", selector.toString().c_str(),
update.toString().c_str(), fullCollNameToString(ns).c_str(), flags, header->toString().c_str());
}
void staticValidateModifiedFields(std::string fieldName,
std::set<std::string>* affectedFields,
std::set<std::string>* prefixesOfAffectedFields) {
if (affectedFields->find(fieldName) != affectedFields->end())
throw field_name_duplication_with_mods();
if (prefixesOfAffectedFields->find(fieldName) != prefixesOfAffectedFields->end())
throw conflicting_mods_in_update();
affectedFields->insert(fieldName);
auto upOneFn = upOneLevel(fieldName);
if (!upOneFn.empty()) {
while (!upOneFn.empty()) {
if (affectedFields->find(upOneFn) != affectedFields->end())
throw conflicting_mods_in_update();
prefixesOfAffectedFields->insert(upOneFn);
upOneFn = upOneLevel(upOneFn);
}
}
}
bool shouldCreateRoot(std::string operatorName) {
return operatorName == DocLayerConstants::SET || operatorName == DocLayerConstants::INC ||
operatorName == DocLayerConstants::MUL || operatorName == DocLayerConstants::CURRENT_DATE ||
operatorName == DocLayerConstants::MAX || operatorName == DocLayerConstants::MIN ||
operatorName == DocLayerConstants::PUSH || operatorName == DocLayerConstants::ADD_TO_SET;
}
// #156: staticValidateUpdateObject function is moved to updateDocument constructor
/* staticValidateUpdateObject function part has more similar and related functionalities
* present in updateDocument constructor. Instead of using StaticValidateUpdate function
* part, that part is moved to updateDocument constructor. So there is no need to call staticValidateUpdate
* function separately, if operatorUpdate is enabled it will execute updateDocument which now has
* staticValidateUpdate functionalities also.
*/
ACTOR Future<Void> updateDocument(Reference<IReadWriteContext> cx,
Reference<UnboundCollectionContext> ucx,
bson::BSONObj update,
bool upsert,
bool multi = false) {
state std::set<std::string> affectedFields;
state std::set<std::string> prefixesOfAffectedFields;
state std::vector<Future<Void>> futures;
state Standalone<StringRef> encodedId = wait(cx->getKeyEncodedId());
for (auto i = update.begin(); i.more();) {
auto el = i.next();
std::string operatorName = el.fieldName();
if (!el.isABSONObj() || el.Obj().nFields() == 0) {
throw update_operator_empty_parameter();
}
if (upsert && operatorName == DocLayerConstants::SET_ON_INSERT)
operatorName = DocLayerConstants::SET;