/
ExtCmd.actor.cpp
1416 lines (1255 loc) · 57.1 KB
/
ExtCmd.actor.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
/*
* ExtCmd.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 "bson.h"
#include "ordering.h"
#include "ExtCmd.h"
#include "ExtMsg.actor.h"
#include "ExtUtil.actor.h"
#include "QLPlan.actor.h"
#include "QLProjection.actor.h"
#ifndef WIN32
#include "gitVersion.h"
#endif
#include "flow/actorcompiler.h" // This must be the last #include.
using namespace FDB;
extern const char* getGitVersion();
extern const char* getFlowGitVersion();
ACTOR static Future<std::pair<int, int>> dropIndexMatching(Reference<DocTransaction> tr,
Namespace ns,
std::string field,
DataValue value,
Reference<MetadataManager> mm) {
state Reference<UnboundCollectionContext> indexesCollection = wait(mm->indexesCollection(tr, ns.first));
state Reference<UnboundCollectionContext> targetedCollection = wait(mm->getUnboundCollectionContext(tr, ns));
state Reference<Plan> indexesPlan = getIndexesForCollectionPlan(indexesCollection, ns);
state std::vector<bson::BSONObj> indexes = wait(getIndexesTransactionally(indexesPlan, tr));
state int count = 0;
state bool any = false;
state bson::BSONObj matchingIndexObj;
state Reference<QueryContext> matchingIndex;
state std::string matchingName;
// This next ugly block of code needs to stick around for now because the unconventional way in which we are
// representing the 'key' field in an index document (which was done because this is one place we can't get away
// with ignoring the ordering of documents) breaks the conventional query pipeline. So we need this specialized
// handling.
for (const auto& indexObj : indexes) {
count++;
if (value.getBSONType() == bson::BSONType::String) {
if (value.getString() == indexObj.getStringField(field.c_str())) {
any = true;
matchingIndexObj = indexObj;
matchingIndex = indexesCollection->bindCollectionContext(tr)->cx->getSubContext(
DataValue(indexObj.getField(DocLayerConstants::ID_FIELD)).encode_key_part());
matchingName = std::string(indexObj.getStringField(DocLayerConstants::NAME_FIELD));
}
} else if (value.getBSONType() == bson::BSONType::Object) {
if (value.getPackedObject().woCompare(indexObj.getObjectField(field.c_str())) == 0) {
any = true;
matchingIndexObj = indexObj;
matchingIndex = indexesCollection->bindCollectionContext(tr)->cx->getSubContext(
DataValue(indexObj.getField(DocLayerConstants::ID_FIELD)).encode_key_part());
matchingName = std::string(indexObj.getStringField(DocLayerConstants::NAME_FIELD));
}
}
}
if (!any)
return std::make_pair(count, 0);
matchingIndex->clearDescendants();
matchingIndex->clearRoot();
TraceEvent(SevInfo, "BumpMetadataVersion")
.detail("reason", "dropIndex")
.detail("ns", fullCollNameToString(ns))
.detail("index", matchingIndexObj.toString());
wait(matchingIndex->commitChanges());
Key indexKey = targetedCollection->getIndexesSubspace().withSuffix(encodeMaybeDotted(matchingName));
tr->tr->clear(FDB::KeyRangeRef(indexKey, strinc(indexKey)));
targetedCollection->bindCollectionContext(tr)->bumpMetadataVersion();
return std::make_pair(count, 1);
}
ACTOR static Future<Void> Internal_doDropDatabase(Reference<DocTransaction> tr,
Reference<ExtMsgQuery> query,
Reference<DirectorySubspace> rootDirectory) {
wait(success(rootDirectory->removeIfExists(tr->tr, {StringRef(query->ns.first)})));
return Void();
}
ACTOR static Future<Reference<ExtMsgReply>> doDropDatabase(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
try {
// No need to wait on lastWrite. The ranges we write ensure that this will conflict with anything it needs to
// conflict with.
wait(runRYWTransaction(ec->docLayer->database,
[=](Reference<DocTransaction> tr) {
return Internal_doDropDatabase(tr, query, ec->docLayer->rootDirectory);
},
ec->options.retryLimit, ec->options.timeoutMillies));
reply->addDocument(BSON("ok" << 1.0));
return reply;
} catch (Error& e) {
// clang-format off
reply->addDocument(BSON("ok" << 1.0 <<
"err" << e.what() <<
"code" << e.code()));
// clang-format on
return reply;
}
}
struct DropDatabaseCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doDropDatabase(ec, query, reply);
}
};
REGISTER_CMD(DropDatabaseCmd, "dropdatabase");
struct WhatsmyuriCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
// clang-format off
reply->addDocument(BSON("you" << nmc->bc->getPeerAddress().toString() <<
"ok" << 1.0));
// clang-format on
return Future<Reference<ExtMsgReply>>(reply);
}
};
REGISTER_CMD(WhatsmyuriCmd, "whatsmyuri");
struct GetCmdLineOptsCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
// clang-format off
reply->addDocument(BSON("argv" << BSON_ARRAY("fdbdoc") <<
"ok" << 1.0));
// clang-format on
return Future<Reference<ExtMsgReply>>(reply);
}
};
REGISTER_CMD(GetCmdLineOptsCmd, "getcmdlineopts");
bson::NullLabeler BSONNULL;
struct GetlasterrorCmd {
static const char* name;
ACTOR static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
state bson::BSONObjBuilder bob;
Future<WriteResult> lastWrite = ec->lastWrite;
bob.appendNumber("connectionId", (long long)ec->connectionId);
try {
WriteResult res = wait(lastWrite);
bob.appendNumber("n", (long long)res.n); //< FIXME: ???
bob << "err" << BSONNULL << "ok" << 1.0;
if (!res.upsertedOIDList.empty()) {
bob.appendElements(DataValue::decode_key_part(res.upsertedOIDList[0]).wrap("upserted"));
}
if (res.type == WriteType::UPDATE) {
bob << "updatedExisting" << (res.nModified > 0 && res.upsertedOIDList.empty());
}
} catch (Error& e) {
bob.append("err", e.what());
bob.append("code", e.code());
bob.appendNumber("n", (long long)0);
bob.append("ok", 1.0);
}
reply->addDocument(bob.obj());
reply->setResponseFlags(8);
ec->lastWrite = WriteResult();
return reply;
}
};
REGISTER_CMD(GetlasterrorCmd, "getlasterror");
struct FakeErrorCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
throw operation_failed();
}
};
REGISTER_CMD(FakeErrorCmd, "fakeerror");
struct GetLogCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
bson::BSONObjBuilder bob;
if (query->ns.first != "admin") {
// clang-format off
reply->addDocument((bob << "ok" << 0.0 <<
"errmsg" << "access denied; use admin db" <<
"$err" << "access denied; use admin db").obj());
// clang-format on
return reply;
}
std::string log = query->query["getLog"].String();
if (log == "*") {
reply->addDocument(BSON("names" << BSON_ARRAY("global"
<< "startupWarnings")
<< "ok" << 1));
} else if (log == "startupWarnings") {
reply->addDocument(BSON("totalLinesWritten" << 3 << "log"
<< BSON_ARRAY(""
<< "WARNING: This is not really mongodb."
<< "")
<< "ok" << 1));
} else if (log == "global") {
reply->addDocument(BSON("totalLinesWritten" << 1 << "log" << BSON_ARRAY("foo") << "ok" << 1.0));
}
return reply;
}
};
REGISTER_CMD(GetLogCmd, "getlog");
struct ServerStatusCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
// bson::BSONObjBuilder bob;
// bob.append( "opcounters" << BSON( "query" << queries ) );
// bob.append( "ok", 1 );
// reply->addDocument( bob.obj() );
// reply->addDocument( BSON( "opcounters" << BSON( "query" << queries ) << "ok" << 1 ) );
reply->addDocument(BSON("ok" << 1.0));
return reply;
}
};
REGISTER_CMD(ServerStatusCmd, "serverstatus");
struct ReplSetGetStatusCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
bson::BSONObjBuilder bob;
// FIXME: what do we really want to report here?
bob.append("ok", 0.0);
bob.append("errmsg", "not really talking to mongodb");
bob.append("$err", "not really talking to mongodb");
reply->addDocument(bob.obj());
return reply;
}
};
REGISTER_CMD(ReplSetGetStatusCmd, "replsetgetstatus");
struct PingCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
reply->addDocument(BSON("ok" << 1.0));
return reply;
}
};
REGISTER_CMD(PingCmd, "ping");
struct IsMasterCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
reply->addDocument(BSON(
// clang-format off
"ismaster" << true <<
"maxBsonObjectSize" << 16777216 <<
"maxMessageSizeBytes" << 48000000 <<
// FIXME: BM: Just like other fields, going with defaults. We should revisit these numbers.
"maxWriteBatchSize" << 1000 <<
"localTime" << bson::Date_t(timer() * 1000) <<
"minWireVersion" << EXT_MIN_WIRE_VERSION <<
"maxWireVersion" << EXT_MAX_WIRE_VERSION <<
"ok" << 1.0
// clang-format on
));
return reply;
}
};
REGISTER_CMD(IsMasterCmd, "ismaster");
struct GetNonceCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
reply->addDocument(BSON("nonce"
<< "0000000000000000"
<< "ok" << 1.0));
return reply;
}
};
REGISTER_CMD(GetNonceCmd, "getnonce");
ACTOR static Future<int> internal_doDropIndexesActor(Reference<DocTransaction> tr,
Namespace ns,
Reference<MetadataManager> mm) {
state Reference<UnboundCollectionContext> indexesCollection = wait(mm->indexesCollection(tr, ns.first));
state Reference<Plan> plan = getIndexesForCollectionPlan(indexesCollection, ns);
state Reference<UnboundCollectionContext> unbound = wait(mm->getUnboundCollectionContext(tr, ns));
plan = flushChanges(deletePlan(plan, indexesCollection, std::numeric_limits<int64_t>::max()));
state int64_t count = wait(executeUntilCompletionTransactionally(plan, tr));
Key indexes = unbound->getIndexesSubspace();
tr->tr->clear(FDB::KeyRangeRef(indexes, strinc(indexes)));
unbound->bindCollectionContext(tr)->bumpMetadataVersion();
TraceEvent(SevInfo, "BumpMetadataVersion")
.detail("reason", "dropAllIndexes")
.detail("ns", fullCollNameToString(ns));
return count;
}
ACTOR static Future<Void> Internal_doDropCollection(Reference<DocTransaction> tr,
Reference<ExtMsgQuery> query,
Reference<MetadataManager> mm) {
state Reference<UnboundCollectionContext> unbound = wait(mm->getUnboundCollectionContext(tr, query->ns));
wait(success(internal_doDropIndexesActor(tr, query->ns, mm)));
wait(unbound->collectionDirectory->remove(tr->tr));
return Void();
}
ACTOR static Future<Reference<ExtMsgReply>> doDropCollection(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
try {
// No need to wait on lastWrite in either case. The ranges we write ensure that this will conflict with
// anything it needs to conflict with.
wait(runRYWTransaction(
ec->docLayer->database,
[=](Reference<DocTransaction> tr) { return Internal_doDropCollection(tr, query, ec->mm); },
ec->options.retryLimit, ec->options.timeoutMillies));
reply->addDocument(BSON("ok" << 1.0));
return reply;
} catch (Error& e) {
reply->addDocument(BSON("ok" << 1.0 << "err" << e.what() << "code" << e.code()));
return reply;
}
}
struct DropCollectionCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doDropCollection(ec, query, reply);
}
};
REGISTER_CMD(DropCollectionCmd, "drop");
ACTOR static Future<Void> internal_doRenameCollectionIndexesActor(Reference<DocTransaction> tr,
Namespace ns,
Reference<MetadataManager> mm,
std::string destinationCollection) {
state Reference<UnboundCollectionContext> indexesCollection = wait(mm->indexesCollection(tr, ns.first));
state Reference<Plan> indexesPlan = wait(getIndexesForCollectionPlan(ns, tr, mm));
state std::vector<bson::BSONObj> indexes = wait(getIndexesTransactionally(indexesPlan, tr));
state Reference<QueryContext> matchingIndex;
for (const auto& indexObj : indexes) {
matchingIndex = indexesCollection->bindCollectionContext(tr)->cx->getSubContext(
DataValue(indexObj.getField(DocLayerConstants::ID_FIELD)).encode_key_part());
matchingIndex->set(DataValue(DocLayerConstants::NS_FIELD, DVTypeCode::STRING).encode_key_part(),
DataValue(ns.first + "." + destinationCollection, DVTypeCode::STRING).encode_value());
wait(matchingIndex->commitChanges());
}
state Reference<UnboundCollectionContext> unbound = wait(mm->getUnboundCollectionContext(tr, ns));
unbound->bindCollectionContext(tr)->bumpMetadataVersion();
TraceEvent(SevInfo, "BumpMetadataVersion")
.detail("reason", "renameCollection")
.detail("ns", fullCollNameToString(ns));
return Void();
}
ACTOR static Future<Void> Internal_doRenameCollection(Reference<DocTransaction> tr,
Reference<ExtMsgQuery> query,
Reference<ExtConnection> ec) {
state Namespace ns;
ns.first = upOneLevel(query->ns.second);
state std::string sourceCollection = getLastPart(query->ns.second);
state std::string destinationCollection = getLastPart(query->query.getStringField("to"));
state bool dropTarget = query->query.getBoolField("dropTarget");
state Future<bool> exists_destinationCollectionF =
ec->docLayer->rootDirectory->exists(tr->tr, {StringRef(ns.first), StringRef(destinationCollection)});
state Future<bool> exists_sourceCollectionF =
ec->docLayer->rootDirectory->exists(tr->tr, {StringRef(ns.first), StringRef(sourceCollection)});
wait(success(exists_destinationCollectionF) && success(exists_sourceCollectionF));
if (exists_sourceCollectionF.get()) {
if (exists_destinationCollectionF.get()) {
if (dropTarget) {
if (sourceCollection == destinationCollection) {
throw old_and_new_collection_name_cannot_be_same();
}
ns.second = destinationCollection;
state Reference<UnboundCollectionContext> unbound = wait(ec->mm->getUnboundCollectionContext(tr, ns));
wait(success(internal_doDropIndexesActor(tr, ns, ec->mm)));
wait(unbound->collectionDirectory->remove(tr->tr));
} else {
throw collection_name_already_exist();
}
}
} else {
throw collection_name_does_not_exist();
}
wait(success(ec->docLayer->rootDirectory->move(tr->tr, {StringRef(ns.first), StringRef(sourceCollection)},
{StringRef(ns.first), StringRef(destinationCollection)})));
ns.second = sourceCollection;
wait(success(internal_doRenameCollectionIndexesActor(tr, ns, ec->mm, destinationCollection)));
return Void();
}
ACTOR static Future<Reference<ExtMsgReply>> doRenameCollection(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
try {
// No need to wait on lastWrite in either case. The ranges we write ensure that this will conflict with
// anything it needs to conflict with.
wait(runRYWTransaction(ec->docLayer->database,
[=](Reference<DocTransaction> tr) { return Internal_doRenameCollection(tr, query, ec); },
ec->options.retryLimit, ec->options.timeoutMillies));
reply->addDocument(BSON("ok" << 1.0));
return reply;
} catch (Error& e) {
reply->addDocument(BSON("ok" << 0.0 << "errmsg" << e.what() << "code" << e.code()));
return reply;
}
}
struct RenameCollectionCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doRenameCollection(ec, query, reply);
}
};
REGISTER_CMD(RenameCollectionCmd, "renamecollection");
ACTOR static Future<Reference<ExtMsgReply>> getStreamCount(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
try {
state Reference<DocTransaction> dtr = ec->getOperationTransaction();
Reference<UnboundCollectionContext> cx = wait(ec->mm->getUnboundCollectionContext(dtr, query->ns, true));
Reference<Plan> plan = planQuery(cx, query->query.getObjectField(DocLayerConstants::QUERY_FIELD));
plan = ec->wrapOperationPlan(plan, true, cx);
// Rather than use a SkipPlan, we subtract "skipped" documents from the final count (and add them to any limit)
state int64_t skip = query->query.hasField("skip") ? query->query.getField("skip").numberLong() : 0;
state int64_t limitPlusSkip = query->query.hasField("limit")
? skip + query->query.getField("limit").numberLong()
: std::numeric_limits<int64_t>::max();
// SOMEDAY: We can optimize this by only counting the first limitPlusSkip documents
int64_t count = wait(executeUntilCompletionTransactionally(plan, dtr));
reply->addDocument(BSON("n" << (double)std::max<int64_t>(count - skip, 0) << "ok" << 1.0));
return reply;
} catch (Error& e) {
reply->addDocument(BSON("$err" << e.what() << "code" << e.code() << "ok" << 1.0));
reply->setResponseFlags(2);
return reply;
}
}
struct GetCountCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return getStreamCount(ec, query, reply);
}
};
REGISTER_CMD(GetCountCmd, "count");
ACTOR static Future<Reference<ExtMsgReply>> doFindAndModify(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
try {
state bool issort = query->query.hasField("sort");
state bool isremove = query->query.hasField("remove") && query->query.getField("remove").trueValue();
state bool isnew = query->query.hasField("new") && query->query.getField("new").trueValue() && !(isremove);
state bool isupdate = query->query.hasField("update");
state bool isupsert =
isupdate && query->query.hasField("upsert") && query->query.getField("upsert").trueValue();
state bson::BSONObj selector = query->query.hasField(DocLayerConstants::QUERY_FIELD)
? query->query.getObjectField(DocLayerConstants::QUERY_FIELD).getOwned()
: bson::BSONObj();
state Reference<Projection> projection = query->query.hasField("fields")
? parseProjection(query->query.getObjectField("fields").getOwned())
: Reference<Projection>(new Projection());
state Optional<bson::BSONObj> ordering =
issort ? query->query.getObjectField("sort") : Optional<bson::BSONObj>();
state bson::BSONObj updateDoc;
state bson::BSONObj retval;
if (issort) {
throw not_implemented();
}
if (isupdate) {
updateDoc = query->query.getObjectField("update");
}
state bool isoperatorUpdate = isupdate && hasOperatorFieldnames(updateDoc);
if ((isremove && isupdate) || !(isremove || isupdate))
throw bad_find_and_modify();
if (isoperatorUpdate) {
staticValidateUpdateObject(updateDoc, false, isupsert);
}
state Reference<DocTransaction> tr = ec->getOperationTransaction();
state Reference<UnboundCollectionContext> ucx = wait(ec->mm->getUnboundCollectionContext(tr, query->ns));
state Reference<IUpdateOp> updater;
state Reference<IInsertOp> upserter;
if (isremove)
updater = ref(new DeleteDocument());
else if (isoperatorUpdate)
updater = operatorUpdate(updateDoc);
else
updater = replaceUpdate(updateDoc);
if (isupsert) {
if (isoperatorUpdate)
upserter = operatorUpsert(selector, updateDoc);
else
upserter = simpleUpsert(selector, updateDoc);
}
state Reference<Plan> plan = planQuery(ucx, selector);
plan = ref(new FindAndModifyPlan(plan, updater, upserter, projection, ordering, isnew, ucx,
ec->docLayer->database, ec->mm));
state std::pair<int64_t, Reference<ScanReturnedContext>> pair =
wait(executeUntilCompletionAndReturnLastTransactionally(plan, tr));
state int64_t i = pair.first;
state bool returnedUpserted = i && pair.second->scanId() == -1;
if (i) {
retval = pair.second->toDataValue().get().getPackedObject().getOwned();
}
bson::BSONObjBuilder bob;
if (!isnew) {
if (i) {
bob.appendObject("value", retval.objdata());
} else if (!issort) {
bob.appendNull("value");
} else {
bob.appendObject("value", bson::BSONObj().objdata());
}
} else {
if (i) {
bob.appendObject("value", retval.objdata());
} else {
bob.appendNull("value");
}
}
bson::BSONObjBuilder lastErrorObject;
lastErrorObject.appendBool("updatedExisting", i && !returnedUpserted);
lastErrorObject.appendNumber("n", (int)i);
if (returnedUpserted)
lastErrorObject.append(retval.getField(DocLayerConstants::ID_FIELD));
bson::BSONObj lastErrorObj = lastErrorObject.obj().getOwned();
bob.appendObject("lastErrorObject", lastErrorObj.objdata());
bob.appendNumber("ok", 1.0);
bson::BSONObj replyObj = bob.obj().getOwned();
reply->addDocument(replyObj);
} catch (Error& e) {
// clang-format off
reply->addDocument(BSON("errmsg" << e.what() <<
"$err" << e.what() <<
"code" << e.code() <<
"ok" << 1.0));
// clang-format on
}
return reply;
}
struct FindAndModifyCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doFindAndModify(ec, query, reply);
}
};
REGISTER_CMD(FindAndModifyCmd, "findandmodify");
ACTOR static Future<Reference<ExtMsgReply>> doDropIndexesActor(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
state int dropped;
try {
if (query->query.hasField("index")) {
bson::BSONElement el = query->query.getField("index");
if (el.type() == bson::BSONType::String) {
if (el.String() == "*") {
// No need to wait on lastWrite in either case. The ranges we write ensure that this will conflict
// with anything it needs to conflict with.
int result = wait(runRYWTransaction(ec->docLayer->database,
[=](Reference<DocTransaction> tr) {
return internal_doDropIndexesActor(tr, query->ns, ec->mm);
},
ec->options.retryLimit, ec->options.timeoutMillies));
dropped = result;
reply->addDocument(BSON("nIndexesWas" << dropped + 1 << "msg"
<< "non-_id indexes dropped for collection"
<< "ok" << 1.0));
return reply;
} else {
std::pair<int, int> result = wait(runRYWTransaction(
ec->docLayer->database,
[=](Reference<DocTransaction> tr) {
return dropIndexMatching(tr, query->ns, DocLayerConstants::NAME_FIELD,
DataValue(el.String(), DVTypeCode::STRING), ec->mm);
},
ec->options.retryLimit, ec->options.timeoutMillies));
dropped = result.first;
reply->addDocument(BSON("nIndexesWas" << dropped + 1 << "ok" << 1.0));
return reply;
}
} else if (el.type() == bson::BSONType::Object) {
std::pair<int, int> result =
wait(runRYWTransaction(ec->docLayer->database,
[=](Reference<DocTransaction> tr) {
return dropIndexMatching(tr, query->ns, DocLayerConstants::KEY_FIELD,
DataValue(el.Obj()), ec->mm);
},
ec->options.retryLimit, ec->options.timeoutMillies));
dropped = result.first;
reply->addDocument(BSON("nIndexesWas" << dropped + 1 << "ok" << 1.0));
return reply;
} else {
// clang-format off
reply->addDocument(BSON("ok" << 0.0 <<
"$err" << "'index' must be a string or an object" <<
"errmsg" << "'index' must be a string or an object"));
// clang-format on
return reply;
}
} else {
int result = wait(runRYWTransaction(
ec->docLayer->database,
[=](Reference<DocTransaction> tr) { return internal_doDropIndexesActor(tr, query->ns, ec->mm); },
ec->options.retryLimit, ec->options.timeoutMillies));
dropped = result;
// clang-format off
reply->addDocument(BSON("nIndexesWas" << dropped + 1 <<
"msg" << "non-_id indexes dropped for collection" <<
"ok" << 1.0));
// clang-format on
return reply;
}
} catch (Error& e) {
// clang-format off
reply->addDocument(BSON("ok" << 0.0 <<
"err" << e.what() <<
"code" << e.code()));
// clang-format on
return reply;
}
}
struct DropIndexesCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doDropIndexesActor(nmc, query, reply);
}
};
REGISTER_CMD(DropIndexesCmd, "dropindexes");
// Hooray for "compatibility"
struct DeleteIndexesCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> nmc,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doDropIndexesActor(nmc, query, reply);
}
};
REGISTER_CMD(DeleteIndexesCmd, "deleteindexes");
ACTOR static Future<Reference<ExtMsgReply>> doCreateIndexes(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
std::vector<Future<WriteCmdResult>> f;
std::vector<bson::BSONElement> arr = query->query.getField("indexes").Array();
for (auto el : arr) {
bson::BSONObj indexDoc = el.Obj();
f.push_back(attemptIndexInsertion(indexDoc, ec, ec->getOperationTransaction(), query->ns));
}
try {
wait(waitForAll(f));
reply->addDocument(BSON("ok" << 1.0));
} catch (Error& e) {
// clang-format off
reply->addDocument(BSON("ok" << 0.0 <<
"$err" << e.what() <<
"errmsg" << e.what() <<
"code" << e.code()));
// clang-format on
}
return reply;
}
struct CreateIndexesCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doCreateIndexes(ec, query, reply);
}
};
REGISTER_CMD(CreateIndexesCmd, "createindexes");
struct BuildInfoCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
// clang-format off
reply->addDocument(BSON(
"version" << EXT_SERVER_VERSION <<
"gitVersion" << getGitVersion() <<
"OpenSSLVersion" << "" <<
"sysInfo" << "<string>" <<
"loaderFlags" << "<string>" <<
"compilerFlags" << "<string>" <<
"allocator" << "<string>" <<
"versionArray" << EXT_SERVER_VERSION_ARRAY <<
"javascriptEngine" << "<string>" <<
"bits" << 64 <<
"debug" << false <<
"maxBsonObjectSize"<< 16777216 <<
"ok" << 1.0
));
// clang-format on
return reply;
}
};
REGISTER_CMD(BuildInfoCmd, "buildinfo");
ACTOR static Future<Reference<ExtMsgReply>> listDatabases(Reference<DocTransaction> tr,
Reference<ExtMsgReply> reply,
Reference<DirectorySubspace> rootDirectory) {
state bson::BSONObjBuilder bob;
state bson::BSONArrayBuilder bab;
state std::string dbName;
state Standalone<VectorRef<StringRef>> dbs = wait(rootDirectory->list(tr->tr));
for (auto db : dbs) {
dbName = db.toString();
Standalone<VectorRef<StringRef>> colls = wait(rootDirectory->list(tr->tr, {db}));
bool empty = colls.empty();
bab.append(
BSON(DocLayerConstants::NAME_FIELD << dbName << "sizeOnDisk" << (empty ? 0 : 1000000) << "empty" << empty));
}
bob.appendArray("databases", bab.arr());
bob.append("totalSize", -1);
bob.append("ok", 1.0);
reply->addDocument(bob.obj());
return reply;
}
struct ListDatabasesCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return listDatabases(ec->getOperationTransaction(), reply, ec->docLayer->rootDirectory);
}
};
REGISTER_CMD(ListDatabasesCmd, "listdatabases");
ACTOR static Future<Reference<ExtMsgReply>> getDBStats(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
state Reference<DocTransaction> tr = ec->getOperationTransaction();
state Standalone<VectorRef<StringRef>> collections =
wait(ec->docLayer->rootDirectory->list(tr->tr, {StringRef(query->ns.first)}));
state Reference<UnboundCollectionContext> cx = wait(ec->mm->indexesCollection(tr, query->ns.first));
state int64_t indexes = wait(executeUntilCompletionTransactionally(ref(new TableScanPlan(cx)), tr));
reply->addDocument(BSON("db" << query->ns.first << "collections" << collections.size() << "indexes"
<< (int)(indexes + collections.size()) << "ok" << 1.0));
return reply;
}
// FIXME: Add more to this command
struct DBStatsCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return getDBStats(ec, query, reply);
}
};
REGISTER_CMD(DBStatsCmd, "dbstats");
// FIXME: Add more here too
ACTOR static Future<Reference<ExtMsgReply>> getCollectionStats(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
state Reference<DocTransaction> tr = ec->getOperationTransaction();
state Reference<Plan> plan = wait(getIndexesForCollectionPlan(query->ns, tr, ec->mm));
state int64_t indexesCount = wait(executeUntilCompletionTransactionally(plan, tr));
reply->addDocument(BSON(DocLayerConstants::NS_FIELD << query->ns.first + "." + query->ns.second << "nindexes"
<< (int)indexesCount + 1 << "ok" << 1.0));
return reply;
}
struct CollectionStatsCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return getCollectionStats(ec, query, reply);
}
};
REGISTER_CMD(CollectionStatsCmd, "collstats");
ACTOR static Future<Void> Internal_doCreateCollection(Reference<DocTransaction> tr,
Reference<ExtMsgQuery> query,
Reference<MetadataManager> mm) {
state Reference<UnboundCollectionContext> unbound = wait(mm->getUnboundCollectionContext(tr, query->ns));
return Void();
}
ACTOR static Future<Reference<ExtMsgReply>> doCreateCollection(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
try {
if (query->query.getBoolField("capped") || query->query.hasField("storageEngine")) {
TraceEvent(SevWarn, "CreateUnsupportedOption").detail("query", query->toString());
throw unsupported_cmd_option();
}
wait(runRYWTransaction(
ec->docLayer->database,
[=](Reference<DocTransaction> tr) { return Internal_doCreateCollection(tr, query, ec->mm); },
ec->options.retryLimit, ec->options.timeoutMillies));
reply->addDocument(BSON("ok" << 1.0));
return reply;
} catch (Error& e) {
reply->addDocument(BSON("ok" << 1.0 << "err" << e.what() << "code" << e.code()));
return reply;
}
}
struct CreateCollectionCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doCreateCollection(ec, query, reply);
}
};
REGISTER_CMD(CreateCollectionCmd, "create");
ACTOR static Future<Reference<ExtMsgReply>> doGetKVStatusActor(Reference<ExtConnection> ec,
Reference<ExtMsgReply> reply) {
try {
state Reference<DocTransaction> dtr = ec->getOperationTransaction();
state StringRef statusKey = LiteralStringRef("\xff\xff/status/json");
Optional<FDB::FDBStandalone<StringRef>> status = wait(dtr->tr->get(statusKey));
if (status.present()) {
const DataValue vv = DataValue::decode_value(status.get());
reply->addDocument(
BSON("ok" << 1.0 << "jsonValue"
<< vv.encode_value().toString()) /*bson::fromjson(vv.encode_value().c_str())*/);
}
} catch (Error& e) {
reply->addDocument(
BSON("ok" << 1.0 << "err"
<< "This command is supported only with version 3.0 and above of the KV Store, if you are using "
"an older FDB version please use the fdbcli utility to check its status."
<< "code" << e.code()));
}
return reply;
}
struct GetKVStatusCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
return doGetKVStatusActor(ec, reply);
}
};
REGISTER_CMD(GetKVStatusCmd, "getkvstatus");
struct GetDocLayerVersionCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
// clang-format off
reply->addDocument(BSON(
"ok" << 1 <<
"packageVersion" << FDB_DOC_VT_VERSION <<
"sourceVersion" << getGitVersion() <<
"flowSourceVersion" << getFlowGitVersion()
));
// clang-format on
return reply;
}
};
REGISTER_CMD(GetDocLayerVersionCmd, "getdoclayerversion");
struct BuggifyKnobsCmd {
static const char* name;
static Future<Reference<ExtMsgReply>> call(Reference<ExtConnection> ec,
Reference<ExtMsgQuery> query,
Reference<ExtMsgReply> reply) {
enableBuggify(true);
const bool bEnable = query->query.getBoolField(name);
auto* docLayerKnobs = new DocLayerKnobs(bEnable);
delete DOCLAYER_KNOBS;
DOCLAYER_KNOBS = docLayerKnobs;
reply->addDocument(DOCLAYER_KNOBS->dumpKnobs());
return reply;
}
};
REGISTER_CMD(BuggifyKnobsCmd, "buggifyknobs");