我怎样才能使用 Fabric 将它并行地达到 运行?

How can I get this to run in parallel using Fabric?

我之前问过一个相关问题:

How to issue commands on remote hosts in parallel using Fabric without using a fabfile?

我在多个测试主机上并行执行测试时遇到问题。

我的代码如下所示:

@parallel  
def run_test(arg_list):
    # arg_list is a list of dictionary.  Each entry in
    # arg_list has a 'ip_address' and a 'test_config_file'

    for x in arg_list:
        ip_address = x['ip_address']
        test_config_file = x['test_config_file']
        env['host_string'] = ip_address
        # The test program "test_localhost.py" is already on all the Test hosts
        cmd = "/root/test_localhost.py --ip_addr=" + ip_address + " --config=" + test_config_file
        run(cmd)


if __name__ == '__main__':

    env.parallel = True

    # Each test host will have unique test_config_files
    arg_list = list()
    arg_list.append({'ip_address':'10.10.10.10', 'test_config_file': "config_01.json"})
    arg_list.append({'ip_address':'10.10.10.11', 'test_config_file': "config_02.json"})

    execute(run_test, arg_list)

我已经 运行 此代码针对 2 个以上的测试主机。我有一个脚本来检查测试是否在测试主机上 运行ning。测试不是 运行 并行进行的。

相反,测试是按顺序 运行 - "test_localhost.py" 首先是在 10.10.10.10 上 运行,然后在完成后,在 10.10 上是 运行 .10.11.

我还需要做些什么来并行进行测试 运行 吗?

注意:我无法使用 fabfile,因为我要为每个测试主机发送不同的测试配置文件。

这是我会做的。不同主机的不同参数的技巧是向 env context_manager 添加信息,让您掌握任务的主机特定参数。只需确保主机与您用于字典的键相匹配,并行命令就可以正常工作。最后,fabric 中的任务通常是 运行 通过 fab 命令。我从未使用原生 python 脚本尝试过它,我不确定后果或是否需要进行任何特殊处理。 fabric 项目的典型格式是在名为 fabfile.py 的文件中定义任务,这些任务可以是 运行 使用 fab.

在名为 fabfile.py 的文件中:

from fabric.decorators import task, parallel
from fabric.operations import run
from fabric.context_managers import env

@task
def run_test(arg_list):
    # arg_list is a list of dictionary.  Each entry in
    # arg_list has a 'ip_address' and a 'test_config_file'
    env.hosts = [ x['ip_address'] for x in arg_list ]
    env.host_data = dict()
    for x in arg_list:
        env.host_data[x['ip_address']] = x
    execute(run_command)

@parallel
def run_command():
    context = env.host_data[env.host]
    cmd = '/root/test_localhost.py --ip_addr=%(ip_address)s --config=%(test_config_file)s' % context
    run(cmd)

@task 
def run_my_test():
    arg_list.append({'ip_address':'10.10.10.10', 'test_config_file': "config_01.json"})
    arg_list.append({'ip_address':'10.10.10.11', 'test_config_file': "config_02.json"})
    run_test(arg_list)

从命令行 运行:

fab run_my_test