/
pdfile.cpp
1786 lines (1585 loc) · 66.1 KB
/
pdfile.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
// pdfile.cpp
/**
* Copyright (C) 2008 10gen 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/>.
*/
/*
todo:
_ table scans must be sequential, not next/prev pointers
_ coalesce deleted
_ disallow system* manipulations from the database.
*/
#include "stdafx.h"
#include "pdfile.h"
#include "db.h"
#include "../util/mmap.h"
#include "../util/hashtab.h"
#include "../util/file_allocator.h"
#include "btree.h"
#include <algorithm>
#include <list>
#include "query.h"
#include "repl.h"
#include "dbhelpers.h"
#include "namespace.h"
#include "queryutil.h"
#include "extsort.h"
namespace mongo {
string dbpath = "/data/db/";
DataFileMgr theDataFileMgr;
map<string,Database*> databases;
int MAGIC = 0x1000;
int curOp = -2;
int callDepth = 0;
extern int otherTraceLevel;
void addNewNamespaceToCatalog(const char *ns, const BSONObj *options = 0);
void ensureIdIndexForNewNs(const char *ns) {
if ( !strstr( ns, ".system." ) && !strstr( ns, ".$freelist" ) ) {
log( 1 ) << "adding _id index for new collection" << endl;
ensureHaveIdIndex( ns );
}
}
string getDbContext() {
stringstream ss;
Client * c = currentClient.get();
if ( c ){
Database *database = c->database();
if ( database ) {
ss << database->name << ' ';
ss << cc().ns() << ' ';
}
}
ss<< "op:" << curOp << ' ' << callDepth;
return ss.str();
}
BSONObj::BSONObj(const Record *r) {
init(r->data, false);
}
/*---------------------------------------------------------------------*/
int initialExtentSize(int len) {
long long sz = len * 16;
if ( len < 1000 ) sz = len * 64;
if ( sz > 1000000000 )
sz = 1000000000;
int z = ((int)sz) & 0xffffff00;
assert( z > len );
DEV log() << "initialExtentSize(" << len << ") returns " << z << endl;
return z;
}
bool _userCreateNS(const char *ns, const BSONObj& j, string& err) {
if ( nsdetails(ns) ) {
err = "collection already exists";
return false;
}
log(1) << "create collection " << ns << ' ' << j << '\n';
/* todo: do this only when we have allocated space successfully? or we could insert with a { ok: 0 } field
and then go back and set to ok : 1 after we are done.
*/
if( strstr(ns, ".$freelist") == 0 )
addNewNamespaceToCatalog(ns, j.isEmpty() ? 0 : &j);
long long size = initialExtentSize(128);
BSONElement e = j.findElement("size");
if ( e.isNumber() ) {
size = (long long) e.number();
size += 256;
size &= 0xffffffffffffff00LL;
}
uassert( "invalid size spec", size > 0 );
bool newCapped = false;
int mx = 0;
e = j.findElement("capped");
if ( e.type() == Bool && e.boolean() ) {
newCapped = true;
e = j.findElement("max");
if ( e.isNumber() ) {
mx = (int) e.number();
}
}
// $nExtents just for debug/testing. We create '$nExtents' extents,
// each of size 'size'.
e = j.findElement( "$nExtents" );
int nExtents = int( e.number() );
Database *database = cc().database();
if ( nExtents > 0 ) {
assert( size <= 0x7fffffff );
for ( int i = 0; i < nExtents; ++i ) {
database->suitableFile((int) size)->allocExtent( ns, (int) size, newCapped );
}
} else {
while ( size > 0 ) {
int max = MongoDataFile::maxSize() - MDFHeader::headerSize();
int desiredExtentSize = (int) (size > max ? max : size);
Extent *e = database->suitableFile( desiredExtentSize )->allocExtent( ns, desiredExtentSize, newCapped );
size -= e->length;
}
if ( !newCapped ) {
// ok to call this multiple times
database->preallocateAFile();
}
}
NamespaceDetails *d = nsdetails(ns);
assert(d);
if ( j.getField( "autoIndexId" ).isBoolean() ) {
if ( j.getBoolField( "autoIndexId" ) ) {
ensureIdIndexForNewNs( ns );
}
} else {
if ( !newCapped ) {
ensureIdIndexForNewNs( ns );
}
}
if ( mx > 0 )
d->max = mx;
return true;
}
// { ..., capped: true, size: ..., max: ... }
// returns true if successful
bool userCreateNS(const char *ns, BSONObj j, string& err, bool logForReplication) {
const char *coll = strchr( ns, '.' ) + 1;
massert( "invalid ns", coll && *coll );
char cl[ 256 ];
nsToClient( ns, cl );
bool ok = _userCreateNS(ns, j, err);
if ( logForReplication && ok ) {
if ( j.getField( "create" ).eoo() ) {
BSONObjBuilder b;
b << "create" << coll;
b.appendElements( j );
j = b.obj();
}
string logNs = string( cl ) + ".$cmd";
logOp("c", logNs.c_str(), j);
}
return ok;
}
/*---------------------------------------------------------------------*/
int MongoDataFile::maxSize() {
if ( sizeof( int* ) == 4 )
return 512 * 1024 * 1024;
else
return 0x7ff00000;
}
int MongoDataFile::defaultSize( const char *filename ) const {
int size;
if ( fileNo <= 4 )
size = (64*1024*1024) << fileNo;
else
size = 0x7ff00000;
if ( strstr(filename, "_hudsonSmall") ) {
int mult = 1;
if ( fileNo > 1 && fileNo < 1000 )
mult = fileNo;
size = 1024 * 512 * mult;
log() << "Warning : using small files for _hudsonSmall" << endl;
}
else if ( cmdLine.smallfiles ){
size = size >> 2;
}
return size;
}
void MongoDataFile::open( const char *filename, int minSize, bool preallocateOnly ) {
{
/* check quotas
very simple temporary implementation - we will in future look up
the quota from the grid database
*/
if ( cmdLine.quota && fileNo > 8 && !boost::filesystem::exists(filename) ) {
/* todo: if we were adding / changing keys in an index did we do some
work previously that needs cleaning up? Possible. We should
check code like that and have it catch the exception and do
something reasonable.
*/
string s = "db disk space quota exceeded ";
Database *database = cc().database();
if ( database )
s += database->name;
uasserted(s);
}
}
long size = defaultSize( filename );
while ( size < minSize ) {
if ( size < maxSize() / 2 )
size *= 2;
else {
size = maxSize();
break;
}
}
if ( size > maxSize() )
size = maxSize();
assert( ( size >= 64*1024*1024 ) || cmdLine.smallfiles || ( strstr( filename, "_hudsonSmall" ) ) );
assert( size % 4096 == 0 );
if ( preallocateOnly ) {
if ( cmdLine.prealloc ) {
theFileAllocator().requestAllocation( filename, size );
}
return;
}
header = (MDFHeader *) mmf.map(filename, size);
if( sizeof(char *) == 4 )
uassert("can't map file memory - mongo requires 64 bit build for larger datasets", header);
else
uassert("can't map file memory", header);
header->init(fileNo, size);
}
void addNewExtentToNamespace(const char *ns, Extent *e, DiskLoc eloc, DiskLoc emptyLoc, bool capped) {
DiskLoc oldExtentLoc;
NamespaceIndex *ni = nsindex(ns);
NamespaceDetails *details = ni->details(ns);
if ( details ) {
assert( !details->lastExtent.isNull() );
assert( !details->firstExtent.isNull() );
e->xprev = details->lastExtent;
details->lastExtent.ext()->xnext = eloc;
assert( !eloc.isNull() );
details->lastExtent = eloc;
}
else {
ni->add(ns, eloc, capped);
details = ni->details(ns);
}
details->lastExtentSize = e->length;
DEBUGGING out() << "temp: newextent adddelrec " << ns << endl;
details->addDeletedRec(emptyLoc.drec(), emptyLoc);
}
Extent* MongoDataFile::createExtent(const char *ns, int approxSize, bool newCapped, int loops) {
massert( "shutdown in progress", !goingAway );
massert( "bad new extent size", approxSize >= 0 && approxSize <= 0x7ff00000 );
massert( "header==0 on new extent: 32 bit mmap space exceeded?", header ); // null if file open failed
int ExtentSize = approxSize <= header->unusedLength ? approxSize : header->unusedLength;
DiskLoc loc;
if ( ExtentSize <= 0 ) {
/* not there could be a lot of looping here is db just started and
no files are open yet. we might want to do something about that. */
if ( loops > 8 ) {
assert( loops < 10000 );
out() << "warning: loops=" << loops << " fileno:" << fileNo << ' ' << ns << '\n';
}
log() << "newExtent: " << ns << " file " << fileNo << " full, adding a new file\n";
return cc().database()->addAFile( 0, true )->createExtent(ns, approxSize, newCapped, loops+1);
}
int offset = header->unused.getOfs();
header->unused.setOfs( fileNo, offset + ExtentSize );
header->unusedLength -= ExtentSize;
loc.setOfs(fileNo, offset);
Extent *e = _getExtent(loc);
DiskLoc emptyLoc = e->init(ns, ExtentSize, fileNo, offset);
addNewExtentToNamespace(ns, e, loc, emptyLoc, newCapped);
DEV log() << "new extent " << ns << " size: 0x" << hex << ExtentSize << " loc: 0x" << hex << offset
<< " emptyLoc:" << hex << emptyLoc.getOfs() << dec << endl;
return e;
}
Extent* MongoDataFile::allocExtent(const char *ns, int approxSize, bool capped) {
string s = cc().database()->name + ".$freelist";
NamespaceDetails *f = nsdetails(s.c_str());
if( f ) {
int low, high;
if( capped ) {
// be strict about the size
low = approxSize;
if( low > 2048 ) low -= 256;
high = (int) (approxSize * 1.05) + 256;
}
else {
low = (int) (approxSize * 0.8);
high = (int) (approxSize * 1.4);
}
if( high < 0 ) high = approxSize;
int n = 0;
Extent *best = 0;
int bestDiff = 0x7fffffff;
{
DiskLoc L = f->firstExtent;
while( !L.isNull() ) {
Extent * e = L.ext();
if( e->length >= low && e->length <= high ) {
int diff = abs(e->length - approxSize);
if( diff < bestDiff ) {
bestDiff = diff;
best = e;
if( diff == 0 )
break;
}
}
L = e->xnext;
++n;
}
}
OCCASIONALLY if( n > 512 ) log() << "warning: newExtent " << n << " scanned\n";
if( best ) {
Extent *e = best;
// remove from the free list
if( !e->xprev.isNull() )
e->xprev.ext()->xnext = e->xnext;
if( !e->xnext.isNull() )
e->xnext.ext()->xprev = e->xprev;
if( f->firstExtent == e->myLoc )
f->firstExtent = e->xnext;
if( f->lastExtent == e->myLoc )
f->lastExtent = e->xprev;
// use it
OCCASIONALLY if( n > 512 ) log() << "warning: newExtent " << n << " scanned\n";
DiskLoc emptyLoc = e->reuse(ns);
addNewExtentToNamespace(ns, e, e->myLoc, emptyLoc, capped);
return e;
}
}
return createExtent(ns, approxSize, capped);
}
/*---------------------------------------------------------------------*/
DiskLoc Extent::reuse(const char *nsname) {
log(3) << "reset extent was:" << ns.buf << " now:" << nsname << '\n';
massert( "Extent::reset bad magic value", magic == 0x41424344 );
xnext.Null();
xprev.Null();
ns = nsname;
firstRecord.Null();
lastRecord.Null();
DiskLoc emptyLoc = myLoc;
emptyLoc.inc( (extentData-(char*)this) );
int delRecLength = length - (extentData - (char *) this);
DeletedRecord *empty1 = (DeletedRecord *) extentData;
DeletedRecord *empty = (DeletedRecord *) getRecord(emptyLoc);
assert( empty == empty1 );
memset(empty, delRecLength, 1);
empty->lengthWithHeaders = delRecLength;
empty->extentOfs = myLoc.getOfs();
empty->nextDeleted.Null();
return emptyLoc;
}
/* assumes already zeroed -- insufficient for block 'reuse' perhaps */
DiskLoc Extent::init(const char *nsname, int _length, int _fileNo, int _offset) {
magic = 0x41424344;
myLoc.setOfs(_fileNo, _offset);
xnext.Null();
xprev.Null();
ns = nsname;
length = _length;
firstRecord.Null();
lastRecord.Null();
DiskLoc emptyLoc = myLoc;
emptyLoc.inc( (extentData-(char*)this) );
DeletedRecord *empty1 = (DeletedRecord *) extentData;
DeletedRecord *empty = (DeletedRecord *) getRecord(emptyLoc);
assert( empty == empty1 );
empty->lengthWithHeaders = _length - (extentData - (char *) this);
empty->extentOfs = myLoc.getOfs();
return emptyLoc;
}
/*
Record* Extent::newRecord(int len) {
if( firstEmptyRegion.isNull() )
return 0;
assert(len > 0);
int newRecSize = len + Record::HeaderSize;
DiskLoc newRecordLoc = firstEmptyRegion;
Record *r = getRecord(newRecordLoc);
int left = r->netLength() - len;
if( left < 0 ) {
//
firstEmptyRegion.Null();
return 0;
}
DiskLoc nextEmpty = r->next.getNextEmpty(firstEmptyRegion);
r->lengthWithHeaders = newRecSize;
r->next.markAsFirstOrLastInExtent(this); // we're now last in the extent
if( !lastRecord.isNull() ) {
assert(getRecord(lastRecord)->next.lastInExtent()); // it was the last one
getRecord(lastRecord)->next.set(newRecordLoc); // until now
r->prev.set(lastRecord);
}
else {
r->prev.markAsFirstOrLastInExtent(this); // we are the first in the extent
assert( firstRecord.isNull() );
firstRecord = newRecordLoc;
}
lastRecord = newRecordLoc;
if( left < Record::HeaderSize + 32 ) {
firstEmptyRegion.Null();
}
else {
firstEmptyRegion.inc(newRecSize);
Record *empty = getRecord(firstEmptyRegion);
empty->next.set(nextEmpty); // not for empty records, unless in-use records, next and prev can be null.
empty->prev.Null();
empty->lengthWithHeaders = left;
}
return r;
}
*/
/*---------------------------------------------------------------------*/
auto_ptr<Cursor> DataFileMgr::findAll(const char *ns, const DiskLoc &startLoc) {
DiskLoc loc;
bool found = nsindex(ns)->find(ns, loc);
if ( !found ) {
// out() << "info: findAll() namespace does not exist: " << ns << endl;
return auto_ptr<Cursor>(new BasicCursor(DiskLoc()));
}
Extent *e = getExtent(loc);
DEBUGGING {
out() << "listing extents for " << ns << endl;
DiskLoc tmp = loc;
set<DiskLoc> extents;
while ( 1 ) {
Extent *f = getExtent(tmp);
out() << "extent: " << tmp.toString() << endl;
extents.insert(tmp);
tmp = f->xnext;
if ( tmp.isNull() )
break;
f = f->getNextExtent();
}
out() << endl;
nsdetails(ns)->dumpDeleted(&extents);
}
if ( !nsdetails( ns )->capped ) {
if ( !startLoc.isNull() )
return auto_ptr<Cursor>(new BasicCursor( startLoc ));
while ( e->firstRecord.isNull() && !e->xnext.isNull() ) {
/* todo: if extent is empty, free it for reuse elsewhere.
that is a bit complicated have to clean up the freelists.
*/
RARELY out() << "info DFM::findAll(): extent " << loc.toString() << " was empty, skipping ahead " << ns << endl;
// find a nonempty extent
// it might be nice to free the whole extent here! but have to clean up free recs then.
e = e->getNextExtent();
}
return auto_ptr<Cursor>(new BasicCursor( e->firstRecord ));
} else {
return auto_ptr< Cursor >( new ForwardCappedCursor( nsdetails( ns ), startLoc ) );
}
}
/* get a table scan cursor, but can be forward or reverse direction.
order.$natural - if set, > 0 means forward (asc), < 0 backward (desc).
*/
auto_ptr<Cursor> findTableScan(const char *ns, const BSONObj& order, const DiskLoc &startLoc) {
BSONElement el = order.findElement("$natural"); // e.g., { $natural : -1 }
if ( el.number() >= 0 )
return DataFileMgr::findAll(ns, startLoc);
// "reverse natural order"
NamespaceDetails *d = nsdetails(ns);
if ( !d )
return auto_ptr<Cursor>(new BasicCursor(DiskLoc()));
if ( !d->capped ) {
if ( !startLoc.isNull() )
return auto_ptr<Cursor>(new ReverseCursor( startLoc ));
Extent *e = d->lastExtent.ext();
while ( e->lastRecord.isNull() && !e->xprev.isNull() ) {
OCCASIONALLY out() << " findTableScan: extent empty, skipping ahead" << endl;
e = e->getPrevExtent();
}
return auto_ptr<Cursor>(new ReverseCursor( e->lastRecord ));
} else {
return auto_ptr< Cursor >( new ReverseCappedCursor( d, startLoc ) );
}
}
/* drop a collection/namespace */
void dropNS(const string& nsToDrop) {
NamespaceDetails* d = nsdetails(nsToDrop.c_str());
uassert( (string)"ns not found: " + nsToDrop , d );
NamespaceString s(nsToDrop);
assert( s.db == cc().database()->name );
if( s.isSystem() ) {
if( s.coll == "system.profile" )
uassert( "turn off profiling before dropping system.profile collection", cc().database()->profile == 0 );
else
uasserted( "can't drop system ns" );
}
{
// remove from the system catalog
BSONObj cond = BSON( "name" << nsToDrop ); // { name: "colltodropname" }
string system_namespaces = cc().database()->name + ".system.namespaces";
/*int n = */ deleteObjects(system_namespaces.c_str(), cond, false, false, true);
// no check of return code as this ns won't exist for some of the new storage engines
}
// free extents
if( !d->firstExtent.isNull() ) {
string s = cc().database()->name + ".$freelist";
NamespaceDetails *freeExtents = nsdetails(s.c_str());
if( freeExtents == 0 ) {
string err;
_userCreateNS(s.c_str(), BSONObj(), err);
freeExtents = nsdetails(s.c_str());
massert("can't create .$freelist", freeExtents);
}
if( freeExtents->firstExtent.isNull() ) {
freeExtents->firstExtent = d->firstExtent;
freeExtents->lastExtent = d->lastExtent;
}
else {
DiskLoc a = freeExtents->firstExtent;
assert( a.ext()->xprev.isNull() );
a.ext()->xprev = d->lastExtent;
d->lastExtent.ext()->xnext = a;
freeExtents->firstExtent = d->firstExtent;
d->firstExtent.setInvalid();
d->lastExtent.setInvalid();
}
}
// remove from the catalog hashtable
cc().database()->namespaceIndex.kill(nsToDrop.c_str());
}
void dropCollection( const string &name, string &errmsg, BSONObjBuilder &result ) {
log(1) << "dropCollection: " << name << endl;
NamespaceDetails *d = nsdetails(name.c_str());
assert( d );
if ( d->nIndexes != 0 ) {
try {
assert( deleteIndexes(d, name.c_str(), "*", errmsg, result, true) );
}
catch( DBException& ) {
uasserted("drop: deleteIndexes for collection failed - consider trying repair");
}
assert( d->nIndexes == 0 );
}
log(1) << "\t deleteIndexes done" << endl;
result.append("ns", name.c_str());
ClientCursor::invalidate(name.c_str());
dropNS(name);
}
/* delete this index. does NOT clean up the system catalog
(system.indexes or system.namespaces) -- only NamespaceIndex.
*/
void IndexDetails::kill() {
string ns = indexNamespace(); // e.g. foo.coll.$ts_1
// clean up parent namespace index cache
NamespaceDetailsTransient::get( parentNS().c_str() ).deletedIndex();
BSONObjBuilder b;
b.append("name", indexName().c_str());
b.append("ns", parentNS().c_str());
BSONObj cond = b.done(); // e.g.: { name: "ts_1", ns: "foo.coll" }
/* important to catch exception here so we can finish cleanup below. */
try {
btreeStore->drop(ns.c_str());
}
catch(DBException& ) {
log(2) << "IndexDetails::kill(): couldn't drop ns " << ns << endl;
}
head.setInvalid();
info.setInvalid();
// clean up in system.indexes. we do this last on purpose. note we have
// to make the cond object before the drop() above though.
string system_indexes = cc().database()->name + ".system.indexes";
int n = deleteObjects(system_indexes.c_str(), cond, false, false, true);
wassert( n == 1 );
}
void getKeys( vector< const char * > fieldNames, vector< BSONElement > fixed, const BSONObj &obj, BSONObjSetDefaultOrder &keys ) {
BSONObjBuilder b;
b.appendNull( "" );
BSONElement nullElt = b.done().firstElement();
BSONElement arrElt;
unsigned arrIdx = ~0;
for( unsigned i = 0; i < fieldNames.size(); ++i ) {
if ( *fieldNames[ i ] == '\0' )
continue;
BSONElement e = obj.getFieldDottedOrArray( fieldNames[ i ] );
if ( e.eoo() )
e = nullElt; // no matching field
if ( e.type() != Array )
fieldNames[ i ] = ""; // no matching field or non-array match
if ( *fieldNames[ i ] == '\0' )
fixed[ i ] = e; // no need for further object expansion (though array expansion still possible)
if ( e.type() == Array && arrElt.eoo() ) { // we only expand arrays on a single path -- track the path here
arrIdx = i;
arrElt = e;
}
// enforce single array path here
uassert( "cannot index parallel arrays", e.type() != Array || e.rawdata() == arrElt.rawdata() );
}
bool allFound = true; // have we found elements for all field names in the key spec?
for( vector< const char * >::const_iterator i = fieldNames.begin(); allFound && i != fieldNames.end(); ++i )
if ( **i != '\0' )
allFound = false;
if ( allFound ) {
if ( arrElt.eoo() ) {
// no terminal array element to expand
BSONObjBuilder b;
for( vector< BSONElement >::iterator i = fixed.begin(); i != fixed.end(); ++i )
b.appendAs( *i, "" );
keys.insert( b.obj() );
} else {
// terminal array element to expand, so generate all keys
BSONObjIterator i( arrElt.embeddedObject() );
if ( i.more() ){
while( i.more() ) {
BSONObjBuilder b;
for( unsigned j = 0; j < fixed.size(); ++j ) {
if ( j == arrIdx )
b.appendAs( i.next(), "" );
else
b.appendAs( fixed[ j ], "" );
}
keys.insert( b.obj() );
}
}
else if ( fixed.size() > 1 ){
// x : [] - need to insert undefined
BSONObjBuilder b;
for( unsigned j = 0; j < fixed.size(); ++j ) {
if ( j == arrIdx )
b.appendUndefined( "" );
else
b.appendAs( fixed[ j ], "" );
}
keys.insert( b.obj() );
}
}
} else {
// nonterminal array element to expand, so recurse
assert( !arrElt.eoo() );
BSONObjIterator i( arrElt.embeddedObject() );
while( i.more() ) {
BSONElement e = i.next();
if ( e.type() == Object )
getKeys( fieldNames, fixed, e.embeddedObject(), keys );
}
}
}
void getKeysFromObject( const BSONObj &keyPattern, const BSONObj &obj, BSONObjSetDefaultOrder &keys ) {
BSONObjIterator i( keyPattern );
vector< const char * > fieldNames;
vector< BSONElement > fixed;
BSONObjBuilder nullKey;
while( i.more() ) {
fieldNames.push_back( i.next().fieldName() );
fixed.push_back( BSONElement() );
nullKey.appendNull( "" );
}
getKeys( fieldNames, fixed, obj, keys );
if ( keys.empty() )
keys.insert( nullKey.obj() );
}
/* Pull out the relevant key objects from obj, so we
can index them. Note that the set is multiple elements
only when it's a "multikey" array.
Keys will be left empty if key not found in the object.
*/
void IndexDetails::getKeysFromObject( const BSONObj& obj, BSONObjSetDefaultOrder& keys) const {
BSONObj keyPattern = info.obj().getObjectField("key"); // e.g., keyPattern == { ts : 1 }
if ( keyPattern.objsize() == 0 ) {
out() << keyPattern.toString() << endl;
out() << info.obj().toString() << endl;
assert(false);
}
mongo::getKeysFromObject( keyPattern, obj, keys );
}
int nUnindexes = 0;
void _unindexRecord(IndexDetails& id, BSONObj& obj, const DiskLoc& dl, bool logMissing = true) {
BSONObjSetDefaultOrder keys;
id.getKeysFromObject(obj, keys);
for ( BSONObjSetDefaultOrder::iterator i=keys.begin(); i != keys.end(); i++ ) {
BSONObj j = *i;
// out() << "UNINDEX: j:" << j.toString() << " head:" << id.head.toString() << dl.toString() << endl;
if ( otherTraceLevel >= 5 ) {
out() << "_unindexRecord() " << obj.toString();
out() << "\n unindex:" << j.toString() << endl;
}
nUnindexes++;
bool ok = false;
try {
ok = id.head.btree()->unindex(id.head, id, j, dl);
}
catch (AssertionException&) {
problem() << "Assertion failure: _unindex failed " << id.indexNamespace() << endl;
out() << "Assertion failure: _unindex failed" << '\n';
out() << " obj:" << obj.toString() << '\n';
out() << " key:" << j.toString() << '\n';
out() << " dl:" << dl.toString() << endl;
sayDbContext();
}
if ( !ok && logMissing ) {
out() << "unindex failed (key too big?) " << id.indexNamespace() << '\n';
}
}
}
/* unindex all keys in all indexes for this record. */
void unindexRecord(NamespaceDetails *d, Record *todelete, const DiskLoc& dl, bool noWarn = false) {
if ( d->nIndexes == 0 ) return;
BSONObj obj(todelete);
for ( int i = 0; i < d->nIndexes; i++ ) {
_unindexRecord(d->indexes[i], obj, dl, !noWarn);
}
}
/* deletes a record, just the pdfile portion -- no index cleanup, no cursor cleanup, etc.
caller must check if capped
*/
void DataFileMgr::_deleteRecord(NamespaceDetails *d, const char *ns, Record *todelete, const DiskLoc& dl)
{
/* remove ourself from the record next/prev chain */
{
if ( todelete->prevOfs != DiskLoc::NullOfs )
todelete->getPrev(dl).rec()->nextOfs = todelete->nextOfs;
if ( todelete->nextOfs != DiskLoc::NullOfs )
todelete->getNext(dl).rec()->prevOfs = todelete->prevOfs;
}
/* remove ourself from extent pointers */
{
Extent *e = todelete->myExtent(dl);
if ( e->firstRecord == dl ) {
if ( todelete->nextOfs == DiskLoc::NullOfs )
e->firstRecord.Null();
else
e->firstRecord.setOfs(dl.a(), todelete->nextOfs);
}
if ( e->lastRecord == dl ) {
if ( todelete->prevOfs == DiskLoc::NullOfs )
e->lastRecord.Null();
else
e->lastRecord.setOfs(dl.a(), todelete->prevOfs);
}
}
/* add to the free list */
{
d->nrecords--;
d->datasize -= todelete->netLength();
/* temp: if in system.indexes, don't reuse, and zero out: we want to be
careful until validated more, as IndexDetails has pointers
to this disk location. so an incorrectly done remove would cause
a lot of problems.
*/
if ( strstr(ns, ".system.indexes") ) {
memset(todelete, 0, todelete->lengthWithHeaders);
}
else {
DEV memset(todelete->data, 0, todelete->netLength()); // attempt to notice invalid reuse.
d->addDeletedRec((DeletedRecord*)todelete, dl);
}
}
}
void DataFileMgr::deleteRecord(const char *ns, Record *todelete, const DiskLoc& dl, bool cappedOK, bool noWarn)
{
dassert( todelete == dl.rec() );
NamespaceDetails* d = nsdetails(ns);
if ( d->capped && !cappedOK ) {
out() << "failing remove on a capped ns " << ns << endl;
return;
}
/* check if any cursors point to us. if so, advance them. */
ClientCursor::aboutToDelete(dl);
unindexRecord(d, todelete, dl, noWarn);
_deleteRecord(d, ns, todelete, dl);
NamespaceDetailsTransient::get( ns ).registerWriteOp();
}
void setDifference(BSONObjSetDefaultOrder &l, BSONObjSetDefaultOrder &r, vector<BSONObj*> &diff) {
BSONObjSetDefaultOrder::iterator i = l.begin();
BSONObjSetDefaultOrder::iterator j = r.begin();
while ( 1 ) {
if ( i == l.end() )
break;
while ( j != r.end() && j->woCompare( *i ) < 0 )
j++;
if ( j == r.end() || i->woCompare(*j) != 0 ) {
const BSONObj *jo = &*i;
diff.push_back( (BSONObj *) jo );
}
i++;
}
}
struct IndexChanges/*on an update*/ {
BSONObjSetDefaultOrder oldkeys;
BSONObjSetDefaultOrder newkeys;
vector<BSONObj*> removed; // these keys were removed as part of the change
vector<BSONObj*> added; // these keys were added as part of the change
void dupCheck(IndexDetails& idx) {
if( added.empty() || !idx.unique() )
return;
for( vector<BSONObj*>::iterator i = added.begin(); i != added.end(); i++ )
uassert("E11001 duplicate key on update", !idx.hasKey(**i));
}
};
inline void getIndexChanges(vector<IndexChanges>& v, NamespaceDetails& d, BSONObj newObj, BSONObj oldObj) {
v.resize(d.nIndexes);
for ( int i = 0; i < d.nIndexes; i++ ) {
IndexDetails& idx = d.indexes[i];
BSONObj idxKey = idx.info.obj().getObjectField("key"); // eg { ts : 1 }
IndexChanges& ch = v[i];
idx.getKeysFromObject(oldObj, ch.oldkeys);
idx.getKeysFromObject(newObj, ch.newkeys);
if( ch.newkeys.size() > 1 )
d.setIndexIsMultikey(i);
setDifference(ch.oldkeys, ch.newkeys, ch.removed);
setDifference(ch.newkeys, ch.oldkeys, ch.added);
}
}
inline void dupCheck(vector<IndexChanges>& v, NamespaceDetails& d) {
for ( int i = 0; i < d.nIndexes; i++ ) {
IndexDetails& idx = d.indexes[i];
v[i].dupCheck(idx);
}
}
/** Note: if the object shrinks a lot, we don't free up space, we leave extra at end of the record.
*/
void DataFileMgr::update(
const char *ns,
Record *toupdate, const DiskLoc& dl,
const char *_buf, int _len, stringstream& ss)
{
dassert( toupdate == dl.rec() );
NamespaceDetails *d = nsdetails(ns);
BSONObj objOld(toupdate);
BSONObj objNew(_buf);
assert( objNew.objsize() == _len );
assert( objNew.objdata() == _buf );
if( !objNew.hasElement("_id") && objOld.hasElement("_id") ) {
/* add back the old _id value if the update removes it. Note this implementation is slow
(copies entire object multiple times), but this shouldn't happen often, so going for simple
code, not speed.
*/
BSONObjBuilder b;
BSONElement e;
assert( objOld.getObjectID(e) );
b.append(e); // put _id first, for best performance
b.appendElements(objNew);
objNew = b.obj();
}
/* duplicate key check. we descend the btree twice - once for this check, and once for the actual inserts, further
below. that is suboptimal, but it's pretty complicated to do it the other way without rollbacks...
*/
vector<IndexChanges> changes;
getIndexChanges(changes, *d, objNew, objOld);
dupCheck(changes, *d);
if ( toupdate->netLength() < objNew.objsize() ) {
// doesn't fit. reallocate -----------------------------------------------------
uassert("E10003 failing update: objects in a capped ns cannot grow", !(d && d->capped));
d->paddingTooSmall();
if ( cc().database()->profile )
ss << " moved ";
deleteRecord(ns, toupdate, dl);
insert(ns, objNew.objdata(), objNew.objsize(), false);
return;
}
NamespaceDetailsTransient::get( ns ).registerWriteOp();
d->paddingFits();
/* have any index keys changed? */
if( d->nIndexes ) {
for ( int x = 0; x < d->nIndexes; x++ ) {
IndexDetails& idx = d->indexes[x];
for ( unsigned i = 0; i < changes[x].removed.size(); i++ ) {
try {
idx.head.btree()->unindex(idx.head, idx, *changes[x].removed[i], dl);
}
catch (AssertionException&) {
ss << " exception update unindex ";
problem() << " caught assertion update unindex " << idx.indexNamespace() << endl;
}
}
assert( !dl.isNull() );
BSONObj idxKey = idx.info.obj().getObjectField("key");
for ( unsigned i = 0; i < changes[x].added.size(); i++ ) {
try {
/* we did the dupCheck() above. so we don't have to worry about it here. */
idx.head.btree()->bt_insert(
idx.head,
dl, *changes[x].added[i], idxKey, /*dupsAllowed*/true, idx);
}
catch (AssertionException&) {
ss << " exception update index ";
out() << " caught assertion update index " << idx.indexNamespace() << '\n';
problem() << " caught assertion update index " << idx.indexNamespace() << endl;
}
if ( cc().database()->profile )