在 bash 中使用 xargs 进行并行处理

Hee*_*wal 5 python bash xargs openstack

我有一个小脚本,我可以在其中获取每个 openstack 的租户,并在 python 的帮助下获取一些输出。生成报告的时间太长,我被建议使用xargs. 我之前的代码如下所示。

#!/bin/bash
cd /scripts/cloud01/floating_list

rm -rf ./reports/openstack_reports/
mkdir -p ./reports/openstack_reports/

source ../creds/base
for tenant in A B C D E F G H I J K L M N O P Q R S T
do
  source ../creds/$tenant
  python ../tools/openstack_resource_list.py > ./reports/openstack_reports/$tenant.html

done
lftp -f ./lftp_script
Run Code Online (Sandbox Code Playgroud)

现在我已经将 xargs 放入脚本中,脚本看起来像这样。

#!/bin/bash
cd /scripts/cloud01/floating_list

rm -rf ./reports/openstack_reports/
mkdir -p ./reports/openstack_reports/

source ../creds/base

# Need xargs idea below
cat tenants_list.txt | xargs -P 8 -I '{}' # something that takes the tenant name and source
TENANT_NAME={}
python ../tools/openstack_resource_list.py > ./reports/openstack_reports/$tenant.html
lftp -f ./lftp_script
Run Code Online (Sandbox Code Playgroud)

在这个脚本中我应该如何实现source ../creds/$tenant?因为在处理每个租户的同时,也需要对其进行采购,我不确定如何将其包含在 xargs 中以进行并行执行。

tri*_*eee 2

xargs无法轻松运行 shell 函数...但它可以运行 shell。

# If the tenant names are this simple, don't put them in a file
printf '%s\n' {A..T} |
xargs -P 8 -I {} bash -c 'source ../creds/"$0"
      python ../tools/openstack_resource_list.py > ./reports/openstack_reports/"$0".html' {}
Run Code Online (Sandbox Code Playgroud)

有点模糊的是,后面的参数在脚本内部bash -c '...'被暴露出来。$0

如果您想将租户保留在文件中,xargs -a filename这是避免无用使用 的cat好方法,尽管它不能移植到所有xargs实现。(重定向xargs ... <filename显然是完全可移植的。)

为了提高效率,您可以重构脚本以循环尽可能多的参数:

printf '%s\n' {A..T} |
xargs -n 3 -P 8 bash -c 'for tenant; do
      source ../creds/"$tenant"
      python ../tools/openstack_resource_list.py > ./reports/openstack_reports/"$tenant".html
  done' _
Run Code Online (Sandbox Code Playgroud)

这将运行最多 8 个并行 shell 实例,每个实例最多分配 3 个租户(因此实际上只有 7 个实例),尽管参数数量很少,性能差异可能可以忽略不计。

因为我们现在实际上收到了一个参数列表,所以我们将_其作为要填充的值传递$0(只是因为它需要设置为某个值,以便正确获取真正的参数)。

如果source可能进行的修改并不总是保证在下一次迭代中被覆盖source(例如,某些租户具有需要为其他租户取消设置的变量?),这会使问题变得复杂,但如果您真的这样做,可能会发布一个单独的问题实际上需要帮助解决这个问题;或者只是退回到第一个变体,其中每个租户都在单独的 shell 实例中运行。