0

我当前的 for 循环会从 16 个虚拟机中逐个删除快照

for vmName in vmList:
    snapshots = vmServer.get_vm_by_name(vmName).get_snapshots()
    for i in range(len(snapshots)-3):
        snapshotName = snapshots[i].get_name()
        print "Deleting snapshot " + snapshotName + " of " + vmName
        vmServer.get_vm_by_name(vmName).delete_named_snapshot(snapshotName)

我需要并行运行它(所以它不会等待上一个工作完成来开始下一个)我试图应用“多处理”,这里是完整的代码:

import argparse
from pysphere import VIServer # Tested with vCenter Server 5.5.0 and pysphere package 0.1.7
from CONFIG import * # Contains username and password for vCenter connection, list of VM names to take snapshot
from multiprocessing.pool import ThreadPool as Pool

def purgeSnapshotStage(vmList):
    # Connect to vCenter
    vmServer = VIServer()
    vmServer.connect("VM_ADDRESS", username, password)

    snapshots = vmServer.get_vm_by_name(vmName).get_snapshots()
    for i in range(len(snapshots) - 3):
        snapshotName = snapshots[i].get_name()
        print "Deleting snapshot " + snapshotName + "   of VM:   " + vmName
        vmServer.get_vm_by_name(vmName).delete_named_snapshot(snapshotName)

    vmServer.disconnect()

# Get the environment to delete snapshot from command line
parser = argparse.ArgumentParser(description="Take snapshot of VMs for stage or stage2")
parser.add_argument('env', choices=("stage", "stage2", "stage3"), help="Valid value stage or stage2 or stage3")
env = parser.parse_args().env
vmList = globals()[env + "VmList"]

pool_size = 5  # your "parallelness"
pool = Pool(pool_size)

for vmName in vmList:
    pool.apply_async(purgeSnapshotStage, (vmList,))

pool.close()
pool.join()

但是有一个错误,因为它试图只对最后一个执行“删除”命令。没有找到关于多处理的好指南,也找不到如何调试它。需要帮助找出错误。

4

1 回答 1

0

你在这里有一个错误:

for vmName in vmList:
    pool.apply_async(purgeSnapshotStage, (vmList,))

它应该是:

for vmName in vmList:
    pool.apply_async(purgeSnapshotStage, (vmName,))

然后在你的函数头中你需要这个:

def purgeSnapshotStage(vmList):

然后,您的代码中可能还有其他错误。

一般来说:我怀疑并行化这可能会给您带来任何性能优势。您的瓶颈将是 vmware 服务器。同时启动多个删除作业不会更快。

于 2017-02-04T11:19:12.130 回答