zoukankan      html  css  js  c++  java
  • HDFS源码分析之EditLogTailer

    在FSNamesystem中,有这么一个成员变量,定义如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. /** 
    2.  * Used when this NN is in standby state to read from the shared edit log. 
    3.  * 当NameNode处于standby状态时用于从共享的edit log读取数据 
    4.  */  
    5. private EditLogTailer editLogTailer = null;  

            editLogTailer是一个编辑日志edit log的追踪器,它的主要作用就是当NameNode处于standby状态时用于从共享的edit log读取数据。它的构造是在FSNamesystem的startStandbyServices()方法中,代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. editLogTailer = new EditLogTailer(this, conf);  
    2. editLogTailer.start();  

            利用当前FSNamesystem实例this和配置信息conf实例化一个EditLogTailer对象,然后调用其start()方法启动它。

            接下来我们看看EditLogTailer的实现,先来看下其成员变量,代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. // 编辑日志跟踪线程EditLogTailerThread实例tailerThread  
    2. private final EditLogTailerThread tailerThread;  
    3.   
    4. // HDFS配置信息Configuration实例conf  
    5. private final Configuration conf;  
    6.   
    7. // 文件系统命名空间FSNamesystem实例namesystem  
    8. private final FSNamesystem namesystem;  
    9.   
    10. // 文件系统编辑日志FSEditLog实例editLog  
    11. private FSEditLog editLog;  
    12.   
    13. // Active NameNode地址InetSocketAddress  
    14. private InetSocketAddress activeAddr;  
    15.   
    16. // 名字节点通信接口NamenodeProtocol  
    17. private NamenodeProtocol cachedActiveProxy = null;  
    18.   
    19. /** 
    20.  * The last transaction ID at which an edit log roll was initiated. 
    21.  * 一次编辑日志滚动开始时的最新事务ID 
    22.  */  
    23. private long lastRollTriggerTxId = HdfsConstants.INVALID_TXID;  
    24.   
    25. /** 
    26.  * The highest transaction ID loaded by the Standby. 
    27.  * StandBy NameNode加载的最高事务ID 
    28.  */  
    29. private long lastLoadedTxnId = HdfsConstants.INVALID_TXID;  
    30.   
    31. /** 
    32.  * The last time we successfully loaded a non-zero number of edits from the 
    33.  * shared directory. 
    34.  * 最后一次我们从共享目录成功加载一个非零编辑的时间 
    35.  */  
    36. private long lastLoadTimestamp;  
    37.   
    38. /** 
    39.  * How often the Standby should roll edit logs. Since the Standby only reads 
    40.  * from finalized log segments, the Standby will only be as up-to-date as how 
    41.  * often the logs are rolled. 
    42.  * StandBy NameNode滚动编辑日志的时间间隔。 
    43.  */  
    44. private final long logRollPeriodMs;  
    45.   
    46. /** 
    47.  * How often the Standby should check if there are new finalized segment(s) 
    48.  * available to be read from. 
    49.  * StandBy NameNode检查是否存在可以读取的新的最终日志段的时间间隔 
    50.  */  
    51. private final long sleepTimeMs;  

            其中,比较重要的几个变量如下:

            1、EditLogTailerThread tailerThread:它是编辑日志跟踪线程,

            我们再来看下EditLogTailer的构造方法,如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1.  public EditLogTailer(FSNamesystem namesystem, Configuration conf) {  
    2.      
    3. // 实例化编辑日志追踪线程EditLogTailerThread  
    4. this.tailerThread = new EditLogTailerThread();  
    5.      
    6. // 根据入参初始化配置信息conf和文件系统命名系统namesystem  
    7. this.conf = conf;  
    8.    this.namesystem = namesystem;  
    9.      
    10.    // 从namesystem中获取editLog  
    11.    this.editLog = namesystem.getEditLog();  
    12.      
    13.    // 最新加载edit log时间lastLoadTimestamp初始化为当前时间  
    14.    lastLoadTimestamp = now();  
    15.   
    16.    // StandBy NameNode滚动编辑日志的时间间隔logRollPeriodMs  
    17.    // 取参数dfs.ha.log-roll.period,参数未配置默认为2min  
    18.    logRollPeriodMs = conf.getInt(DFSConfigKeys.DFS_HA_LOGROLL_PERIOD_KEY,  
    19.        DFSConfigKeys.DFS_HA_LOGROLL_PERIOD_DEFAULT) * 1000;  
    20.      
    21.    // 如果logRollPeriodMs大于等于0  
    22.    if (logRollPeriodMs >= 0) {  
    23.       
    24.      // 调用getActiveNodeAddress()方法初始化Active NameNode地址activeAddr  
    25.      this.activeAddr = getActiveNodeAddress();  
    26.      Preconditions.checkArgument(activeAddr.getPort() > 0,  
    27.          "Active NameNode must have an IPC port configured. " +  
    28.          "Got address '%s'", activeAddr);  
    29.      LOG.info("Will roll logs on active node at " + activeAddr + " every " +  
    30.          (logRollPeriodMs / 1000) + " seconds.");  
    31.    } else {  
    32.      LOG.info("Not going to trigger log rolls on active node because " +  
    33.          DFSConfigKeys.DFS_HA_LOGROLL_PERIOD_KEY + " is negative.");  
    34.    }  
    35.      
    36.    // StandBy NameNode检查是否存在可以读取的新的最终日志段的时间间隔sleepTimeMs  
    37.    // 取参数dfs.ha.tail-edits.period,参数未配置默认为1min  
    38.    sleepTimeMs = conf.getInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY,  
    39.        DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_DEFAULT) * 1000;  
    40.      
    41.    LOG.debug("logRollPeriodMs=" + logRollPeriodMs +  
    42.        " sleepTime=" + sleepTimeMs);  
    43.  }  

            下面,我们再看下这个十分重要的编辑日志追踪线程EditLogTailerThread的实现,它的构造方法很简单,没有什么可说的,我们着重看下它的run()方法,代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. @Override  
    2. public void run() {  
    3.   SecurityUtil.doAsLoginUserOrFatal(  
    4.       new PrivilegedAction<Object>() {  
    5.       @Override  
    6.       public Object run() {  
    7.         doWork();  
    8.         return null;  
    9.       }  
    10.     });  
    11. }  

            run()方法内继而调用了doWork()方法,代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. private void doWork() {  
    2.       
    3.   // 标志位shouldRun为true时一直循环  
    4.   while (shouldRun) {  
    5.     try {  
    6.       // There's no point in triggering a log roll if the Standby hasn't  
    7.       // read any more transactions since the last time a roll was  
    8.       // triggered.   
    9.       // 自从上次日志滚动触发以来,如果StandBy NameNode没有读到任何事务的话,没有点触发一次日志滚动,  
    10.           
    11.       // 如果是自从上次加载后过了太长时间,并且上次编辑日志滚动开始时的最新事务ID小于上次StandBy NameNode加载的最高事务ID  
    12.       if (tooLongSinceLastLoad() &&  
    13.           lastRollTriggerTxId < lastLoadedTxnId) {  
    14.             
    15.         // 触发Active NameNode进行编辑日志滚动  
    16.         triggerActiveLogRoll();  
    17.       }  
    18.       /** 
    19.        * Check again in case someone calls {@link EditLogTailer#stop} while 
    20.        * we're triggering an edit log roll, since ipc.Client catches and 
    21.        * ignores {@link InterruptedException} in a few places. This fixes 
    22.        * the bug described in HDFS-2823. 
    23.        */  
    24.         
    25.       // 判断标志位shouldRun,如果其为false的话,退出循环  
    26.       if (!shouldRun) {  
    27.         break;  
    28.       }  
    29.         
    30.       // 调用doTailEdits()方法执行日志追踪  
    31.       doTailEdits();  
    32.     } catch (EditLogInputException elie) {  
    33.       LOG.warn("Error while reading edits from disk. Will try again.", elie);  
    34.     } catch (InterruptedException ie) {  
    35.       // interrupter should have already set shouldRun to false  
    36.       continue;  
    37.     } catch (Throwable t) {  
    38.       LOG.fatal("Unknown error encountered while tailing edits. " +  
    39.           "Shutting down standby NN.", t);  
    40.       terminate(1, t);  
    41.     }  
    42.   
    43.     // 线程休眠sleepTimeMs时间后继续工作  
    44.     try {  
    45.       Thread.sleep(sleepTimeMs);  
    46.     } catch (InterruptedException e) {  
    47.       LOG.warn("Edit log tailer interrupted", e);  
    48.     }  
    49.   }  
    50. }  

            当标志位shouldRun为true时,doWork()方法一直在while循环内执行,其处理逻辑如下:

            1、如果是自从上次加载后过了太长时间,并且上次编辑日志滚动开始时的最新事务ID小于上次StandBy NameNode加载的最高事务ID,触发Active NameNode进行编辑日志滚动:

            自从上次加载后过了太长时间是根据tooLongSinceLastLoad()方法判断的,而触发Active NameNode进行编辑日志滚动则是通过triggerActiveLogRoll()方法来完成的;

            2、判断标志位shouldRun,如果其为false的话,退出循环;

            3、调用doTailEdits()方法执行日志追踪;

            4、线程休眠sleepTimeMs时间后继续执行上述工作。

            我们先来看下如果确定自从上次加载后过了太长时间,tooLongSinceLastLoad()方法代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1.  /** 
    2.   * @return true if the configured log roll period has elapsed. 
    3.   */  
    4.  private boolean tooLongSinceLastLoad() {  
    5.     
    6. // StandBy NameNode滚动编辑日志的时间间隔logRollPeriodMs大于0,  
    7. // 且最后一次我们从共享目录成功加载一个非零编辑的时间到现在的时间间隔大于logRollPeriodMs  
    8.    return logRollPeriodMs >= 0 &&   
    9.      (now() - lastLoadTimestamp) > logRollPeriodMs ;  
    10.  }  

            它判断的主要依据就是,StandBy NameNode滚动编辑日志的时间间隔logRollPeriodMs大于0,且最后一次我们从共享目录成功加载一个非零编辑的时间到现在的时间间隔大于logRollPeriodMs。

            触发Active NameNode进行编辑日志滚动的triggerActiveLogRoll()方法代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. /** 
    2.  * Trigger the active node to roll its logs. 
    3.  * 触发Active NameNode滚动日志 
    4.  */  
    5. private void triggerActiveLogRoll() {  
    6.   LOG.info("Triggering log roll on remote NameNode " + activeAddr);  
    7.   try {  
    8.       
    9.     // 获得Active NameNode的代理,并调用其rollEditLog()方法滚动编辑日志  
    10.     getActiveNodeProxy().rollEditLog();  
    11.       
    12.     // 将上次StandBy NameNode加载的最高事务ID,即lastLoadedTxnId,赋值给上次编辑日志滚动开始时的最新事务ID,即lastRollTriggerTxId,  
    13.     // 这么做是为了方便进行日志回滚  
    14.     lastRollTriggerTxId = lastLoadedTxnId;  
    15.   } catch (IOException ioe) {  
    16.     LOG.warn("Unable to trigger a roll of the active NN", ioe);  
    17.   }  
    18. }  

            它首先会获得Active NameNode的代理,并调用其rollEditLog()方法滚动编辑日志,然后将上次StandBy NameNode加载的最高事务ID,即lastLoadedTxnId,赋值给上次编辑日志滚动开始时的最新事务ID,即lastRollTriggerTxId,这么做是为了方便进行日志回滚以及逻辑判断。

            好了,最后我们看下最重要的执行日志追踪的doTailEdits()方法吧,代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1.  @VisibleForTesting  
    2.  void doTailEdits() throws IOException, InterruptedException {  
    3.    // Write lock needs to be interruptible here because the   
    4.    // transitionToActive RPC takes the write lock before calling  
    5.    // tailer.stop() -- so if we're not interruptible, it will  
    6.    // deadlock.  
    7.     
    8. // namesystem加写锁  
    9.    namesystem.writeLockInterruptibly();  
    10.    try {  
    11.       
    12.      // 通过namesystem获取文件系统镜像FSImage实例image  
    13.      FSImage image = namesystem.getFSImage();  
    14.   
    15.      // 通过文件系统镜像FSImage实例image获取最新的事务ID  
    16.      long lastTxnId = image.getLastAppliedTxId();  
    17.        
    18.      if (LOG.isDebugEnabled()) {  
    19.        LOG.debug("lastTxnId: " + lastTxnId);  
    20.      }  
    21.      Collection<EditLogInputStream> streams;  
    22.      try {  
    23.         
    24.     // 从编辑日志editLog中获取编辑日志输入流集合streams,获取的输入流为最新事务ID加1之后的数据  
    25.        streams = editLog.selectInputStreams(lastTxnId + 1, 0, null, false);  
    26.      } catch (IOException ioe) {  
    27.        // This is acceptable. If we try to tail edits in the middle of an edits  
    28.        // log roll, i.e. the last one has been finalized but the new inprogress  
    29.        // edits file hasn't been started yet.  
    30.        LOG.warn("Edits tailer failed to find any streams. Will try again " +  
    31.            "later.", ioe);  
    32.        return;  
    33.      }  
    34.      if (LOG.isDebugEnabled()) {  
    35.        LOG.debug("edit streams to load from: " + streams.size());  
    36.      }  
    37.        
    38.      // Once we have streams to load, errors encountered are legitimate cause  
    39.      // for concern, so we don't catch them here. Simple errors reading from  
    40.      // disk are ignored.  
    41.      long editsLoaded = 0;  
    42.      try {  
    43.         
    44.     // 调用文件系统镜像FSImage实例image的loadEdits(),  
    45.     // 利用编辑日志输入流集合streams,加载编辑日志至目标namesystem中的文件系统镜像FSImage,  
    46.     // 并获得编辑日志加载的大小editsLoaded  
    47.        editsLoaded = image.loadEdits(streams, namesystem);  
    48.      } catch (EditLogInputException elie) {  
    49.        editsLoaded = elie.getNumEditsLoaded();  
    50.        throw elie;  
    51.      } finally {  
    52.        if (editsLoaded > 0 || LOG.isDebugEnabled()) {  
    53.          LOG.info(String.format("Loaded %d edits starting from txid %d ",  
    54.              editsLoaded, lastTxnId));  
    55.        }  
    56.      }  
    57.   
    58.      if (editsLoaded > 0) {// 如果editsLoaded大于0  
    59.     // 最后一次我们从共享目录成功加载一个非零编辑的时间lastLoadTimestamp更新为当前时间  
    60.        lastLoadTimestamp = now();  
    61.      }  
    62.        
    63.      // 上次StandBy NameNode加载的最高事务ID更新为image中最新事务ID  
    64.      lastLoadedTxnId = image.getLastAppliedTxId();  
    65.    } finally {  
    66.        
    67.      // namesystem去除写锁  
    68.      namesystem.writeUnlock();  
    69.    }  
    70.  }  

            大体处理流程如下:

            1、首先,namesystem加写锁;

            2、通过namesystem获取文件系统镜像FSImage实例image;

            3、通过文件系统镜像FSImage实例image获取最新的事务ID,即lastTxnId;

            4、从编辑日志editLog中获取编辑日志输入流集合streams,获取的输入流为最新事务ID加1之后的数据:

            ps:注意,这个编辑日志输入流集合streams并非读取的是editLog对象中的数据,毕竟editLog也是根据namesystem来获取的,如果从其中读取数据再加载到namesystem中的fsimage中,没有多大意义,这个日志输入流实际上是通过Hadoop HA中的JournalNode来获取的,这个我们以后再分析。

            5、调用文件系统镜像FSImage实例image的loadEdits(),利用编辑日志输入流集合streams,加载编辑日志至目标namesystem中的文件系统镜像FSImage,并获得编辑日志加载的大小editsLoaded;

            6、如果editsLoaded大于0,最后一次我们从共享目录成功加载一个非零编辑的时间lastLoadTimestamp更新为当前时间;

            7、上次StandBy NameNode加载的最高事务ID更新为image中最新事务ID;

            8、namesystem去除写锁。

            部分涉及FSImage、FSEditLog、JournalNode等的细节,限于篇幅,我们以后再分析!

  • 相关阅读:
    git命令大全
    QT学习笔记7:C++函数默认参数
    QT学习笔记6:常见的 QGraphicsItem
    QT学习笔记5:QMouseEvent鼠标事件简介
    QT学习笔记4:QT中GraphicsView编程
    QT学习笔记3:QT中语法说明
    Opencv学习笔记5:Opencv处理彩虹图、铜色图、灰度反转图
    Opencv学习笔记4:Opencv处理调整图片亮度和对比度
    deploy java web in IDEA with tomcat
    mongodb install
  • 原文地址:https://www.cnblogs.com/jirimutu01/p/5556232.html
Copyright © 2011-2022 走看看