Chinaunix首页 | 论坛 | 博客
  • 博客访问: 808990
  • 博文数量: 50
  • 博客积分: 757
  • 博客等级: 上士
  • 技术积分: 1913
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-29 14:29
个人简介

DBA

文章分类

全部博文(50)

文章存档

2015年(3)

2014年(2)

2013年(14)

2012年(19)

2011年(12)

分类: NOSQL

2013-03-29 17:39:29

    前一段时间使用repair命令修复线上的数据库,发现数据库中碎片巨大,占用200多G的数据在repair之后只有50多G,然后就研究了一下Mongodb是如何利用已经删除了的空间的。
    分析下源码(源码版本2.2.2,新版本可能随时更新):
    Mongodb在执行删除(文档)操作时,并不会进行物理删除,而是将他们放入每个命名空间维护的删除列表里。

  1. //pdfile.cpp delete()
  2.        /* add to the free list */
  3.         {
  4.                 ....
  5.                 d->addDeletedRec((DeletedRecord*)todelete, dl);
  6.             }
  7.         }




  8. //namespace_detail.cpp addDeletedRec(..)
  9.        ....
  10.        else {
  11.             int b = bucket(d->lengthWithHeaders());
  12.             DiskLoc& list = deletedList[b];
  13.             DiskLoc oldHead = list;
  14.             getDur().writingDiskLoc(list) = dloc;
  15.             d->nextDeleted() = oldHead;
  16.         }

上面的deletedList就是维护的删除数据列表。

点击(此处)折叠或打开

  1. //namespace_detail.h
  2.  /* deleted lists -- linked lists of deleted records -- are placed in 'buckets' of various sizes so you can look for a deleterecord about the right size.
  3.  */
  4.     const int Buckets = 19;
  5.     const int MaxBucket = 18;
  6.     DiskLoc deletedList[Buckets];
  7.     int bucketSizes[] = { 32, 64, 128, 256, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, 0x10000, 0x20000, 0x40000, 0x80000, 0x100000, 0x200000,0x400000, 0x800000};
       可以看到,deleteList数组实际保存的是DiskLoc,长度19,跟bucketSizes[]的长度一致。DiskLoc就是文档在磁盘上的位置,并且有后指针,可以指向下一个DiskLoc,从而组成一个列表。deleteList中实际就保存了19个列表,每个列表就是已经被删除文档地址,且这些文档都在bucketSizes所规定的的范围内。描述不太清楚,上图吧:




    插入文档时,Mongodb会先计算需要开辟多大的空间,然后去找deleteList中的位置,如果deleteList中不满足,那么才会去开辟新的空间。


点击(此处)折叠或打开

  1. //pdfile.cpp
  2. int lenWHdr = d->getRecordAllocationSize( len + Record::HeaderSize );
  3. DiskLoc loc;
  4.         if( addID || tableToIndex || d->isCapped() ) {
  5.             // if need id, we don't do the early indexing. this is not the common case so that is sort of ok
  6.             earlyIndex = false;
  7.             loc = allocateSpaceForANewRecord(ns, d, lenWHdr, god);
  8.         }
  9.         else {
  10.             loc = d->allocWillBeAt(ns, lenWHdr);
  11.             if( loc.isNull() ) {
  12.                 // need to get a new extent so we have to do the true alloc now (not common case)
  13.                 earlyIndex = false;
  14.                 loc = allocateSpaceForANewRecord(ns, d, lenWHdr, god);
  15.             }
  16.         }

我们暂时不讨论cappedCollection(固定大小的集合),只看常规集合


点击(此处)折叠或打开

  1. /* predetermine location of the next alloc without actually doing it.
  2.         if cannot predetermine returns null (so still call alloc() then)
  3.     */
  4.     DiskLoc NamespaceDetails::allocWillBeAt(const char *ns, int lenToAlloc) {
  5.         if ( ! isCapped() ) {
  6.             lenToAlloc = (lenToAlloc + 3) & 0xfffffffc;
  7.             return __stdAlloc(lenToAlloc, true);
  8.         }
  9.         return DiskLoc();
  10.     }

  11.  /* for non-capped collections.
  12.        @param peekOnly just look up where and don't reserve
  13.        returned item is out of the deleted list upon return
  14.     */
  15.     DiskLoc NamespaceDetails::__stdAlloc(int len, bool peekOnly) {
  16.         DiskLoc *prev;
  17.         DiskLoc *bestprev = 0;
  18.         DiskLoc bestmatch;
  19.         int bestmatchlen = 0x7fffffff;
  20.         int b = bucket(len);
  21.         DiskLoc cur = deletedList[b];
  22.         prev = &deletedList[b];
  23.         int extra = 5; // look for a better fit, a little.
  24.         int chain = 0;
  25.         while ( 1 ) {
  26.             {
  27.                 int a = cur.a();
  28.                 if ( a < -1 || a >= 100000 ) {
  29.                     problem() << "~~ Assertion - cur out of range in _alloc() " <<

  30. cur.toString() <<
  31.                               " a:" << a << " b:" << b << " chain:" << chain << '\n';
  32.                     logContext();
  33.                     if ( cur == *prev )
  34.                         prev->Null();
  35.                     cur.Null();
  36.                 }
  37.             }
  38.             if ( cur.isNull() ) {
  39.                 // move to next bucket. if we were doing "extra", just break
  40.                 if ( bestmatchlen < 0x7fffffff )
  41.                     break;
  42.                 b++;
  43.                 if ( b > MaxBucket ) {
  44.                     // out of space. alloc a new extent.
  45.                     return DiskLoc();
  46.                 }
  47.                 cur = deletedList[b];
  48.                 prev = &deletedList[b];
  49.                 continue;
  50.             }
  51.             DeletedRecord *r = cur.drec();
  52.             if ( r->lengthWithHeaders() >= len &&
  53.                  r->lengthWithHeaders() < bestmatchlen ) {
  54.                 bestmatchlen = r->lengthWithHeaders();
  55.                 bestmatch = cur;
  56.                 bestprev = prev;
  57.             }
  58.             if ( bestmatchlen < 0x7fffffff && --extra <= 0 )
  59.                 break;
  60.             if ( ++chain > 30 && b < MaxBucket ) {
  61.                 // too slow, force move to next bucket to grab a big chunk
  62.                 //b++;
  63.                 chain = 0;
  64.                 cur.Null();
  65.             }
  66.             else {
  67.                 /*this defensive check only made sense for the mmap storage engine:
  68.                   if ( r->nextDeleted.getOfs() == 0 ) {
  69.                     problem() << "~~ Assertion - bad nextDeleted " << r->nextDeleted.toString()

  70. <<
  71.                     " b:" << b << " chain:" << chain << ", fixing.\n";
  72.                     r->nextDeleted.Null();
  73.                 }*/
  74.                 cur = r->nextDeleted();
  75.                 prev = &r->nextDeleted();
  76.             }
  77.         }

  78.         /* unlink ourself from the deleted list */
  79.         if( !peekOnly ) {
  80.             DeletedRecord *bmr = bestmatch.drec();
  81.             *getDur().writing(bestprev) = bmr->nextDeleted();
  82.             bmr->nextDeleted().writing().setInvalid(); // defensive.
  83.             verify(bmr->extentOfs() < bestmatch.getOfs());
  84.         }

  85.         return bestmatch;
  86.     }

上面这段就是Mongodb在deleteList中寻找合适插入位置的算法.


  1. int b = bucket(len);
  2. DiskLoc cur = deletedList[b];

      这是最初始的寻找位置的算法,解释一下,bucket函数就是寻找跟len(插入文档的大小)最接近的bucketSize,比如说len=68,那么应该在64-128这个范围内,在deleteList中应该是第3个列表,那么b=2,cur就是返回的第三个列表的起始位置。如果找到了,那么就是用列表中的值,如果找不到,就继续往下一个列表中寻找。找到之后,将找到的位置从deleteList中删除,返回。

     如果所有的列表都遍历完成还是找不到,那么mongodb就会去硬盘上真的开辟一段空间。我们上面说过Mongodb会先计算需要开辟的空间大小,有两种方式
     
     

  1. //namespace_detail.cpp
  2. int NamespaceDetails::getRecordAllocationSize( int minRecordSize ) {
  3.         if ( _paddingFactor == 0 ) {
  4.             warning() << "implicit updgrade of paddingFactor of very old collection" << endl;
  5.             setPaddingFactor(1.0);
  6.         }
  7.         verify( _paddingFactor >= 1 );


  8.         if ( isUserFlagSet( Flag_UsePowerOf2Sizes ) ) {
  9.             int allocationSize = bucketSizes[ bucket( minRecordSize ) ];
  10.             if ( allocationSize < minRecordSize ) {
  11.                 // if we get here, it means we're allocating more than 8mb
  12.                 // the highest bucket is 8mb, so the above code will never return more than 8mb for allocationSize
  13.                 // if this happens, we are going to round up to the nearest megabyte
  14.                 fassert( 16439, bucket( minRecordSize ) == MaxBucket );
  15.                 allocationSize = 1 + ( minRecordSize | ( ( 1 << 20 ) - 1 ) );
  16.             }
  17.             return allocationSize;
  18.         }

  19.         return static_cast<int>(minRecordSize * _paddingFactor);
  20.     }

          第一种padding方式,Mongodb会计算一个_paddingFactor,开辟doclen*(1+paddingFactor)大小,以防止update引起的长度变大,需要移动数据。第二种方式usePowerOf2Size,Mongodb为文档开辟的空间总是2的倍数,如之前我们说过的,文档大小68字节,那么就会开辟128字节,bucket函数就是从bucketSize数组中寻找最接近文档长度的那个2的次方值。

点击(此处)折叠或打开

  1. //namespace_detail.cpp
  2.  int bucketSizes[] = {
  3.         32, 64, 128, 256, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000,
  4.         0x8000, 0x10000, 0x20000, 0x40000, 0x80000, 0x100000, 0x200000,
  5.         0x400000, 0x800000
  6.     };

     这两种方式各有优劣,padding方式会为文档开辟更合适的大小,而且paddingFactor比较小,一般为0.01-0.09,不会浪费空间,文档更新小的话也不会移动文档位置。但是当大量更新和删除的时候,这种方式重复利用空间的能力就比较小,因为在deleteList中,不太容易找到合适的已删除文档,而且一旦更新就会又移动位置,磁盘重复利用率低,增长快,碎片多。相比之下,usePowerOf2Size方式,Mongodb每次都会开辟比文档大的多的空间,使用空间变多,但是更新和删除的容错率就会比较高,因为在deleteList列表中更容易找到合适的删除文档(每个列表中的文档大小都是相同的固定的),更新的时候也不会大量移动位置,磁盘重复利用率高,增长慢。


所以,在读操作较多的应用中,可以使用padding方式,也是mongodb默认的方式,在写操作较多的应用中,可以使用usePowerOf2Size方式。
usePowerOf2Size是在创建集合的时候指定的
db.runCommand( {collMod: "products", usePowerOf2Sizes : true }) //enable
db.runCommand( {collMod: "products", usePowerOf2Sizes : false })//disable
usePowerOf2Size只影响新插入和更新引起的分配空间大小,对之前的文档不起作用。




阅读(5907) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~