0
0
mirror of https://github.com/mongodb/mongo.git synced 2024-11-30 17:10:48 +01:00
mongodb/db/pdfile.cpp

895 lines
24 KiB
C++
Raw Normal View History

2007-10-20 01:35:48 +02:00
// pdfile.cpp
2007-10-30 10:50:14 +01:00
/*
todo:
_ manage deleted records. bucket?
_ use deleted on inserts!
_ quantize allocations
2007-10-30 16:35:17 +01:00
_ table scans must be sequential, not next/prev pointers
2007-10-31 02:16:35 +01:00
_ regex support
2007-10-30 10:50:14 +01:00
*/
2007-10-20 01:35:48 +02:00
#include "stdafx.h"
#include "pdfile.h"
#include "db.h"
#include "../util/mmap.h"
#include "../util/hashtab.h"
2007-11-09 03:42:50 +01:00
#include "objwrappers.h"
#include "btree.h"
2007-11-22 03:44:57 +01:00
#include <algorithm>
2008-03-09 05:16:41 +01:00
#include <list>
2007-10-20 01:35:48 +02:00
2007-11-27 21:30:51 +01:00
const char *dbpath = "/data/db/";
2007-10-20 01:35:48 +02:00
DataFileMgr theDataFileMgr;
2008-01-20 23:42:26 +01:00
map<string,Client*> clients;
Client *client;
2008-02-10 22:28:48 +01:00
const char *curNs = "";
2008-02-26 01:13:30 +01:00
int MAGIC = 0x1000;
int curOp = -2;
2008-03-24 23:04:22 +01:00
int callDepth = 0;
2008-01-20 23:42:26 +01:00
2007-12-02 17:33:59 +01:00
extern int otherTraceLevel;
2007-10-20 01:35:48 +02:00
2008-02-10 22:28:48 +01:00
void sayDbContext() {
cout << " client: " << (client ? client->name.c_str() : "null");
2008-03-24 23:04:22 +01:00
cout << " op:" << curOp << ' ' << callDepth << endl;
2008-02-26 01:13:30 +01:00
if( client )
cout << " ns: " << curNs << endl;
2008-02-10 22:28:48 +01:00
}
2007-11-02 03:34:44 +01:00
JSObj::JSObj(Record *r) {
_objdata = r->data;
_objsize = *((int*) _objdata);
2008-02-11 03:34:17 +01:00
if( _objsize > r->netLength() ) {
cout << "About to assert fail _objsize <= r->netLength()" << endl;
cout << " _objsize: " << _objsize << endl;
cout << " netLength(): " << r->netLength() << endl;
cout << " extentOfs: " << r->extentOfs << endl;
cout << " nextOfs: " << r->nextOfs << endl;
cout << " prevOfs: " << r->prevOfs << endl;
assert( _objsize <= r->netLength() );
}
2007-11-05 04:34:37 +01:00
iFree = false;
2007-11-02 03:34:44 +01:00
}
2007-10-20 01:35:48 +02:00
/*---------------------------------------------------------------------*/
2007-10-30 10:50:14 +01:00
int bucketSizes[] = {
32, 64, 128, 256, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000,
0x8000, 0x10000, 0x20000, 0x40000, 0x80000, 0x100000, 0x200000,
0x400000, 0x800000
};
2008-01-20 23:42:26 +01:00
//NamespaceIndexMgr namespaceIndexMgr;
2007-11-10 22:46:30 +01:00
void NamespaceDetails::addDeletedRec(DeletedRecord *d, DiskLoc dloc) {
int b = bucket(d->lengthWithHeaders);
DiskLoc& list = deletedList[b];
DiskLoc oldHead = list;
list = dloc;
d->nextDeleted = oldHead;
}
2007-10-30 10:50:14 +01:00
2008-03-09 05:16:41 +01:00
/* lenToAlloc is WITH header
*/
DiskLoc NamespaceDetails::alloc(const char *ns, int lenToAlloc, DiskLoc& extentLoc) {
2007-10-30 16:35:17 +01:00
lenToAlloc = (lenToAlloc + 3) & 0xfffffffc;
2008-03-09 05:16:41 +01:00
DiskLoc loc = _alloc(ns, lenToAlloc);
2007-10-30 16:35:17 +01:00
if( loc.isNull() )
return loc;
DeletedRecord *r = loc.drec();
/* note we want to grab from the front so our next pointers on disk tend
to go in a forward direction which is important for performance. */
int regionlen = r->lengthWithHeaders;
extentLoc.set(loc.a(), r->extentOfs);
int left = regionlen - lenToAlloc;
2008-03-09 05:16:41 +01:00
if( left < 24 || (left < (lenToAlloc >> 3) && capped == 0) ) {
2007-10-30 16:35:17 +01:00
// you get the whole thing.
return loc;
}
/* split off some for further use. */
r->lengthWithHeaders = lenToAlloc;
DiskLoc newDelLoc = loc;
newDelLoc.inc(lenToAlloc);
DeletedRecord *newDel = newDelLoc.drec();
newDel->extentOfs = r->extentOfs;
newDel->lengthWithHeaders = left;
newDel->nextDeleted.Null();
addDeletedRec(newDel, newDelLoc);
return loc;
}
void sayDbContext();
2007-10-30 16:35:17 +01:00
/* returned item is out of the deleted list upon return */
2008-03-09 05:16:41 +01:00
DiskLoc NamespaceDetails::__alloc(int len) {
2007-10-30 16:35:17 +01:00
DiskLoc *prev;
DiskLoc *bestprev = 0;
DiskLoc bestmatch;
int bestmatchlen = 0x7fffffff;
int b = bucket(len);
DiskLoc cur = deletedList[b]; prev = &deletedList[b];
int extra = 5; // look for a better fit, a little.
int chain = 0;
while( 1 ) {
2008-03-13 20:39:09 +01:00
{
int a = cur.a();
if( a < -1 || a >= 100000 ) {
cout << "Assertion failure - a() out of range in _alloc() " << a << endl;
sayDbContext();
if( cur == *prev )
prev->Null();
cur.Null();
}
}
2007-10-30 16:35:17 +01:00
if( cur.isNull() ) {
// move to next bucket. if we were doing "extra", just break
if( bestmatchlen < 0x7fffffff )
break;
b++;
if( b > MaxBucket ) {
// out of space. alloc a new extent.
return DiskLoc();
}
cur = deletedList[b]; prev = &deletedList[b];
continue;
}
DeletedRecord *r = cur.drec();
if( r->lengthWithHeaders >= len &&
r->lengthWithHeaders < bestmatchlen ) {
bestmatchlen = r->lengthWithHeaders;
bestmatch = cur;
bestprev = prev;
}
if( bestmatchlen < 0x7fffffff && --extra <= 0 )
break;
if( ++chain > 30 && b < MaxBucket ) {
// too slow, force move to next bucket to grab a big chunk
b++;
chain = 0;
cur.Null();
}
else {
cur = r->nextDeleted; prev = &r->nextDeleted;
}
}
/* unlink ourself from the deleted list */
*bestprev = bestmatch.drec()->nextDeleted;
return bestmatch;
}
2008-03-09 05:16:41 +01:00
/* combine adjacent deleted records
this is O(n^2) but we call it for capped tables where typically n==1 or 2!
(or 3...there will be a little unused sliver at the end of the extent.)
*/
void NamespaceDetails::compact() {
2008-03-09 14:40:34 +01:00
assert(capped);
2008-03-09 05:16:41 +01:00
list<DiskLoc> drecs;
for( int i = 0; i < Buckets; i++ ) {
DiskLoc dl = deletedList[i];
deletedList[i].Null();
while( !dl.isNull() ) {
DeletedRecord *r = dl.drec();
drecs.push_back(dl);
dl = r->nextDeleted;
}
}
drecs.sort();
list<DiskLoc>::iterator j = drecs.begin();
assert( j != drecs.end() );
DiskLoc a = *j;
while( 1 ) {
j++;
if( j == drecs.end() ) {
addDeletedRec(a.drec(), a);
break;
}
DiskLoc b = *j;
while( a.a() == b.a() && a.getOfs() + a.drec()->lengthWithHeaders == b.getOfs() ) {
// a & b are adjacent. merge.
a.drec()->lengthWithHeaders += b.drec()->lengthWithHeaders;
j++;
if( j == drecs.end() ) {
addDeletedRec(a.drec(), a);
return;
}
b = *j;
}
addDeletedRec(a.drec(), a);
a = b;
}
}
DiskLoc NamespaceDetails::_alloc(const char *ns, int len) {
if( !capped )
return __alloc(len);
assert( len < 400000000 );
int passes = 0;
DiskLoc loc;
2008-03-09 14:40:34 +01:00
// delete records until we have room and the max # objects limit achieved.
2008-03-09 05:16:41 +01:00
while( 1 ) {
2008-03-09 14:40:34 +01:00
if( nrecords < max ) {
loc = __alloc(len);
if( !loc.isNull() )
break;
}
2008-03-09 05:16:41 +01:00
DiskLoc fr = firstExtent.ext()->firstRecord;
if( fr.isNull() ) {
cout << "couldn't make room for new record in capped ns\n";
cout << " ns:" << ns;
cout << "\n len: " << len << endl;
assert(false);
return DiskLoc();
}
theDataFileMgr.deleteRecord(ns, fr.rec(), fr, true);
compact();
assert( ++passes < 5000 );
}
return loc;
}
2008-01-20 23:42:26 +01:00
/*
2007-11-02 03:34:44 +01:00
class NamespaceCursor : public Cursor {
public:
virtual bool ok() { return i >= 0; }
virtual Record* _current() { assert(false); return 0; }
virtual DiskLoc currLoc() { assert(false); return DiskLoc(); }
virtual JSObj current() {
NamespaceDetails &d = namespaceIndex.ht->nodes[i].value;
JSObjBuilder b;
b.append("name", namespaceIndex.ht->nodes[i].k.buf);
return b.done();
}
virtual bool advance() {
while( 1 ) {
i++;
if( i >= namespaceIndex.ht->n )
break;
if( namespaceIndex.ht->nodes[i].inUse() )
return true;
}
i = -1000000;
return false;
}
NamespaceCursor() {
i = -1;
advance();
}
private:
int i;
};
auto_ptr<Cursor> makeNamespaceCursor() {
return auto_ptr<Cursor>(new NamespaceCursor());
2008-01-20 23:42:26 +01:00
}*/
2007-11-02 03:34:44 +01:00
2007-11-03 02:30:40 +01:00
void newNamespace(const char *ns) {
cout << "New namespace: " << ns << endl;
2008-01-20 23:42:26 +01:00
if( strstr(ns, "system.namespaces") == 0 ) {
2007-11-03 02:30:40 +01:00
JSObjBuilder b;
b.append("name", ns);
JSObj j = b.done();
2008-01-20 23:42:26 +01:00
char client[256];
nsToClient(ns, client);
string s = client;
s += ".system.namespaces";
theDataFileMgr.insert(s.c_str(), j.objdata(), j.objsize(), true);
2007-11-03 02:30:40 +01:00
}
}
2008-03-09 05:16:41 +01:00
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 );
cout << "initialExtentSize(" << len << ") returns " << z << endl;
return z;
}
2008-03-09 14:40:34 +01:00
// { ..., capped: true, size: ..., max: ... }
2008-03-09 05:16:41 +01:00
bool userCreateNS(const char *ns, JSObj& j) {
if( nsdetails(ns) )
return false;
2008-03-09 14:40:34 +01:00
cout << j.toString() << endl;
2008-03-09 05:16:41 +01:00
newNamespace(ns);
int ies = initialExtentSize(128);
Element e = j.findElement("size");
if( e.type() == Number ) {
ies = (int) e.number();
ies += 256;
ies &= 0xffffff00;
if( ies > 1024 * 1024 * 1024 + 256 ) return false;
}
client->newestFile()->newExtent(ns, ies);
NamespaceDetails *d = nsdetails(ns);
assert(d);
e = j.findElement("capped");
2008-03-09 14:40:34 +01:00
if( e.type() == Bool && e.boolean() ) {
2008-03-09 05:16:41 +01:00
d->capped = 1;
2008-03-09 14:40:34 +01:00
e = j.findElement("max");
if( e.type() == Number ) {
int mx = (int) e.number();
if( mx > 0 )
d->max = mx;
}
}
2008-03-09 05:16:41 +01:00
return true;
}
2007-10-20 01:35:48 +02:00
/*---------------------------------------------------------------------*/
2008-01-20 23:42:26 +01:00
void PhysicalDataFile::open(int fn, const char *filename) {
int length;
2008-03-05 22:51:27 +01:00
2008-02-11 18:36:51 +01:00
if( fn <= 4 ) {
2008-01-20 23:42:26 +01:00
length = (64*1024*1024) << fn;
2008-02-11 18:36:51 +01:00
if( strstr(filename, "alleyinsider") && length < 512 * 1024 * 1024 )
length = 512 * 1024 * 1024;
} else
2008-01-20 23:42:26 +01:00
length = 0x7ff00000;
2008-02-12 05:38:10 +01:00
2008-01-20 23:42:26 +01:00
assert( length >= 64*1024*1024 && length % 4096 == 0 );
assert(fn == fileNo);
2007-10-20 01:35:48 +02:00
header = (PDFHeader *) mmf.map(filename, length);
assert(header);
2008-01-20 23:42:26 +01:00
header->init(fileNo, length);
2007-10-20 01:35:48 +02:00
}
2007-10-30 10:50:14 +01:00
/* prev - previous extent for this namespace. null=this is the first one. */
2008-03-09 05:16:41 +01:00
Extent* PhysicalDataFile::newExtent(const char *ns, int approxSize, int loops) {
assert( approxSize >= 0 && approxSize <= 0x7ff00000 );
2007-11-06 03:43:49 +01:00
int ExtentSize = approxSize <= header->unusedLength ? approxSize : header->unusedLength;
2007-10-30 16:35:17 +01:00
DiskLoc loc;
2007-11-06 03:43:49 +01:00
if( ExtentSize <= 0 ) {
2008-03-09 05:16:41 +01:00
if( loops > 8 ) {
assert(false);
return 0;
}
2008-01-20 23:42:26 +01:00
cout << "INFO: newExtent(): file full, adding a new file " << ns << endl;
2008-03-09 05:16:41 +01:00
return client->addAFile()->newExtent(ns, approxSize, loops+1);
2007-10-20 01:35:48 +02:00
}
int offset = header->unused.getOfs();
2008-01-20 23:42:26 +01:00
header->unused.setOfs( fileNo, offset + ExtentSize );
2007-10-20 01:35:48 +02:00
header->unusedLength -= ExtentSize;
2008-01-20 23:42:26 +01:00
loc.setOfs(fileNo, offset);
2007-10-20 01:35:48 +02:00
Extent *e = _getExtent(loc);
2008-01-20 23:42:26 +01:00
DiskLoc emptyLoc = e->init(ns, ExtentSize, fileNo, offset);
2007-10-30 16:35:17 +01:00
DiskLoc oldExtentLoc;
2008-01-20 23:42:26 +01:00
NamespaceIndex *ni = nsindex(ns);
NamespaceDetails *details = ni->details(ns);
2007-11-13 22:44:01 +01:00
if( details ) {
assert( !details->firstExtent.isNull() );
e->xprev = details->lastExtent;
details->lastExtent.ext()->xnext = loc;
details->lastExtent = loc;
2007-10-30 10:50:14 +01:00
}
2007-10-30 16:35:17 +01:00
else {
2008-01-20 23:42:26 +01:00
ni->add(ns, loc);
details = ni->details(ns);
2007-10-30 16:35:17 +01:00
}
2007-11-13 22:44:01 +01:00
details->lastExtentSize = approxSize;
details->addDeletedRec(emptyLoc.drec(), emptyLoc);
2007-10-30 16:35:17 +01:00
2008-02-29 18:00:17 +01:00
cout << "new extent size: 0x" << hex << ExtentSize << " loc: 0x" << hex << offset << dec;
cout << " emptyLoc:" << hex << emptyLoc.getOfs() << dec;
cout << ' ' << ns << endl;
2007-10-20 01:35:48 +02:00
return e;
}
/*---------------------------------------------------------------------*/
/* assumes already zeroed -- insufficient for block 'reuse' perhaps */
2008-01-20 23:42:26 +01:00
DiskLoc Extent::init(const char *nsname, int _length, int _fileNo, int _offset) {
2007-10-20 01:35:48 +02:00
magic = 0x41424344;
2008-01-20 23:42:26 +01:00
myLoc.setOfs(_fileNo, _offset);
2007-10-30 10:50:14 +01:00
xnext.Null(); xprev.Null();
2007-10-20 01:35:48 +02:00
ns = nsname;
length = _length;
firstRecord.Null(); lastRecord.Null();
2007-10-30 16:35:17 +01:00
DiskLoc emptyLoc = myLoc;
emptyLoc.inc( (extentData-(char*)this) );
2007-10-20 01:35:48 +02:00
2007-10-30 16:35:17 +01:00
DeletedRecord *empty1 = (DeletedRecord *) extentData;
DeletedRecord *empty = (DeletedRecord *) getRecord(emptyLoc);
2007-10-20 01:35:48 +02:00
assert( empty == empty1 );
empty->lengthWithHeaders = _length - (extentData - (char *) this);
2007-10-30 16:35:17 +01:00
empty->extentOfs = myLoc.getOfs();
return emptyLoc;
2007-10-20 01:35:48 +02:00
}
2007-10-30 16:35:17 +01:00
/*
2007-10-20 01:35:48 +02:00
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 ) {
2007-10-30 16:35:17 +01:00
//
2007-10-20 01:35:48 +02:00
firstEmptyRegion.Null();
return 0;
}
2007-10-30 10:50:14 +01:00
DiskLoc nextEmpty = r->next.getNextEmpty(firstEmptyRegion);
2007-10-20 01:35:48 +02:00
r->lengthWithHeaders = newRecSize;
2007-10-30 10:50:14 +01:00
r->next.markAsFirstOrLastInExtent(this); // we're now last in the extent
2007-10-20 01:35:48 +02:00
if( !lastRecord.isNull() ) {
2007-10-30 10:50:14 +01:00
assert(getRecord(lastRecord)->next.lastInExtent()); // it was the last one
getRecord(lastRecord)->next.set(newRecordLoc); // until now
r->prev.set(lastRecord);
2007-10-20 01:35:48 +02:00
}
2007-10-30 10:50:14 +01:00
else {
r->prev.markAsFirstOrLastInExtent(this); // we are the first in the extent
assert( firstRecord.isNull() );
2007-10-20 01:35:48 +02:00
firstRecord = newRecordLoc;
2007-10-30 10:50:14 +01:00
}
lastRecord = newRecordLoc;
2007-10-20 01:35:48 +02:00
if( left < Record::HeaderSize + 32 ) {
firstEmptyRegion.Null();
}
else {
firstEmptyRegion.inc(newRecSize);
Record *empty = getRecord(firstEmptyRegion);
2007-10-30 10:50:14 +01:00
empty->next.set(nextEmpty); // not for empty records, unless in-use records, next and prev can be null.
empty->prev.Null();
2007-10-20 01:35:48 +02:00
empty->lengthWithHeaders = left;
}
return r;
}
2007-10-30 16:35:17 +01:00
*/
2007-10-20 01:35:48 +02:00
/*---------------------------------------------------------------------*/
2007-11-02 03:34:44 +01:00
auto_ptr<Cursor> DataFileMgr::findAll(const char *ns) {
2007-10-20 01:35:48 +02:00
DiskLoc loc;
2008-01-20 23:42:26 +01:00
bool found = nsindex(ns)->find(ns, loc);
2007-10-20 01:35:48 +02:00
if( !found ) {
cout << "info: findAll() namespace does not exist: " << ns << endl;
2007-11-02 03:34:44 +01:00
return auto_ptr<Cursor>(new BasicCursor(DiskLoc()));
2007-10-20 01:35:48 +02:00
}
2008-01-20 23:42:26 +01:00
Extent *e = getExtent(loc);
2008-01-25 01:41:01 +01:00
while( e->firstRecord.isNull() && !e->xnext.isNull() ) {
cout << " DFM::findAll(): extent empty, skipping ahead" << 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();
}
2007-11-02 03:34:44 +01:00
return auto_ptr<Cursor>(new BasicCursor( e->firstRecord ));
2007-10-20 01:35:48 +02:00
}
2008-03-09 16:05:25 +01:00
/* get a table scan cursor, but can be forward or reverse direction */
auto_ptr<Cursor> findTableScan(const char *ns, JSObj& order) {
Element el = order.findElement("$natural");
if( el.type() != Number || el.number() >= 0 )
return DataFileMgr::findAll(ns);
// "reverse natural order" // "reverse natural order"
NamespaceDetails *d = nsdetails(ns);
if( !d )
return auto_ptr<Cursor>(new BasicCursor(DiskLoc()));
Extent *e = d->lastExtent.ext();
while( e->lastRecord.isNull() && !e->xprev.isNull() ) {
cout << " findTableScan: extent empty, skipping ahead" << endl;
e = e->getPrevExtent();
}
return auto_ptr<Cursor>(new ReverseCursor( e->lastRecord ));
}
2007-11-05 01:17:42 +01:00
void aboutToDelete(const DiskLoc& dl);
2008-01-20 23:42:26 +01:00
/* 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.
*/
2007-11-22 03:44:57 +01:00
void IndexDetails::getKeysFromObject(JSObj& obj, set<JSObj>& keys) {
JSObj keyPattern = info.obj().getObjectField("key");
JSObjBuilder b;
JSObj key = obj.extractFields(keyPattern, b);
if( key.isEmpty() )
return;
Element f = key.firstElement();
if( f.type() != Array ) {
b.decouple();
key.iWillFree();
keys.insert(key);
return;
}
JSObj arr = f.embeddedObject();
// cout << arr.toString() << endl;
2007-11-22 03:44:57 +01:00
JSElemIter i(arr);
while( i.more() ) {
Element e = i.next();
if( e.eoo() ) break;
JSObjBuilder b;
b.appendAs(e, f.fieldName());
JSObj o = b.doneAndDecouple();
keys.insert(o);
}
}
2007-12-06 23:04:20 +01:00
int nUnindexes = 0;
2007-12-07 01:03:23 +01:00
void _unindexRecord(const char *ns, IndexDetails& id, JSObj& obj, const DiskLoc& dl) {
2007-11-22 03:44:57 +01:00
set<JSObj> keys;
id.getKeysFromObject(obj, keys);
for( set<JSObj>::iterator i=keys.begin(); i != keys.end(); i++ ) {
JSObj j = *i;
2008-03-13 20:39:09 +01:00
// cout << "UNINDEX: j:" << j.toString() << " head:" << id.head.toString() << dl.toString() << endl;
2007-12-02 17:33:59 +01:00
if( otherTraceLevel >= 5 ) {
cout << "_unindexRecord() " << obj.toString();
cout << "\n unindex:" << j.toString() << endl;
}
2007-12-06 23:04:20 +01:00
nUnindexes++;
2008-02-28 22:29:31 +01:00
bool ok = false;
try {
ok = id.head.btree()->unindex(id.head, ns, j, dl);
}
catch(AssertionException) {
cout << " caught assertion _unindexRecord " << id.indexNamespace() << '\n';
}
2007-12-06 23:04:20 +01:00
2007-12-02 17:33:59 +01:00
if( !ok ) {
2008-02-25 02:16:36 +01:00
cout << "Assertion failure: _unindex failed" << '\n';
cout << " obj:" << obj.toString() << '\n';
cout << " key:" << j.toString() << '\n';
cout << " dl:" << dl.toString() << endl;
2008-03-13 20:39:09 +01:00
sayDbContext();
2007-12-02 17:33:59 +01:00
}
2007-11-22 03:44:57 +01:00
}
2007-11-11 20:21:02 +01:00
}
2007-12-07 01:03:23 +01:00
void unindexRecord(const char *ns, NamespaceDetails *d, Record *todelete, const DiskLoc& dl) {
2007-11-11 20:21:02 +01:00
if( d->nIndexes == 0 ) return;
JSObj obj(todelete);
for( int i = 0; i < d->nIndexes; i++ ) {
2007-12-07 01:03:23 +01:00
_unindexRecord(ns, d->indexes[i], obj, dl);
2007-11-11 20:21:02 +01:00
}
}
2008-03-09 05:16:41 +01:00
void DataFileMgr::deleteRecord(const char *ns, Record *todelete, const DiskLoc& dl, bool cappedOK)
2007-10-30 16:35:17 +01:00
{
2008-03-09 05:16:41 +01:00
NamespaceDetails* d = nsdetails(ns);
if( d->capped && !cappedOK ) {
cout << "failing remove on a capped ns " << ns << endl;
return;
}
2007-11-05 01:17:42 +01:00
/* check if any cursors point to us. if so, advance them. */
aboutToDelete(dl);
2007-12-07 01:03:23 +01:00
unindexRecord(ns, d, todelete, dl);
2007-11-11 20:21:02 +01:00
2007-10-30 10:50:14 +01:00
/* remove ourself from the record next/prev chain */
2007-10-30 16:35:17 +01:00
{
if( todelete->prevOfs != DiskLoc::NullOfs )
todelete->getPrev(dl).rec()->nextOfs = todelete->nextOfs;
if( todelete->nextOfs != DiskLoc::NullOfs )
todelete->getNext(dl).rec()->prevOfs = todelete->prevOfs;
}
2007-10-30 10:50:14 +01:00
/* remove ourself from extent pointers */
2007-10-30 16:35:17 +01:00
{
Extent *e = todelete->myExtent(dl);
2008-01-20 23:42:26 +01:00
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);
}
2007-10-30 10:50:14 +01:00
}
2007-11-05 01:17:42 +01:00
/* add to the free list */
2007-10-30 16:35:17 +01:00
{
2007-11-06 03:43:49 +01:00
d->nrecords--;
d->datasize -= todelete->netLength();
2007-10-30 16:35:17 +01:00
d->addDeletedRec((DeletedRecord*)todelete, dl);
}
2007-10-30 10:50:14 +01:00
}
2007-11-22 03:44:57 +01:00
void setDifference(set<JSObj>& l, set<JSObj>& r, vector<JSObj*> &diff) {
set<JSObj>::iterator i = l.begin();
set<JSObj>::iterator j = r.begin();
while( 1 ) {
if( i == l.end() )
break;
while( j != r.end() && *j < *i )
j++;
2007-12-14 18:48:47 +01:00
if( j == r.end() || !i->woEqual(*j) ) {
const JSObj *jo = &*i;
diff.push_back( (JSObj *) jo );
2007-11-22 03:44:57 +01:00
}
i++;
}
}
2007-10-30 10:50:14 +01:00
/** Note: as written so far, if the object shrinks a lot, we don't free up space. */
void DataFileMgr::update(
const char *ns,
Record *toupdate, const DiskLoc& dl,
2008-03-17 01:59:19 +01:00
const char *buf, int len, stringstream& ss)
2007-10-30 10:50:14 +01:00
{
2008-03-09 05:16:41 +01:00
NamespaceDetails *d = nsdetails(ns);
2007-11-12 00:28:33 +01:00
if( toupdate->netLength() < len ) {
2008-03-09 05:16:41 +01:00
if( d && d->capped ) {
2008-03-17 01:59:19 +01:00
ss << " failing a growing update on a capped ns " << ns << endl;
2008-03-09 05:16:41 +01:00
return;
}
2007-10-30 10:50:14 +01:00
// doesn't fit.
2008-03-17 01:59:19 +01:00
if( client->profile )
ss << " moved ";
2007-10-30 10:50:14 +01:00
deleteRecord(ns, toupdate, dl);
insert(ns, buf, len);
return;
}
2007-11-12 00:28:33 +01:00
/* has any index keys changed? */
{
2008-01-20 23:42:26 +01:00
NamespaceDetails *d = nsdetails(ns);
2007-11-12 00:28:33 +01:00
if( d->nIndexes ) {
JSObj newObj(buf);
JSObj oldObj = dl.obj();
for( int i = 0; i < d->nIndexes; i++ ) {
IndexDetails& idx = d->indexes[i];
JSObj idxKey = idx.info.obj().getObjectField("key");
2007-11-22 03:44:57 +01:00
set<JSObj> oldkeys;
set<JSObj> newkeys;
idx.getKeysFromObject(oldObj, oldkeys);
idx.getKeysFromObject(newObj, newkeys);
vector<JSObj*> removed;
setDifference(oldkeys, newkeys, removed);
2007-12-06 23:04:20 +01:00
string idxns = idx.indexNamespace();
2008-02-28 22:29:31 +01:00
for( unsigned i = 0; i < removed.size(); i++ ) {
try {
idx.head.btree()->unindex(idx.head, idxns.c_str(), *removed[i], dl);
}
catch(AssertionException) {
2008-03-17 01:59:19 +01:00
ss << " exception update unindex ";
2008-02-28 22:29:31 +01:00
cout << " caught assertion update unindex " << idxns.c_str() << '\n';
}
2007-11-22 03:44:57 +01:00
}
vector<JSObj*> added;
setDifference(newkeys, oldkeys, added);
2007-12-06 23:04:20 +01:00
assert( !dl.isNull() );
2007-11-22 03:44:57 +01:00
for( unsigned i = 0; i < added.size(); i++ ) {
2008-02-28 22:29:31 +01:00
try {
2007-11-12 00:28:33 +01:00
idx.head.btree()->insert(
2008-02-28 22:29:31 +01:00
idx.head, idxns.c_str(),
dl, *added[i], false, idx, true);
2007-11-12 00:28:33 +01:00
}
2008-03-17 01:59:19 +01:00
catch(AssertionException) {
ss << " exception update index ";
2008-02-28 22:29:31 +01:00
cout << " caught assertion update index " << idxns.c_str() << '\n';
}
}
2008-03-17 01:59:19 +01:00
if( client->profile )
ss << "<br>" << added.size() << " key updates ";
2008-02-28 22:29:31 +01:00
2007-11-12 00:28:33 +01:00
}
}
}
2008-03-17 01:59:19 +01:00
// update in place
2007-10-30 10:50:14 +01:00
memcpy(toupdate->data, buf, len);
}
2007-11-06 03:43:49 +01:00
int followupExtentSize(int len, int lastExtentLen) {
int x = initialExtentSize(len);
int y = (int) (lastExtentLen < 4000000 ? lastExtentLen * 4.0 : lastExtentLen * 1.2);
int sz = y > x ? y : x;
sz = ((int)sz) & 0xffffff00;
assert( sz > len );
return sz;
}
2008-03-13 20:39:09 +01:00
int deb=0;
/* add keys to indexes for a new record */
void _indexRecord(IndexDetails& idx, JSObj& obj, DiskLoc newRecordLoc) {
2008-03-13 20:39:09 +01:00
2007-11-22 03:44:57 +01:00
set<JSObj> keys;
idx.getKeysFromObject(obj, keys);
for( set<JSObj>::iterator i=keys.begin(); i != keys.end(); i++ ) {
2007-12-06 23:04:20 +01:00
assert( !newRecordLoc.isNull() );
2008-02-28 22:29:31 +01:00
try {
2008-03-13 20:39:09 +01:00
// cout << "TEMP index: " << newRecordLoc.toString() << obj.toString() << endl;
2008-02-28 22:29:31 +01:00
idx.head.btree()->insert(idx.head, idx.indexNamespace().c_str(), newRecordLoc,
(JSObj&) *i, false, idx, true);
}
catch(AssertionException) {
cout << " caught assertion _indexRecord " << idx.indexNamespace() << '\n';
}
}
}
/* note there are faster ways to build an index in bulk, that can be
done eventually */
void addExistingToIndex(const char *ns, IndexDetails& idx) {
cout << "Adding all existing records for " << ns << " to new index" << endl;
int n = 0;
auto_ptr<Cursor> c = theDataFileMgr.findAll(ns);
while( c->ok() ) {
JSObj js = c->current();
_indexRecord(idx, js, c->currLoc());
c->advance();
n++;
};
cout << " indexing complete for " << n << " records" << endl;
}
/* add keys to indexes for a new record */
void indexRecord(NamespaceDetails *d, const void *buf, int len, DiskLoc newRecordLoc) {
JSObj obj((const char *)buf);
for( int i = 0; i < d->nIndexes; i++ ) {
_indexRecord(d->indexes[i], obj, newRecordLoc);
}
}
2007-11-09 03:42:50 +01:00
DiskLoc DataFileMgr::insert(const char *ns, const void *buf, int len, bool god) {
bool addIndex = false;
2008-01-20 23:42:26 +01:00
const char *sys = strstr(ns, "system.");
if( sys ) {
if( sys == ns ) {
cout << "ERROR: attempt to insert for invalid client 'system': " << ns << endl;
2007-11-09 03:42:50 +01:00
return DiskLoc();
}
2008-01-20 23:42:26 +01:00
if( strstr(ns, ".system.") ) {
if( strstr(ns, ".system.indexes") )
addIndex = true;
else if( !god ) {
cout << "ERROR: attempt to insert in system namespace " << ns << endl;
return DiskLoc();
}
}
2007-11-03 02:30:40 +01:00
}
2008-01-20 23:42:26 +01:00
NamespaceDetails *d = nsdetails(ns);
2007-10-30 16:35:17 +01:00
if( d == 0 ) {
2007-11-03 02:30:40 +01:00
newNamespace(ns);
2008-01-20 23:42:26 +01:00
client->newestFile()->newExtent(ns, initialExtentSize(len));
d = nsdetails(ns);
2007-10-20 01:35:48 +02:00
}
2007-10-30 16:35:17 +01:00
NamespaceDetails *tableToIndex = 0;
2007-11-09 03:42:50 +01:00
string indexFullNS;
const char *tabletoidxns = 0;
2007-11-09 03:42:50 +01:00
if( addIndex ) {
JSObj io((const char *) buf);
const char *name = io.getStringField("name"); // name of the index
tabletoidxns = io.getStringField("ns"); // table it indexes
2007-11-09 03:42:50 +01:00
JSObj key = io.getObjectField("key");
if( name == 0 || *name == 0 || tabletoidxns == 0 || key.isEmpty() || key.objsize() > 2048 ) {
2007-11-20 04:24:17 +01:00
cout << "user warning: bad add index attempt name:" << (name?name:"") << " ns:" <<
(tabletoidxns?tabletoidxns:"") << endl;
return DiskLoc();
}
2008-01-20 23:42:26 +01:00
tableToIndex = nsdetails(tabletoidxns);
if( tableToIndex == 0 ) {
cout << "ERROR: bad add index attempt, no such table(ns):" << tabletoidxns << endl;
2007-11-09 03:42:50 +01:00
return DiskLoc();
}
if( tableToIndex->nIndexes >= MaxIndexes ) {
cout << "ERROR: bad add index attempt, too many indexes for:" << tabletoidxns << endl;
2007-11-09 03:42:50 +01:00
return DiskLoc();
}
if( tableToIndex->findIndexByName(name) >= 0 ) {
2008-02-24 17:29:42 +01:00
//cout << "INFO: index:" << name << " already exists for:" << tabletoidxns << endl;
2007-11-09 03:42:50 +01:00
return DiskLoc();
}
indexFullNS = tabletoidxns;
2007-11-09 03:42:50 +01:00
indexFullNS += ".$";
indexFullNS += name; // client.table.$index -- note this doesn't contain jsobjs, it contains BtreeBuckets.
}
2007-10-30 16:35:17 +01:00
DiskLoc extentLoc;
int lenWHdr = len + Record::HeaderSize;
2008-03-09 05:16:41 +01:00
DiskLoc loc = d->alloc(ns, lenWHdr, extentLoc);
2007-10-30 16:35:17 +01:00
if( loc.isNull() ) {
// out of space
2008-03-09 05:16:41 +01:00
if( d->capped == 0 ) { // size capped doesn't grow
cout << "allocating new extent for " << ns << endl;
client->newestFile()->newExtent(ns, followupExtentSize(len, d->lastExtentSize));
loc = d->alloc(ns, lenWHdr, extentLoc);
}
2007-10-30 16:35:17 +01:00
if( loc.isNull() ) {
2008-03-09 05:16:41 +01:00
cout << "out of space in datafile. capped:" << d->capped << endl;
assert(d->capped);
2007-11-09 03:42:50 +01:00
return DiskLoc();
2007-10-30 16:35:17 +01:00
}
}
Record *r = loc.rec();
assert( r->lengthWithHeaders >= lenWHdr );
2007-10-20 01:35:48 +02:00
memcpy(r->data, buf, len);
2007-10-30 16:35:17 +01:00
Extent *e = r->myExtent(loc);
if( e->lastRecord.isNull() ) {
e->firstRecord = e->lastRecord = loc;
r->prevOfs = r->nextOfs = DiskLoc::NullOfs;
}
else {
Record *oldlast = e->lastRecord.rec();
r->prevOfs = e->lastRecord.getOfs();
r->nextOfs = DiskLoc::NullOfs;
2007-10-30 18:43:44 +01:00
oldlast->nextOfs = loc.getOfs();
2007-10-30 16:35:17 +01:00
e->lastRecord = loc;
}
2007-11-06 03:43:49 +01:00
d->nrecords++;
d->datasize += r->netLength();
2007-11-09 03:42:50 +01:00
if( tableToIndex ) {
IndexDetails& idxinfo = tableToIndex->indexes[tableToIndex->nIndexes];
idxinfo.info = loc;
idxinfo.head = BtreeBucket::addHead(indexFullNS.c_str());
tableToIndex->nIndexes++;
2007-11-09 03:42:50 +01:00
/* todo: index existing records here */
addExistingToIndex(tabletoidxns, idxinfo);
2007-11-09 03:42:50 +01:00
}
/* add this record to our indexes */
if( d->nIndexes )
indexRecord(d, buf, len, loc);
2008-01-25 01:41:01 +01:00
// cout << " inserted at loc:" << hex << loc.getOfs() << " lenwhdr:" << hex << lenWHdr << dec << ' ' << ns << endl;
2007-11-09 03:42:50 +01:00
return loc;
2007-10-20 01:35:48 +02:00
}
2007-11-27 21:30:51 +01:00
void DataFileMgr::init(const char *dir) {
2008-01-20 23:42:26 +01:00
/* string path = dir;
2007-11-27 21:30:51 +01:00
path += "temp.dat";
temp.open(path.c_str(), 64 * 1024 * 1024);
2008-01-20 23:42:26 +01:00
*/
2007-10-20 01:35:48 +02:00
}
void pdfileInit() {
2008-01-20 23:42:26 +01:00
// namespaceIndex.init(dbpath);
2007-11-27 21:30:51 +01:00
theDataFileMgr.init(dbpath);
2007-10-20 01:35:48 +02:00
}