2.3.2.3. 添加

添加 方法向集合添加新元素。它们收到描述要添加的对象的相关类型实例,发送请求来添加它,以及返回描述添加对象的类型实例。

添加新虚拟机

# Add the virtual machine:
vm = vms_service.add(
  OvirtSDK4::Vm.new(
    name: 'myvm',
    cluster: {
      name: 'mycluster'
    },
    template: {
      name: 'mytemplate'
    }
  )
)

重要

add 方法返回的 Ruby 对象是相关类型的实例。它并不是一个服务,只是一个数据容器。在上例中,返回的对象是 Vm 类的实例。

如果您需要对刚添加的虚拟机执行操作,您必须找到管理该服务并调用服务 locator:

启动新的虚拟机

# Add the virtual machine:
vm = vms_service.add(
  ...
)

# Find the service that manages the virtual machine:
vm_service = vms_service.vm_service(vm.id)

# Start the virtual machine:
vm_service.start

大多数对象的创建都是异步任务。例如,如果您创建新虚拟机,则添加 方法将在虚拟机完全创建并准备好使用前返回虚拟机。您应该轮询对象的状态,直到对象完全创建。对于表示处于 DOWN 状态之前检查的虚拟机。

推荐的方法是创建虚拟机,找到管理新虚拟机的服务,并重复检索到虚拟机状态为 DOWN,这表示已创建所有磁盘。

添加虚拟机、循环服务并检索到它的状态

# Add the virtual machine:
vm = vms_service.add(
  ...
)

# Find the service that manages the virtual machine:
vm_service = vms_service.vm_service(vm.id)

# Wait until the virtual machine is DOWN, indicating that all the
# disks have been created:
loop do
  sleep(5)
  vm = vm_service.get
  break if vm.status == OvirtSDK4::VmStatus::DOWN
end

如果无法创建对象,则 SDK 将生成包含失败详情的 Error 异常。它永远不会返回 nil