现在的位置: 首页 > 综合 > 正文

Mongodb源码分析–Replication之主从模式–Slave

2019年05月04日 ⁄ 综合 ⁄ 共 30894字 ⁄ 字号 评论关闭

Mongodb源码分析--Replication之主从模式--Slave 收藏 

    在上文中介绍了主从(master-slave)模式下的一些基本概念及master的执行流程。今天接着介绍一下从(slave)结点是如何发起请求,并通过请求获取的oplog信息来构造本地数据的。

    不过开始今天的正文前,需要介绍一下mongodb在slave结点上进行数据同步时的一个大致流程:
    
    1. 当一个从结点启动时,它会对主结点进行一次彻底同步。从结点将复制主结点中的每一个文档(操作量大且耗时)。当初始化的同步完成后,从结点将查询主结点的oplog并且执行这些操作来保持数据的更新。

    2. 如从结点上的操作落后主结点太多, 从结点处于out-of-sync状态。该状态表示从结点不能通过执行同步操作使本地数据赶上主结点数据,因为主结点中的每一个操作都太新了。造成这种情 况的原因包括结点宕机或者忙于处理读请求(尽管mongodb支持读操作的负载均衡)。如果同步的时间(戳)超出了oplog(滚动)的时间(戳),它将 重新开始一次彻底的同步(通过执行resync操作)。

    3. 当一个从结点处于out-of- sync状态时,复制将被挂起,从结点需要从主结点进行重新同步。resync流程可以手动执行,即在从结点的admin数据库上运行命令 {“resync”:1}, 或者自动执行:在启动从结点时使用 --autoresync选项。因为resync是非常操作量大且耗时,最好通过设置一个足够大的oplogSize来避免resync(默认的 oplog大小是空闲磁盘大小的5%)。

    为了验证上面的流程,下面我们就来看一下slave的执行流程。这里为了便于调试,对环境配置如下:

    1.master db ip-> 10.0.4.210
      启动命令行:d:/mongod>bin>mongod --dbpath=d:/mongodb/db --master --oplogSize 64

    2.在vs中做如下设置(mongod项目属性窗口):
      --slave --source 10.0.4.210:27017 --only test --slavedelay 100

 

    因为mongod的主入口函数在db.cpp中,我们可以通过下面方法的调用流程找到slave的蛛丝马迹:

  1. db.cpp -->  
  2.      main( int  argc,  char *  argv[])  // 加载启动参数如--slave,--slavedelay并绑定到replSettings对象  
  3.           void  initAndListen( int  listenPort,  const   char   * appserverLoc  =  NULL)  
  4.              void  _initAndListen( int  listenPort,  const   char   * appserverLoc  =  NULL)  
  5.                  listen( int  port)  

    当执行到listen()方法后(如下):

  1. void  listen( int  port) {  
  2.          // testTheDb();  
  3.         log()  <<   " waiting for connections on port  "   <<  port  <<  endl;  
  4.         OurListener l(cmdLine.bind_ip, port);  
  5.         l.setAsTimeTracker();  
  6.          // 启动复制  
  7.         startReplication();  
  8.          if  (  ! noHttpInterface )  
  9.             boost::thread web( boost::bind( & webServerThread,  new  RestAdminAccess()  /*  takes ownership  */ ));  
  10.         .....  
  11.     }  

   mongodb会紧跟着执行repl.cpp文件中的startReplication()方法,如下:


 

  1.     // 绑定函数,oplog.cpp ->_logOpOld(), 用于处理master-slave类型的oplog操作  
  2.     oldRepl();  
  3.      /*  this was just to see if anything locks for longer than it should -- we need to be careful 
  4.        not to be locked when trying to connect() or query() the other side. 
  5.         */  
  6.      // boost::thread tempt(tempThread);  
  7.      // 当设置参数不正确时(非slave,master且不是replPair)  
  8.      if (  ! replSettings.slave  &&   ! replSettings.master  &&   ! replPair )  
  9.          return ;  
  10.     {  
  11.         dblock lk;  
  12.         cc().getAuthenticationInfo() -> authorize( " admin " );  
  13.         pairSync -> init();  
  14.     }  
  15.      // 如果是slave,则开启相关访问(master server)线程  
  16.      if  ( replSettings.slave  ||  replPair ) {  
  17.          if  ( replSettings.slave ) {  
  18.             assert( replSettings.slave  ==  SimpleSlave );  
  19.             log( 1 )  <<   " slave=true "   <<  endl;  
  20.         }  
  21.          else  
  22.             replSettings.slave  =  ReplPairSlave;  
  23.          // 构造并启动线程方法replSlaveThread  
  24.         boost::thread repl_thread(replSlaveThread);  
  25.     }  
  26.      // 如果是master,则构造并启动线程方法replMasterThread  
  27.      if  ( replSettings.master  ||  replPair ) {  
  28.          if  ( replSettings.master )  
  29.             log( 1 )  <<   " master=true "   <<  endl;  
  30.         replSettings.master  =   true ;  
  31.         createOplog();//构造oplog集合“local.oplog.$main”  
  32.         boost::thread t(replMasterThread);  
  33.     }  
  34.      //  don't allow writes until we've set up from log  
  35.      while ( replSettings.fastsync )  
  36.         sleepmillis(  50  );  
  37. }  

 

    上面方法在完成必要的参数分析检查之后,就会根据slave的配置信息来构造启动线程方法replSlaveThread,如下:

  

  1. // repl.cpp  
  2.   void  replSlaveThread() {  
  3.      sleepsecs( 1 );  
  4.      Client::initThread( " replslave " );  
  5.      cc().iAmSyncThread();  
  6.      {  
  7.          dblock lk;  
  8.           // 获取认证信息(mongodb支持使用安全认证不管哪种replicate方式,  
  9.           // 只要在master/slave中创建一个能为各个database认识的用户名/密码即可)  
  10.          cc().getAuthenticationInfo() -> authorize( " admin " );  
  11.          ......  
  12.      }  
  13.       while  (  1  ) {  
  14.           try  {  
  15.               // repl主函数  
  16.              replMain();  
  17.               if  ( debug_stop_repl )  
  18.                   break ;  
  19.              sleepsecs( 5 ); // 休眠5秒  
  20.          }  
  21.           catch  ( AssertionException &  ) {  
  22.              ReplInfo r( " Assertion in replSlaveThread(): sleeping 5 minutes before retry " );  
  23.              problem()  <<   " Assertion in replSlaveThread(): sleeping 5 minutes before retry "   <<  endl;  
  24.              sleepsecs( 300 );  
  25.          }  
  26.      }  
  27.  }  

 

    上面方法中有mongodb进行认证的逻辑,之后就会用一个while(1)来循环执行(注:每5秒执行一次)replMain()方法,如下:

  1. // repl.cpp  
  2.    void  replMain() {  
  3.       ReplSource::SourceVector sources;  
  4.        while  (  1  ) {  
  5.            int  s  =   0 ;  
  6.           {  
  7.               dblock lk;  
  8.                // 复制失败  
  9.                if  ( replAllDead ) { // 该标识符会在同步出现异常如(out of sync)时为true  
  10.                    // autoresync:自动地重新执行完整的同步,如果这个从结点脱离了与主结点的同步。  
  11.                    if  (  ! replSettings.autoresync  ||   ! ReplSource::throttledForceResyncDead(  " auto "  ) )  
  12.                        break ;  
  13.               }  
  14.                //  i.e., there is only one sync thread running.  
  15.                //  we will want to change/fix this.  
  16.               assert( syncing  ==   0  );  
  17.               syncing ++ ;  
  18.           }  
  19.            try  {  
  20.                int  nApplied  =   0 ;  
  21.                // repl主函数  
  22.               s  =  _replMain(sources, nApplied);  
  23.                if ( s  ==   1  ) {  
  24.                    if ( nApplied  ==   0  ) s  =   2 ;  
  25.                    else   if ( nApplied  >   100  ) {  
  26.                        //  sleep very little - just enought that we aren't truly hammering master  
  27.                       sleepmillis( 75 );  
  28.                       s  =   0 ;  
  29.                   }  
  30.               }  
  31.           }  
  32.            catch  (...) {  
  33.                out ()  <<   " caught exception in _replMain "   <<  endl;  
  34.               s  =   4 ;  
  35.           }  
  36.           ......  
  37.    }  

     上面代码又是一个while(1)循环,它会判断当前slave是否处于“out of sync”状态,如果是,但未开启autoresync时,则复制将被挂起。否则会执行_replMain方法来进行同步,如下:

      

  1. // repl.cpp  
  2.       int  _replMain(ReplSource::SourceVector &  sources,  int &  nApplied) {  
  3.         {  
  4.             ReplInfo r( " replMain load sources " );  
  5.             dblock lk;  
  6.             ReplSource::loadAll(sources); // 绑定相应的master sources,以便后面遍历同步  
  7.              /* fastsync: 从主结点的快照中启动一个从结点。与完整的同步相比, 
  8.             这个选项允许一个从结点更快地启动,如果它的数据目录已经使用主结点的快照进行初始化。 */  
  9.             replSettings.fastsync  =   false ;  //  初始重置时需要该参数  
  10.         }  
  11.         .....  
  12.        
  13.          int  sleepAdvice  =   1 ;  
  14.          for  ( ReplSource::SourceVector::iterator i  =  sources.begin(); i  !=  sources.end(); i ++  ) {  
  15.             ReplSource  * s  =  i -> get ();  
  16.              int  res  =   - 1 ;  
  17.              try  {  
  18.                 res  =  s -> sync(nApplied);  
  19.                  // 是否有其它要同步的数据库  
  20.                  bool  moreToSync  =  s -> haveMoreDbsToSync();  
  21.                  if ( res  <   0  ) {  
  22.                     sleepAdvice  =   3 ;  
  23.                 }  
  24.                  else   if ( moreToSync ) {  
  25.                     sleepAdvice  =   0 ;  
  26.                 }  
  27.                  else   if  ( s -> sleepAdvice() ) {  
  28.                     sleepAdvice  =  s -> sleepAdvice();  
  29.                 }  
  30.                  else  
  31.                     sleepAdvice  =  res;  
  32.                  if  ( res  >=   0   &&   ! moreToSync  /* && !s->syncedTo.isNull() */  ) {  
  33.                     pairSync -> setInitialSyncCompletedLocking();  
  34.                 }  
  35.             }  
  36.             ......  
  37.         }  
  38.          return  sleepAdvice;  
  39.     }  

 

    上面的_replMain()方法首先会从“local.sources”数据集中获取主(master)节点的信息。这里解释一下,mongod从结 点在启动时会将启动参数(--source)中的信息保存到"local.sources"数据集中,并通过此函数(loadAll())中加载到一个集 合对象中。这里我们看一下其加载代码,如下:

  1. /*  slave: pull some data from the master's oplog 
  2.        note: not yet in db mutex at this point. 
  3.        @return -1 error 
  4.                0 ok, don't sleep 
  5.                1 ok, sleep 
  6.      */  
  7.      // repl.cpp  
  8.      void  ReplSource::loadAll(SourceVector  & v) {  
  9.         Client::Context ctx( " local.sources " );  
  10.         SourceVector old  =  v;  
  11.         v.clear();  
  12.         ......  
  13.          // 遍历local.sources,并将其中的replsource绑定到SourceVector中  
  14.         shared_ptr < Cursor >  c  =  findTableScan( " local.sources " , BSONObj());  
  15.          while  ( c -> ok() ) {  
  16.             ReplSource tmp(c -> current());  
  17.              if  ( replPair  &&  tmp.hostName  ==  replPair -> remote  &&  tmp.sourceName()  ==   " main "  ) {  
  18.                 gotPairWith  =   true ;  
  19.                 tmp.paired  =   true ;  
  20.                  if  ( replacePeer ) {  
  21.                      //  peer was replaced -- start back at the beginning.  
  22.                     tmp.syncedTo  =  OpTime();  
  23.                     tmp.replacing  =   true ;  
  24.                 }  
  25.             }  
  26.              if  ( (  ! replPair  &&  tmp.syncedTo.isNull() )  ||  
  27.                      ( replPair  &&  replSettings.fastsync ) ) {  
  28.                 DBDirectClient c;  
  29.                  // 主服务器进程创建的local.oplog.$main数据集,即"transaction log",以记录从服务器需要的操作队列信息。  
  30.                  // 这里用于获取同步时的时间戳"syncedTo"  
  31.                  if  ( c.exists(  " local.oplog.$main "  ) ) {  
  32.                     BSONObj op  =  c.findOne(  " local.oplog.$main " , QUERY(  " op "   <<  NE  <<   " n "  ).sort( BSON(  " $natural "   <<   - 1  ) ) );  
  33.                      if  (  ! op.isEmpty() ) {  
  34.                         tmp.syncedTo  =  op[  " ts "  ].date();  
  35.                         tmp._lastSavedLocalTs  =  op[  " ts "  ].date();  
  36.                     }  
  37.                 }  
  38.             }  
  39.              // 将source数据绑定到v中以引用方式(&v)返回给上一级函数调用  
  40.             addSourceToList(v, tmp, old);  
  41.             c -> advance();  
  42.         }  
  43.         ......  
  44.     }  

    完成了source的加载之后,就可以开始对source进行同步了,即如下代码:

 

  1. int  ReplSource::sync( int &  nApplied) {  
  2.         _sleepAdviceTime  =   0 ;  
  3.         ReplInfo r( " sync " );  
  4.          if  (  ! cmdLine.quiet ) {  
  5.             Nullstream &  l  =  log();  
  6.             l  <<   " repl: from  " ;  
  7.              if ( sourceName()  !=   " main "  ) {  
  8.                 l  <<   " source: "   <<  sourceName()  <<   '   ' ;  
  9.             }  
  10.             l  <<   " host: "   <<  hostName  <<  endl;  
  11.         }  
  12.         nClonedThisPass  =   0 ;  
  13.          //  对于localhost这类本机地址,则不能同步  
  14.          // FIXME Handle cases where this db isn't on default port, or default port is spec'd in hostName.  
  15.          if  ( ( string ( " localhost " )  ==  hostName  ||   string ( " 127.0.0.1 " )  ==  hostName)  &&  cmdLine.port  ==  CmdLine::DefaultDBPort ) {  
  16.             log()  <<   " repl:   can't sync from self (localhost). sources configuration may be wrong. "   <<  endl;  
  17.             sleepsecs( 5 );  
  18.              return   - 1 ;  
  19.         }  
  20.          // oplogReader链接时出现异常  
  21.          if  (  ! oplogReader.connect(hostName) ) {  
  22.             log( 4 )  <<   " repl:  can't connect to sync source "   <<  endl;  
  23.              if  ( replPair  &&  paired ) {  
  24.                 assert( startsWith(hostName.c_str(), replPair -> remoteHost.c_str()) );  
  25.                 replPair -> arbitrate(); // paired模式下同级结点进行仲裁  
  26.             }  
  27.              return   - 1 ;  
  28.         }  
  29.          if  ( paired ) {  
  30.              int  remote  =  replPair -> negotiate(oplogReader.conn(),  " direct " );  
  31.              int  nMasters  =  ( remote  ==  ReplPair::State_Master )  +  ( replPair -> state  ==  ReplPair::State_Master );  
  32.              // 主库不为1时,则异常  
  33.              if  ( getInitialSyncCompleted()  &&  nMasters  !=   1  ) {  
  34.                 log()  <<  ( nMasters  ==   0   ?   " no master "  :  " two masters "  )  <<   " , deferring oplog pull "   <<  endl;  
  35.                  return   1 ;  
  36.             }  
  37.         }  
  38.         ......  
  39.          
  40.          return  sync_pullOpLog(nApplied); // 根据oplog日志进行同步  
  41.     }  

 

    上面方法先进行一些异常判断,比如source为localhost地址,以及无法链接(oplogReader.connect)等情况。之后,调用sync_pullOpLog方法,从master上获取oplog来同步数据信息,如下:

 

  1. // repl.cpp 获取主库的oplog数据  
  2.      int  ReplSource::sync_pullOpLog( int &  nApplied) {  
  3.          int  okResultCode  =   1 ;  
  4.          // 获取主库中oplog的名空间信息  
  5.          string  ns  =   string ( " local.oplog.$ " )  +  sourceName();  
  6.         log( 2 )  <<   " repl: sync_pullOpLog  "   <<  ns  <<   "  syncedTo: "   <<  syncedTo.toStringLong()  <<   ' /n ' ;  
  7.          bool  tailing  =   true ;  
  8.         oplogReader.tailCheck();  
  9.          if  ( replPair  &&  replPair -> state  ==  ReplPair::State_Master ) {  
  10.             dblock lk;  
  11.             idTracker.reset();  
  12.         }  
  13.         OpTime localLogTail  =  _lastSavedLocalTs;  
  14.          // 是否初始化  
  15.          bool  initial  =  syncedTo.isNull();  
  16.          // 无游标支持或要初始化时  
  17.          if  (  ! oplogReader.haveCursor()  ||  initial ) {  
  18.              if  ( initial ) {  
  19.                  // 显示数据库信息之前,获取最新(last)的 oplog日志时间戳.  
  20.                 syncToTailOfRemoteLog();  
  21.                 BSONObj info;  
  22.                  bool  ok  =  oplogReader.conn() -> runCommand(  " admin " , BSON(  " listDatabases "   <<   1  ), info );  
  23.                 massert(  10389  ,   " Unable to get database list " , ok );  
  24.                 BSONObjIterator i( info.getField(  " databases "  ).embeddedObject() );  
  25.                  while ( i.moreWithEOO() ) {  
  26.                     BSONElement e  =  i.next();  
  27.                      if  ( e.eoo() )  
  28.                          break ;  
  29.                      string  name  =  e.embeddedObject().getField(  " name "  ).valuestr();  
  30.                      if  (  ! e.embeddedObject().getBoolField(  " empty "  ) ) {  
  31.                          if  ( name  !=   " local "  ) {  
  32.                              if  ( only.empty()  ||  only  ==  name ) {  
  33.                                 log(  2  )  <<   " adding to 'addDbNextPass':  "   <<  name  <<  endl;  
  34.                                 addDbNextPass.insert( name );  
  35.                             }  
  36.                         }  
  37.                     }  
  38.                 }  
  39.                 dblock lk;  
  40.                 save();  
  41.             }  
  42.              // 本次同步的日志时间戳(gte:大于或等于)  
  43.             BSONObjBuilder q;  
  44.             q.appendDate( " $gte " , syncedTo.asDate());  
  45.             BSONObjBuilder query;  
  46.             query.append( " ts " , q.done());  
  47.              if  (  ! only.empty() ) {  
  48.                  //  note we may here skip a LOT of data table scanning, a lot of work for the master.  
  49.                 query.appendRegex( " ns " ,  string ( " ^ " )  +  only);  //  maybe append "//." here?  
  50.             }  
  51.             BSONObj queryObj  =  query.done();  
  52.              //  e.g. queryObj = { ts: { $gte: syncedTo } }  
  53.              // tailingQuery查询,并绑定其相应游标信息  
  54.             oplogReader.tailingQuery(ns.c_str(), queryObj);  
  55.             tailing  =   false ;  
  56.         }  
  57.          else  {  
  58.             log( 2 )  <<   " repl: tailing=true/n " ;  
  59.         }  
  60.          // 如果依旧无游标信息,可能链接被关闭,则尝试重置链接  
  61.          if (  ! oplogReader.haveCursor() ) {  
  62.             problem()  <<   " repl: dbclient::query returns null (conn closed?) "   <<  endl;  
  63.             oplogReader.resetConnection();  
  64.              return   - 1 ;  
  65.         }  
  66.          //  show any deferred(延期,搁置)database creates from a previous pass  
  67.         {  
  68.              set < string > ::iterator i  =  addDbNextPass.begin();  
  69.              if  ( i  !=  addDbNextPass.end() ) {  
  70.                 BSONObjBuilder b;  
  71.                 b.append( " ns " ,  * i  +   ' . ' );  
  72.                 b.append( " op " ,  " db " );  
  73.                 BSONObj op  =  b.done();  
  74.                  // 找到相应的oplog之后并使用这些oplog操作同步,方法很复杂,这里暂且略过  
  75.                 sync_pullOpLog_applyOperation(op,  0 ,  false );  
  76.             }  
  77.         }  
  78.          if  (  ! oplogReader.more() ) { // 如没有其它oplog操作,则返回  
  79.              if  ( tailing ) { // 已到cap collection结尾  
  80.                 log( 2 )  <<   " repl: tailing & no new activity/n " ;  
  81.                  if ( oplogReader.awaitCapable() )  
  82.                     okResultCode  =   0 ;  //  don't sleep  
  83.             }  
  84.              else  {  
  85.                 log()  <<   " repl:    "   <<  ns  <<   "  oplog is empty/n " ;  
  86.             }  
  87.             {  
  88.                 dblock lk;  
  89.                  // 最近一次保存到本地操作发生时间  
  90.                 OpTime nextLastSaved  =  nextLastSavedLocalTs();  
  91.                 {  
  92.                     dbtemprelease t;  
  93.                      if  (  ! oplogReader.more() ) {  
  94.                          // 设置_lastSavedLocalTs  
  95.                         setLastSavedLocalTs( nextLastSaved );  
  96.                     }  
  97.                 }  
  98.                 save();  
  99.             }  
  100.              return  okResultCode;  
  101.         }  
  102.          // 下一次操作时间,用于绑定到syncedTo上。  
  103.          // syncedTo为时间戳,保存从结点的更新时间,每次从结点需要查询新的oplog时,  
  104.          // 它使用“syncedTo”获得它需要执行的新的操作,或者发现它已经out-of-sync。  
  105.         OpTime nextOpTime;  
  106.         {  
  107.             BSONObj op  =  oplogReader.next();  
  108.             BSONElement ts  =  op.getField( " ts " );  
  109.              if  ( ts.type()  !=  Date  &&  ts.type()  !=  Timestamp ) {  
  110.                  string  err  =  op.getStringField( " $err " );  
  111.                  // 如获取master oplog时出现error  
  112.                  if  (  ! err.empty() ) {  
  113.                      //  13051 is "tailable cursor requested on non capped collection"  
  114.                      if  (op.getIntField( " code " )  ==   13051 ) {  
  115.                         problem()  <<   " trying to slave off of a non-master "   <<   ' /n ' ;  
  116.                         massert(  13344  ,   " trying to slave off of a non-master " ,  false  );  
  117.                     }  
  118.                      else  {  
  119.                         problem()  <<   " repl: $err reading remote oplog:  "   +  err  <<   ' /n ' ;  
  120.                         massert(  10390  ,   " got $err reading remote oplog " ,  false  );  
  121.                     }  
  122.                 }  
  123.                  else  {  
  124.                     problem()  <<   " repl: bad object read from remote oplog:  "   <<  op.toString()  <<   ' /n ' ;  
  125.                     massert(  10391  ,  " repl: bad object read from remote oplog " ,  false );  
  126.                 }  
  127.             }  
  128.              if  ( replPair  &&  replPair -> state  ==  ReplPair::State_Master ) {  
  129.                 OpTime next( ts.date() );                  
  130.                  if  (  ! tailing  &&   ! initial  &&  next  !=  syncedTo ) {  
  131.                      // 强制slave 重新同步  
  132.                     log()  <<   " remote slave log filled, forcing slave resync "   <<  endl;  
  133.                     resetSlave();  
  134.                      return   1 ;  
  135.                 }  
  136.                 dblock lk;  
  137.                 updateSetsWithLocalOps( localLogTail,  true  );  
  138.             }  
  139.             nextOpTime  =  OpTime( ts.date() );  
  140.             log( 2 )  <<   " repl: first op time received:  "   <<  nextOpTime.toString()  <<   ' /n ' ;  
  141.              if  ( initial ) {  
  142.                 log( 1 )  <<   " repl:   initial run/n " ;  
  143.             }  
  144.              if ( tailing ) {  
  145.                  // 当出现旧数据被新oplog覆盖的情况时  
  146.                  if (  ! ( syncedTo  <  nextOpTime ) ) {  
  147.                     log()  <<   " repl ASSERTION failed : syncedTo < nextOpTime "   <<  endl;  
  148.                     log()  <<   " repl syncTo:      "   <<  syncedTo.toStringLong()  <<  endl;  
  149.                     log()  <<   " repl nextOpTime:  "   <<  nextOpTime.toStringLong()  <<  endl;  
  150.                     assert( false );  
  151.                 }  
  152.                 oplogReader.putBack( op );  //  op will be processed in the loop below  
  153.                 nextOpTime  =  OpTime();  //  will reread the op below  
  154.             }  
  155.          // 如本次同步时间与下一次操作时间不相同,意味着从结点上的操作落后主结点太多,从结点处于out-of-sync状态。  
  156.          // 一个out-of-sync的从结点不能通过执行操作赶上主结点,因为主结点中的每一个操作都太新了。这可能是因为从  
  157.          // 结点挂了或者忙于处理读请求。如果同步的时间超出了oplog滚动的时间,它将重新开始一次彻底的同步。  
  158.              else   if  ( nextOpTime  !=  syncedTo ) {  //  didn't get what we queried for - error  
  159.                 Nullstream &  l  =  log();  
  160.                 l  <<   " repl:   nextOpTime  "   <<  nextOpTime.toStringLong()  <<   '   ' ;  
  161.                  if  ( nextOpTime  <  syncedTo )  
  162.                     l  <<   " <?? " ;  
  163.                  else  
  164.                     l  <<   " > " ;  
  165.                 l  <<   "  syncedTo  "   <<  syncedTo.toStringLong()  <<   ' /n ' ;  
  166.                 log()  <<   " repl:   time diff:  "   <<  (nextOpTime.getSecs()  -  syncedTo.getSecs())  <<   " sec/n " ;  
  167.                 log()  <<   " repl:   tailing:  "   <<  tailing  <<   ' /n ' ;  
  168.                 log()  <<   " repl:   data too stale, halting replication "   <<  endl;  
  169.                 replInfo  =  replAllDead  =   " data too stale halted replication " ;  
  170.                 assert( syncedTo  <  nextOpTime );  
  171.                  throw  SyncException();  
  172.             }  
  173.              else  {  
  174.                  /*  t == syncedTo, so the first op was applied previously or it is the first op of initial query and need not be applied.  */  
  175.             }  
  176.         }  
  177.        // 将获取到的oplog操作信息应用到“从结点(slave)”上  
  178.          // apply operations  
  179.         {  
  180.              int  n  =   0 ;  
  181.             time_t saveLast  =  time( 0 );  
  182.              while  (  1  ) {  
  183.                 
  184.                  bool  moreInitialSyncsPending  =   ! addDbNextPass.empty()  &&  n;  //  we need "&& n" to assure we actually process at least one op to get a sync point recorded in the first place.  
  185.                  if  ( moreInitialSyncsPending  ||   ! oplogReader.more() ) {  
  186.                     dblock lk;  
  187.                     OpTime nextLastSaved  =  nextLastSavedLocalTs();  
  188.                     {  
  189.                         dbtemprelease t;  
  190.                          if  (  ! moreInitialSyncsPending  &&  oplogReader.more() ) {  
  191.                              if  ( getInitialSyncCompleted() ) {  //  if initial sync hasn't completed, break out of loop so we can set to completed or clone more dbs  
  192.                                  continue ;  
  193.                             }  
  194.                         }  
  195.                          else  {  
  196.                             setLastSavedLocalTs( nextLastSaved );  
  197.                         }  
  198.                     }  
  199.                      if ( oplogReader.awaitCapable()  &&  tailing )  
  200.                         okResultCode  =   0 ;  //  don't sleep  
  201.                      // syncedTo设置时间戳,保存从结点的更新时间,用于下次从结点需要查询新的oplog时,  
  202.                      // 它使用“syncedTo”获得它需要的新的oplog,或者用于发现它已经out-of-sync。  
  203.                     syncedTo  =  nextOpTime;  
  204.                     save();  //  note how far we are synced up to now  
  205.                     log()  <<   " repl:   applied  "   <<  n  <<   "  operations "   <<  endl;  
  206.                     nApplied  =  n;  
  207.                     log()  <<   " repl:  end sync_pullOpLog syncedTo:  "   <<  syncedTo.toStringLong()  <<  endl;  
  208.                      break ;  
  209.                 }  
  210.                  else  {  
  211.                 }  
  212.                 .....  
  213.                 BSONObj op  =  oplogReader.next();  
  214.                 unsigned b  =  replApplyBatchSize;  
  215.                  bool  justOne  =  b  ==   1 ;  
  216.                 scoped_ptr < writelock >  lk( justOne  ?   0  :  new  writelock() );  
  217.                  while (  1  ) {  
  218.                     BSONElement ts  =  op.getField( " ts " );  
  219.                      // 类型异常判断  
  220.                      if (  ! ( ts.type()  ==  Date  ||  ts.type()  ==  Timestamp ) ) {  
  221.                         log()  <<   " sync error: problem querying remote oplog record "   <<  endl;  
  222.                         log()  <<   " op:  "   <<  op.toString()  <<  endl;  
  223.                         log()  <<   " halting replication "   <<  endl;  
  224.                         replInfo  =  replAllDead  =   " sync error: no ts found querying remote oplog record " ;  
  225.                          throw  SyncException();  
  226.                     }  
  227.                     OpTime last  =  nextOpTime;  
  228.                     nextOpTime  =  OpTime( ts.date() );  
  229.                      // 当上次操作时间比下一次操作时间要更晚,表示cap collection发生了前部数据被overwrite的情况  
  230.                      // 这时系统会执行resync,相关问题参见:  
  231.                      // http://www.snailinaturtleneck.com/blog/2010/10/14/getting-to-know-your-oplog/  
  232.                      if  (  ! ( last  <  nextOpTime ) ) {  
  233.                         log()  <<   " sync error: last applied optime at slave >= nextOpTime from master "   <<  endl;  
  234.                         log()  <<   "  last:        "   <<  last.toStringLong()  <<  endl;  
  235.                         log()  <<   "  nextOpTime:  "   <<  nextOpTime.toStringLong()  <<  endl;  
  236.                         log()  <<   "  halting replication "   <<  endl;  
  237.                         replInfo  =  replAllDead  =   " sync error last >= nextOpTime " ;  
  238.                         uassert(  10123  ,  " replication error last applied optime at slave >= nextOpTime from master " ,  false );  
  239.                     }  
  240.                      // 在从结点中指定一个从主结点中申请操作的延迟时间(单位是秒)。  
  241.                      // 这使得构造一个delayed slaves变得容易。假如用户意外地删了重要的文档或者插入了坏的数据,这些操作都会复制到所有的从结点中。依靠delaying应用程序的操作,你将有可能从错误的操作中恢复。  
  242.                      if  ( replSettings.slavedelay  &&  ( unsigned( time(  0  ) )  <  nextOpTime.getSecs()  +  replSettings.slavedelay ) ) {  
  243.                         assert( justOne );  
  244.                         oplogReader.putBack( op );  
  245.                          // 设置sleep时间  
  246.                         _sleepAdviceTime  =  nextOpTime.getSecs()  +  replSettings.slavedelay  +   1 ;  
  247.                         dblock lk;  
  248.                          if  ( n  >   0  ) {  
  249.                              // syncedTo设置时间戳,保存从结点的更新时间,用于下次从结点需要查询新的oplog时,  
  250.                              // 它使用“syncedTo”获得它需要的新的oplog,或者用于发现它已经out-of-sync。  
  251.                             syncedTo  =  last;  
  252.                             save();  
  253.                         }  
  254.                         log()  <<   " repl:   applied  "   <<  n  <<   "  operations "   <<  endl;  
  255.                         log()  <<   " repl:   syncedTo:  "   <<  syncedTo.toStringLong()  <<  endl;  
  256.                         log()  <<   " waiting until:  "   <<  _sleepAdviceTime  <<   "  to continue "   <<  endl;  
  257.                          return  okResultCode;  
  258.                     }  
  259.                     sync_pullOpLog_applyOperation(op,  & localLogTail,  ! justOne);  
  260.                     n ++ ;  
  261.                      if (  -- b  ==   0  )  
  262.                          break ;  
  263.                      //  if to here, we are doing mulpile applications in a singel write lock acquisition  
  264.                      if (  ! oplogReader.moreInCurrentBatch() ) {  
  265.                          //  break if no more in batch so we release lock while reading from the master  
  266.                          break ;  
  267.                     }  
  268.                     op  =  oplogReader.next();  
  269.                     getDur().commitIfNeeded();  
  270.                 }  
  271.             }  
  272.         }  
  273.          return  okResultCode;  
  274.     }  

    上面方法代码比较长,首先它会初始要链接的master的oplog名空间信息,之后尝试链接到master上以获取相应的cursor id信息。该cursor id用于标识当前slave访问master时所使用的cursor(因为master中的oplog cursor会在返回oplog信息时不关闭,它支持下次slave链接使用该cursor时从相应的pos位置继续获取。这块内容可以参见这篇文章 Mongodb源码分析--Replication之主从模式--Master).

    如果cursorid正常,则使用oplogReader对象来获取相应的oplog信息(注:oplogReader为mongodb为了查询oplog而声明的一个类,详情参见其源码文件oplogreader.h)

    除此以外,上面方法还会设置本地的syncedTo来记录下次同步时使用的时间戳。同时根据本地保存的时间戳与oplogReader所返回的 master oplog信息中的ts进行比较,以判断是否出现out of sync的情况,以进而执行resync操作。有关这类逻辑说明参见上面的代码注释即可。
    
    当获取的master oplog符合(本地时间戳)要求时,则将oplog对象进行分解,以进而将其中的数据对象保存到本地并执行持久化操作(上面代码 段:getDur().commitIfNeeded())。这里要说明的是,将oplog进行分解时执行的逻辑通过 sync_pullOpLog_applyOperation方法中执行,因为这里牵扯到oplog的数据结构,由于篇幅所限,这部分内容我会在后面章节 中进行说明,我们只要知道在分解结束后,最终调用如下方法将数据放到本机上:

  

  1. // repl.cpp  
  2.      void  ReplSource::applyOperation( const  BSONObj &  op) {  
  3.            
  4.      // oplog.cpp                                      
  5.      void  applyOperation_inlock( const  BSONObj &  op ,  bool  fromRepl ) {  
  6.         OpCounters  *  opCounters  =  fromRepl  ?   & replOpCounters :  & globalOpCounters;  
  7.          if ( logLevel  >=   6  )  
  8.             log()  <<   " applying op:  "   <<  op  <<  endl;  
  9.         assertInWriteLock();  
  10.         OpDebug debug;  
  11.         BSONObj o  =  op.getObjectField( " o " ); // 实际操作的document  
  12.          const   char   * ns  =  op.getStringField( " ns " );  
  13.          //  operation type -- see logOp() comments for types  
  14.          const   char   * opType  =  op.getStringField( " op " );  
  15.          if  (  * opType  ==   ' i '  ) { // 插入  
  16.             opCounters -> gotInsert();  
  17.              const   char   * p  =  strchr(ns,  ' . ' );  
  18.              if  ( p  &&  strcmp(p,  " .system.indexes " )  ==   0  ) {  
  19.                  //  updates aren't allowed for indexes -- so we will do a regular insert. if index already  
  20.                  //  exists, that is ok.  
  21.                 theDataFileMgr.insert(ns, ( void * ) o.objdata(), o.objsize());  
  22.             }  
  23.              else  {  
  24.                  //  do upserts for inserts as we might get replayed more than once  
  25.                 BSONElement _id;  
  26.                  if (  ! o.getObjectID(_id) ) {  
  27.                      /*  No _id.  This will be very slow.  */  
  28.                     Timer t;  
  29.                     updateObjects(ns, o, o,  true ,  false ,  false  , debug );  
  30.                      if ( t.millis()  >=   2  ) {  
  31.                         RARELY OCCASIONALLY log()  <<   " warning, repl doing slow updates (no _id field) for  "   <<  ns  <<  endl;  
  32.                     }  
  33.                 }  
  34.                  else  {  
  35.                     BSONObjBuilder b;  
  36.                     b.append(_id);  
  37.                     RARELY ensureHaveIdIndex(ns);  //  otherwise updates will be slow  
  38.                     updateObjects(ns, o, b.done(),  true ,  false ,  false  , debug );  
  39.                 }  
  40.             }  
  41.         }  
  42.          else   if  (  * opType  ==   ' u '  ) { // 更新  
  43.             opCounters -> gotUpdate();  
  44.             RARELY ensureHaveIdIndex(ns);  //  otherwise updates will be super slow  
  45.             updateObjects(ns, o, op.getObjectField( " o2 " ),  /* upsert */  op.getBoolField( " b " ),  /* multi */   false ,  /* logop */   false  , debug );  
  46.         }  
  47.          else   if  (  * opType  ==   ' d '  ) { // 删除  
  48.             opCounters -> gotDelete();  
  49.              if  ( opType[ 1 ]  ==   0  )  
  50.                 deleteObjects(ns, o, op.getBoolField( " b " ));  
  51.              else  
  52.                 assert( opType[ 1 ]  ==   ' b '  );  //  "db" advertisement  
  53.         }  
  54.          else   if  (  * opType  ==   ' n '  ) { // 无操作  
  55.              //  no op  
  56.         }  
  57.          else   if  (  * opType  ==   ' c '  ) { // command  
  58.             opCounters -> gotCommand();  
  59.             BufBuilder bb;  
  60.             BSONObjBuilder ob;  
  61.             _runCommands(ns, o, bb, ob,  true ,  0 );  
  62.         }  
  63.          else  {  
  64.             stringstream ss;  
  65.             ss  <<   " unknown opType [ "   <<  opType  <<   " ] " ;  
  66.              throw  MsgAssertionException(  13141  , ss.str() );  
  67.         }  
  68.     }  

    到这里,关于如何进行crud的操作,就与我之前的几篇文章的内容关联上了,大家回顾一下即可。最后用一次时序图来回顾一下slave的执行流程:

 

    好了,今天的内容到这里就告一段落了。

 

    原文链接:http://www.cnblogs.com/daizhj/archive/2011/06/20/mongodb_sourcecode_repl_slave_run.html
    作者: daizhj, 代震军   
    微博: http://t.sina.com.cn/daizhj
    Tags: mongodb,c++,Replica,master-slave

抱歉!评论已关闭.