Distributed Computing using Erlang - 2
In previous article we have seen how to connect to a remote node and run a module prebuilt in Erlang. In this article we will learn how we can run our own module to do some task. For example we will fetch ip address from remote nodes which are assigned to their network interfaces.
Our module will be looking like this:
% file name should be ourmodule.erl
-module(ourmodule).-export([ getip/0 ]).getip()->
% This is for Mac specific terminal
% B = os:cmd('ifconfig $2 | grep \"inet \" | awk -F\' \' \'{print $2}\' | awk \'{print $1}\''),
% This is for Linux specific terminal
B = os:cmd('ifconfig $2 | grep \"inet \" | awk -F\' \' \'{print $2}\' | awk \'{print $1}\' | awk -F \':\' \'{print $2}\''),
io:format("node: ~s ~n ~s ", [node(), B]),
ok.
Save this code into a file naming ourmodule.erl .
Now lets compile our module. First we have to go to the directory where our module is saved. Then open the Erlang shell and compile with,
c(ourmodule). %%% output: {ok,ourmodule}
After compilation we will have ourmodule.beam file in the same directory. Which is the erlang executable for this module. Then we have to copy this ourmodule.beam file to the remote nodes. Now from the same directory (at remote node where the beam file is located) lets open a Erlang shell as,
erl -name cloud@remote-host -setcookie "12345"
We are done, this is all we need to do for the remote nodes.
Now from your master/local node execute this command,
rpc:call('cloud@remote-host', ourmodule, getip, []).% output : there will be nodename and some list of ip like
%
% node: cloud@remote-host
% 127.0.0.1
% 192.168.1.45
% ok.
This is a simple example how we can run our own module in distributed Erlang environment. We can do other task using the same module by just adding more function or we can just write new module for our own purpose, and then we can distribute the executable to different node and execute them remotely.