您的位置:首页 > 运维架构

Hadoop源码分析之心跳机制

2012-05-30 22:32 423 查看
一.心跳机制

1. hadoop集群是master/slave模式,master包括Namenode和Jobtracker,slave包括Datanode和Tasktracker。

2. master启动的时候,会开一个ipc server在那里,等待slave心跳。

3. slave启动时,会连接master,并每隔3秒钟主动向master发送一个“心跳”,这个时间可 以通过”heartbeat.recheck.interval”属性来设置。将自己的状态信息告诉master,然后master也是通过这个心跳的返回值,向slave节点传达指令。

4. 需要指出的是:namenode与datanode之间的通信,jobtracker与tasktracker之间的通信,都是通过“心跳”完成的。

二.Datanode、Namenode心跳源码分析

既然“心跳”是Datanode主动给Namenode发送的。那Datanode是怎么样发送的呢?下面贴出Datanode.class中的关键代码:

代码一:

/**
* 循环调用“发送心跳”方法,直到shutdown
* 调用远程Namenode的方法
*/
public void offerService() throws Exception {
•••
while (shouldRun) {
try {
long startTime = now();
// heartBeatInterval是在启动Datanode时根据配置文件设置的,是心跳间隔时间
if (startTime - lastHeartbeat > heartBeatInterval) {
lastHeartbeat = startTime;
//Datanode发送心跳
DatanodeCommand[] cmds = namenode.sendHeartbeat(dnRegistration,
data.getCapacity(),
data.getDfsUsed(),
data.getRemaining(),
xmitsInProgress.get(),
getXceiverCount());
myMetrics.addHeartBeat(now() - startTime);

if (!processCommand(cmds))
continue;
}

•••
}
} // while (shouldRun)
} // offerService


需要注意的是:发送心跳的对象并不是datanode,而是一个名为namenode的对象,难道在datanode端就直接有个namenode的引用吗?其实不然,我们来看看这个namenode吧:

代码二:

public DatanodeProtocol namenode = null;


namenode其实是一个DatanodeProtocol的引用,在对hadoop RPC机制分析的文章中我提到过,这是一个Datanode和Namenode通信的协议,其中有许多未实现的接口方法,sendHeartbeat()就是其中的一个。下面看看这个namenode对象是怎么被实例化的吧:

代码三:

this.namenode = (DatanodeProtocol)
RPC.waitForProxy(DatanodeProtocol.class,
DatanodeProtocol.versionID,
nameNodeAddr,
conf);


其实这个namenode并不是Namenode的一个对象,而只是一个Datanode端对Namenode的代理对象,正是这个代理完成了“心跳”。代理的底层实现就是RPC机制了。

三.Tasktracker、Jobtracker心跳源码分析

同样我们从Tasktracker入手,下面贴出Tasktracker.class的关键代码:

代码四:

代码一:
State offerService() throws Exception {
long lastHeartbeat = System.currentTimeMillis();
while (running && !shuttingDown) {
•••

// 发送心跳,调用代码二
HeartbeatResponse heartbeatResponse = transmitHeartBeat(now);

•••
return State.NORMAL;
}

代码二:
HeartbeatResponse transmitHeartBeat(long now) throws IOException {
•••
HeartbeatResponse heartbeatResponse = jobClient.heartbeat(status,
justStarted,
justInited,
askForNewTask,
heartbeatResponseId);
•••
return heartbeatResponse;
}


其实我觉得分析到这里大家就可以自己分析了,jobClient也是一个协议:

代码五:

InterTrackerProtocol jobClient;


该协议用于定义Tasktracker和Jobtracker的通信。同样,它也是一个代理对象:

代码六:

this.jobClient = (InterTrackerProtocol)
UserGroupInformation.getLoginUser().doAs(
new PrivilegedExceptionAction<Object>() {
public Object run() throws IOException {
return RPC.waitForProxy(InterTrackerProtocol.class,
InterTrackerProtocol.versionID,
jobTrackAddr, fConf);
}
});


终于,hadoop底层通信整个系列的源码分析全部完成了。我可以好好地复习学校的功课了。呵呵。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: