Erlang epmd的角色以及使用

时间:2022-06-01 19:13:45

转载自yufeng.info 


很多同学误会了epmd的作用,认为epmd就是erlang集群的协议,我来澄清下:

Epmd是Erlang Port Mapper Daemon的缩写,在Erlang集群中的作用相当于dns的作用,提供节点名称到端口的查询服务,epmd绑定在总所周知的4369端口上。

epmd文档:http://www.erlang.org/doc/man/epmd.html
epmd协议:http://www.erlang.org/doc/apps/erts/erl_dist_protocol.html

Erlang的节点名称是类似这样的foo@ip的格式,当一个节点启动的时候,首先会在本机启动epmd,同时把自己的节点名称和节点监听的tcp端口登记在上面。
看代码:

// erlexec.c
...
case 'n':
if (strcmp(argv[i], "-name") == 0) { /* -name NAME */
if (i+1 >= argc)
usage("-name");

/*
* Note: Cannot use add_args() here, due to non-defined
* evaluation order.
*/

add_arg(argv[i]);
add_arg(argv[i+1]);
isdistributed = 1;
i++;
...
case 's': /* -sname NAME */
if (strcmp(argv[i], "-sname") == 0) {
if (i+1 >= argc)
usage("-sname");
add_arg(argv[i]);
add_arg(argv[i+1]);
isdistributed = 1;
i++;
}
...
if (isdistributed && !no_epmd)
start_epmd(epmd_prog);
...

我们可以透过erl -epmd EPMD_PROG来传入不同的参数。

再看下实验:

$erl -sname a
$erl -sname b
$erl -sname c
$ ps -ef|grep epmd
membase 4592 1 0 Aug25 ? 00:00:39 /usr/local/bin/epmd -daemon
...
$ netstat -an|grep 4369
tcp 0 0 0.0.0.0:4369 0.0.0.0:* LISTEN
$ epmd -names
epmd: up and running on port 4369 with data:
name c at port 4096
name b at port 4097
name a at port 4098
...
$erl -sname x
Erlang R14B04 (erts-5.8.5) 1 [64-bit] [smp:16:16] [rq:16] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.8.5 (abort with ^G)
(x@my031091)1> erl_epmd:port_please(x, "127.0.0.1").
{port,34625,5}

(x@my031091)2> erl_epmd:names().
{ok,[{"a",4096},{"b",4097},{"c",4098},{"x",34625}]}

epmd是个标准的tcp服务器,它的协议如下:
Erlang epmd的角色以及使用

kernel的erl_epmd模块提供epmd协议的封装,向net_kernel模块提供服务。如果net_kernel要连接其他节点的时候,就取出节点名称的ip部分,透过erl_epmd建立连接到ip:4369,通过epmd协议来查询想要的foo的端口,然后再用ip:port去连接真正的服务。

新版本的epmd提供了强行移除名称的功能,避免由于erlang虚拟机由于某种原因crash,没有注销名字,导致无法再使用这个名字。
要使用stop功能,epmd必须以 -relaxed_command_check 启动,具体参考epmd –help
演示下:

$ erl -sname x -epmd "epmd -relaxed_command_check -daemon"
Erlang R14B04 (erts-5.8.5) 1 [64-bit] [smp:16:16] [rq:16] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.8.5 (abort with ^G)
(x@my031089)1>

$ epmd -names
epmd: up and running on port 4369 with data:
name x at port 58953
$ epmd -stop x
STOPPED
$ epmd -names
epmd: up and running on port 4369 with data:

我们看到名称已经抢先移除成功。

祝玩得开心!