12 月 15, 2019

MPI 是一种信息传递接口,常用于平行计算或分布式计算。OpenMPI 是 MPI 的一种开源方案。本文介绍搭建 OpenMPI 计算集群,基于主人-奴隶架构 (master-slave),使用 SSH 作为通讯协议,使用 NFS 共享文件。

假设:我们有一个 master 和 2 个奴隶,所有机器运行 ubuntu 18.04 x64 系统。master 的 IP 地址为 192.168.0.1,奴隶的IP地址分别为 192.168.0.2 和 192.168.0.3

1. Master 安装及设定

1.1. 更改 master 的 /etc/hosts 文件

这样可以避免后续使用 IP 地址 (此步骤也可以更改为假设私有 DNS 服务)

# cat /etc/hosts
192.168.0.1 master
192.168.0.2 s1
192.168.0.3 s2

1.2. 安装所需软件

apt update
apt install nfs-kernel-server
apt install gcc g++ make openmpi-bin libopenmpi-dev

1.3. 设定 NFS

此处假设 /home/cloud 作为共享目录,共享权限为读/写(请根据实际情况更改)

mkdir /home/cloud
echo "/home/cloud *(rw,sync,no_root_squash,no_subtree_check)" >  /etc/exports
exportfs -a

1.4. 将Slave加入以知主机

for i in {1..2}
do
	ssh-keyscan -H s$i >> ~/.ssh/known_hosts
done 

同时需要设定 SSH 免密登录,方式有很多种,常用的为使用密钥登录,或使用 sshpasswd。

1.5. 新增 hostfile,加入主机

如果不需要 master 参与计算,请移除

#cat /home/cloud/hostfile
master
s1
s2

2. Slave 安装及设定

在所有 Slave 上执行以下设定

2.1. 设定 /etc/hosts

加入 master 和 本机,不需要添加所有的 slave (当然添加了也没问题)

# cat /etc/hosts
192.168.0.1 master
192.168.0.3 s2

2.2. 安装所需软件

apt update
apt install openmpi-bin libopenmpi-dev nfs-common
echo "master:/home/cloud /home/cloud nfs" >> /etc/fstab
mount -a

2.3. 关闭防火墙

iptables -F
ufw reset
ufw disable

3. 测试

3.1. 测试 shell

在 master 上执行如下指令,允许以 root 执行,每个节点执行一个任务

mpirun --allow-run-as-root -npernode 1  --hostfile /home/cloud/hostfile hostname

期望输出

master
s1
s2

如果输出不正常,请检查防火墙设定以及 OpenMPI 是否成功安装

3.2. 测试 Hello World

首先在 /home/cloud 中新增 hello.c

#include "mpi.h"
#include 
#include 

int main (int argc, char *argv[])
{
  int numtasks, taskid, len;
  char hostname[MPI_MAX_PROCESSOR_NAME];
  // 初始化 MPI
  MPI_Init(&argc, &argv);
  // 有几个任务?
  MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
  // 我是谁?
  MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
  // 获取主机名
  MPI_Get_processor_name(hostname, &len);

  printf ("Hello from task %d on %s!\n", taskid, hostname);
  // 关闭 MPI
  MPI_Finalize();
}

编译语法和 gcc 基本一样

 mpicc hello.c -o hello

执行

mpirun --allow-run-as-root -npernode 1  --hostfile /home/cloud/hostfile ./hello

期望输出

Hello from task 0 on master!
Hello from task 1 on s2!
Hello from task 2 on s1!

如果提示 unable to launch the specified application,请检查 slave 是否可以成功访问共享的文件 (NFS)

如果提示 usock_peer_send_blocking,请检查 master 和 slave 的通讯情况 (防火墙)

4. 后记

测试成功后,一个基于 OpenMPI 的计算集群就已经成功设定。如需增加节点,只需要修改 master 的 hosts 以及 hostfile 文件,以及在新节点上执行2的设定即可。

基于安全考虑,应在 Master 上设定 NFS 防火墙,只允许 Slave 所在 IP 段访问。

同样基于安全考虑,可新建一个新用户用于执行 MPI 任务。

基于 MPI 编程需引入 mpi.h 头文件,请参阅 MPI 相关编程教程。

文件同步部分,亦可使用 rsync 或者传统的 FTP 等协议。

常用操作指令

# 启动 10 个任务,每个节点执行 3 个
mpirun --allow-run-as-root -np 10 -npernode 3  --hostfile /home/cloud/hostfile ./task
# 编译,与 gcc / g++ 参数一致
mpicc hello.c -o hello
mpic++ sort.cpp -o sort -mcmodel=large

Reference

OpenMPI FAQ: https://www.open-mpi.org/faq/
Running an MPI Cluster within a LAN: https://mpitutorial.com/tutorials/running-an-mpi-cluster-within-a-lan/

   

無人評論!