本文整理汇总了Python中pysphere.vi_task.VITask类的典型用法代码示例。如果您正苦于以下问题:Python VITask类的具体用法?Python VITask怎么用?Python VITask使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VITask类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: delete_vm
def delete_vm(self, vm_name):
""" VMWareSystem implementation of delete_vm. """
if vm_name is None:
raise Exception('Could not find a VM named %s.' % vm_name)
else:
try:
vm = self.api.get_vm_by_name(vm_name)
except VIException as ex:
raise Exception(ex)
if vm.is_powered_on():
raise Exception('Could not stop %s because it\'s still running.' % vm_name)
else:
# When pysphere moves up to 0.1.8, we can just do:
# vm.destroy()
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
rtn = self.api._proxy.Destroy_Task(request)._returnval
task = VITask(rtn, self.api)
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_SUCCESS:
return True
return False
示例2: delete_vm
def delete_vm(vsphere_client, module, guest, vm, force):
try:
if vm.is_powered_on():
if force:
try:
vm.power_off(sync_run=True)
vm.get_status()
except Exception, e:
module.fail_json(
msg='Failed to shutdown vm %s: %s' % (guest, e))
else:
module.fail_json(
msg='You must use either shut the vm down first or '
'use force ')
# Invoke Destroy_Task
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
ret = vsphere_client._proxy.Destroy_Task(request)._returnval
task = VITask(ret, vsphere_client)
# Wait for the task to finish
status = task.wait_for_state(
[task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_ERROR:
vsphere_client.disconnect()
module.fail_json(msg="Error removing vm: %s %s" %
task.get_error_message())
module.exit_json(changed=True, changes="VM %s deleted" % guest)
示例3: add_existence_vmdk
def add_existence_vmdk(self, vm_name, path):
"""
Add existence hard drive (.vmdk) to the virtual machine
:param vm_name: virtual machine name
:param path: hard drive path
:param space: space for hard drive
:raise: ExistenceException, CreatorException
"""
self._connect_to_esx()
try:
vm = self.esx_server.get_vm_by_name(vm_name)
except Exception:
raise ExistenceException("Couldn't find the virtual machine %s" % vm_name)
unit_number = -1
for disk in vm._disks:
unit_number = max(unit_number, disk["device"]["unitNumber"])
unit_number += 1
request = VI.ReconfigVM_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
spec = request.new_spec()
dc = spec.new_deviceChange()
dc.Operation = "add"
hd = VI.ns0.VirtualDisk_Def("hd").pyclass()
hd.Key = -100
hd.UnitNumber = unit_number
hd.CapacityInKB = 0
hd.ControllerKey = 1000
backing = VI.ns0.VirtualDiskFlatVer2BackingInfo_Def("backing").pyclass()
backing.FileName = path
backing.DiskMode = "persistent"
backing.ThinProvisioned = False
hd.Backing = backing
connectable = hd.new_connectable()
connectable.StartConnected = True
connectable.AllowGuestControl = False
connectable.Connected = True
hd.Connectable = connectable
dc.Device = hd
spec.DeviceChange = [dc]
request.Spec = spec
task = self.esx_server._proxy.ReconfigVM_Task(request)._returnval
vi_task = VITask(task, self.esx_server)
# Wait for task to finis
status = vi_task.wait_for_state([vi_task.STATE_SUCCESS, vi_task.STATE_ERROR])
if status == vi_task.STATE_ERROR:
self._disconnect_from_esx()
raise CreatorException("ERROR CONFIGURING VM:%s" % vi_task.get_error_message())
示例4: destroy
def destroy(self, sync_run=True):
"""
Destroys this object, deleting its contents and removing it from its
parent folder (if any)
* sync_run: (default True), If False does not wait for the task to
finish and returns an instance of a VITask for the user to monitor
its progress
"""
try:
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(self._mor)
_this.set_attribute_type(self._mor.get_attribute_type())
request.set_element__this(_this)
task = self._server._proxy.Destroy_Task(request)._returnval
vi_task = VITask(task, self._server)
if sync_run:
status = vi_task.wait_for_state([vi_task.STATE_SUCCESS,
vi_task.STATE_ERROR])
if status == vi_task.STATE_ERROR:
raise VITaskException(vi_task.info.error)
return
return vi_task
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例5: delete_file
def delete_file(self, path, datacenter=None, sync_run=True):
"""Deletes the specified file or folder from the datastore.
If a file of a virtual machine is deleted, it may corrupt
that virtual machine. Folder deletes are always recursive.
"""
try:
request = VI.DeleteDatastoreFile_TaskRequestMsg()
_this = request.new__this(self._mor)
_this.set_attribute_type(self._mor.get_attribute_type())
request.set_element__this(_this)
request.set_element_name(path)
if datacenter:
request.set_element_datacenter(datacenter)
task = self._server._proxy.DeleteDatastoreFile_Task(request)._returnval
vi_task = VITask(task, self._server)
if sync_run:
status = vi_task.wait_for_state([vi_task.STATE_SUCCESS,
vi_task.STATE_ERROR])
if status == vi_task.STATE_ERROR:
raise VITaskException(vi_task.info.error)
return
return vi_task
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例6: destroy_vm
def destroy_vm(self, vmname):
"""
Destroys virtual machine by name
:param vmname: virtual machine name
:raise: ExistenceException, CreatorException
"""
self._connect_to_esx()
try:
vm = self.esx_server.get_vm_by_name(vmname)
except Exception as error:
self._disconnect_from_esx()
raise ExistenceException("Couldn't find VM '%s' - %s" % (vmname, error.message))
try:
if vm.is_powered_on() or vm.is_powering_off() or vm.is_reverting():
vm.power_off()
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
ret = self.esx_server._proxy.Destroy_Task(request)._returnval
# Wait for the task to finish
task = VITask(ret, self.esx_server)
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status != task.STATE_SUCCESS:
raise CreatorException("Couldn't destroy vm - " + task.get_error_message())
except Exception:
self._disconnect_from_esx()
raise CreatorException("Couldn't destroy the virtual machine %s" % vmname)
示例7: rename
def rename(self, new_name, sync_run=True):
"""
Renames this managed entity.
* new_name: Any / (slash), \ (backslash), character used in this name
element will be escaped. Similarly, any % (percent) character used
in this name element will be escaped, unless it is used to start an
escape sequence. A slash is escaped as %2F or %2f. A backslash is
escaped as %5C or %5c, and a percent is escaped as %25.
* sync_run: (default True), If False does not wait for the task to
finish and returns an instance of a VITask for the user to monitor
its progress
"""
try:
request = VI.Rename_TaskRequestMsg()
_this = request.new__this(self._mor)
_this.set_attribute_type(self._mor.get_attribute_type())
request.set_element__this(_this)
request.set_element_newName(new_name)
task = self._server._proxy.Rename_Task(request)._returnval
vi_task = VITask(task, self._server)
if sync_run:
status = vi_task.wait_for_state([vi_task.STATE_SUCCESS,
vi_task.STATE_ERROR])
if status == vi_task.STATE_ERROR:
raise VITaskException(vi_task.info.error)
return
return vi_task
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例8: register_vm
def register_vm(self, path, name=None, sync_run=True, folder=None,
template=False, resourcepool=None, host=None):
"""Adds an existing virtual machine to the folder.
@path: a datastore path to the virtual machine.
Example "[datastore] path/to/machine.vmx".
@name: the name to be assigned to the virtual machine.
If this parameter is not set, the displayName configuration
parameter of the virtual machine is used.
@sync_run: if True (default) waits for the task to finish, and returns
a VIVirtualMachine instance with the new VM (raises an exception if
the task didn't succeed). If @sync_run is set to False the task is
started and a VITask instance is returned
@folder_name: folder in which to register the virtual machine.
@template: Flag to specify whether or not the virtual machine
should be marked as a template.
@resourcepool: MOR of the resource pool to which the virtual machine should
be attached. If imported as a template, this parameter is not set.
@host: The target host on which the virtual machine will run. This
parameter must specify a host that is a member of the ComputeResource
indirectly specified by the pool. For a stand-alone host or a cluster
with DRS, the parameter can be omitted, and the system selects a default.
"""
if not folder:
folders = self._get_managed_objects(MORTypes.Folder)
folder = [_mor for _mor, _name in folders.iteritems()
if _name == 'vm'][0]
try:
request = VI.RegisterVM_TaskRequestMsg()
_this = request.new__this(folder)
_this.set_attribute_type(folder.get_attribute_type())
request.set_element__this(_this)
request.set_element_path(path)
if name:
request.set_element_name(name)
request.set_element_asTemplate(template)
if resourcepool:
pool = request.new_pool(resourcepool)
pool.set_attribute_type(resourcepool.get_attribute_type())
request.set_element_pool(pool)
if host:
if not VIMor.is_mor(host):
host = VIMor(host, MORTypes.HostSystem)
hs = request.new_host(host)
hs.set_attribute_type(host.get_attribute_type())
request.set_element_host(hs)
task = self._proxy.RegisterVM_Task(request)._returnval
vi_task = VITask(task, self)
if sync_run:
status = vi_task.wait_for_state([vi_task.STATE_SUCCESS,
vi_task.STATE_ERROR])
if status == vi_task.STATE_ERROR:
raise VITaskException(vi_task.info.error)
return
return vi_task
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例9: main
def main():
opts = options()
# CONNECTION PARAMTERS
server = opts.esx_host
user = opts.user
password = opts.passwd
# REQUIRED PARAMETERS
vmname = opts.name
# CONNECT TO THE SERVER
s = VIServer()
s.connect(server, user, password)
try:
vm = s.get_vm_by_name(opts.name)
vm.shutdown_guest()
count = 1
wait_for = 60
try:
while count < wait_for and vm.is_powered_off() == False:
count += 1
time.sleep(1)
print "Elapsed %s seconds ..." % str(count)
except Exception as e:
if count >= wait_for:
print "Failed to shutdown the VM (%s) even after %s seconds." % (vmname, str(wait_for))
print "Please login to the EXSi server and fix the issue. Exception: %s" % str(e)
sys.exit(1)
check_count(count, wait_for)
except Exception as e:
print "Failed to locate and shutdown the new VM using:", opts.name
print "VM could not be deleted."
print "Exception:", str(e)
# Invoke Destroy_Task
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
ret = s._proxy.Destroy_Task(request)._returnval
# Wait for the task to finish
task = VITask(ret, s)
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_SUCCESS:
print "VM successfully deleted from disk"
elif status == task.STATE_ERROR:
print "Error removing vm:", task.get_error_message()
# disconnect from the server
s.disconnect()
示例10: list_files
def list_files(self, path, case_insensitive=True,
folders_first=True, match_patterns=[]):
"""Return a list of files in folder @path
"""
ds_name, file_name = re.match(self._re_path, path).groups()
ds = [k for k,v in self._server.get_datastores().items() if v == ds_name][0]
browser_mor = VIProperty(self._server, ds).browser._obj
request = VI.SearchDatastore_TaskRequestMsg()
_this = request.new__this(browser_mor)
_this.set_attribute_type(browser_mor.get_attribute_type())
request.set_element__this(_this)
request.set_element_datastorePath(path)
search_spec = request.new_searchSpec()
query = [VI.ns0.FloppyImageFileQuery_Def('floppy').pyclass(),
VI.ns0.FileQuery_Def('file').pyclass(),
VI.ns0.FolderFileQuery_Def('folder').pyclass(),
VI.ns0.IsoImageFileQuery_Def('iso').pyclass(),
VI.ns0.VmConfigFileQuery_Def('vm').pyclass(),
VI.ns0.TemplateConfigFileQuery_Def('template').pyclass(),
VI.ns0.VmDiskFileQuery_Def('vm_disk').pyclass(),
VI.ns0.VmLogFileQuery_Def('vm_log').pyclass(),
VI.ns0.VmNvramFileQuery_Def('vm_ram').pyclass(),
VI.ns0.VmSnapshotFileQuery_Def('vm_snapshot').pyclass()]
search_spec.set_element_query(query)
details = search_spec.new_details()
details.set_element_fileOwner(True)
details.set_element_fileSize(True)
details.set_element_fileType(True)
details.set_element_modification(True)
search_spec.set_element_details(details)
search_spec.set_element_searchCaseInsensitive(case_insensitive)
search_spec.set_element_sortFoldersFirst(folders_first)
search_spec.set_element_matchPattern(match_patterns)
request.set_element_searchSpec(search_spec)
response = self._server._proxy.SearchDatastore_Task(request)._returnval
vi_task = VITask(response, self._server)
if vi_task.wait_for_state([vi_task.STATE_ERROR, vi_task.STATE_SUCCESS]) == vi_task.STATE_ERROR:
raise VITaskException(vi_task.info.error)
info = vi_task.get_result()
# return info
if not hasattr(info, "file"):
return []
# for fi in info.file:
# fi._get_all()
return [{'type':fi._type,
'path':fi.path,
'size':fi.fileSize,
'modified':fi.modification,
'owner':fi.owner
} for fi in info.file]
示例11: disconnect_vm_cdroms
def disconnect_vm_cdroms(vm, server):
connected_cdroms = []
for dev in vm.properties.config.hardware.device:
if dev._type == "VirtualCdrom":
# and dev.connectable.connected:
# if dev._type == "VirtualCdrom" and dev.connectable.startConnected:
d = dev._obj
try:
d.Connectable.set_element_connected(False)
d.Connectable.set_element_startConnected(False)
connected_cdroms.append(d)
except:
log(level="warning", msg="%s: no virtual cd roms found." %
vm.properties.name)
if not connected_cdroms:
log(level="info", msg="%s: has no connected cd roms" %
vm.properties.name)
return
request = VI.ReconfigVM_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
spec = request.new_spec()
dev_changes = []
for dev in connected_cdroms:
change_cdrom_type(dev, "CLIENT DEVICE")
dev_change = spec.new_deviceChange()
dev_change.set_element_device(dev)
dev_change.set_element_operation("edit")
dev_changes.append(dev_change)
spec.set_element_deviceChange(dev_changes)
request.set_element_spec(spec)
ret = server._proxy.ReconfigVM_Task(request)._returnval
# Wait for the task to finish
# Remove all this section if you don't wish to wait for the task to finish
task = VITask(ret, server)
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_SUCCESS:
log(level="info", msg="%s: successfully reconfigured" %
vm.properties.name)
elif status == task.STATE_ERROR:
log(level="error", msg="%s: Error reconfiguring vm" %
vm.properties.name)
示例12: apply_changes
def apply_changes(vm, server, cdrom):
request = VI.ReconfigVM_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
spec = request.new_spec()
dev_change = spec.new_deviceChange()
dev_change.set_element_device(cdrom)
dev_change.set_element_operation("edit")
spec.set_element_deviceChange([dev_change])
request.set_element_spec(spec)
ret = server._proxy.ReconfigVM_Task(request)._returnval
task = VITask(ret, server)
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_SUCCESS:
print "%s: successfully reconfigured" % vm.properties.name
elif status == task.STATE_ERROR:
print "%s: Error reconfiguring vm" % vm.properties.name
示例13: destroyGuest
def destroyGuest(host_con, guest_name):
powerOffGuest(host_con, guest_name)
try:
vm = host_con.get_vm_by_name(guest_name)
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
ret = host_con._proxy.Destroy_Task(request)._returnval
task = VITask(ret, host_con)
print 'Waiting for VM to be deleted'
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_SUCCESS:
result = 'Succesfully removed guest: %s' % guest_name
elif status == task.STATE_ERROR:
result = 'Failed to remove VM: %s\n%s' % (guest_name, task.get_error_message())
except Exception as e:
result = 'Failed to remove VM: %s\n%s' % (guest_name, str(e))
return result
示例14: delete_vm
def delete_vm(self, vm_name):
vm = self._get_vm(vm_name)
if vm.is_powered_on():
self.stop_vm(vm_name)
# When pysphere moves up to 0.1.8, we can just do:
# vm.destroy()
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
rtn = self.api._proxy.Destroy_Task(request)._returnval
task = VITask(rtn, self.api)
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_SUCCESS:
return True
else:
return False
示例15: handler_revert_to_snapshot
def handler_revert_to_snapshot(self, task_id, parameters):
vm_id = parameters['vm_id']
snapshot_id = parameters['snapshot_id']
vm_mor = VIMor(vm_id, MORTypes.VirtualMachine)
snapshot_mor = VIMor(snapshot_id, MORTypes.VirtualMachineSnapshot)
vm_properties_future = self.application.executor.submit(self.server._get_object_properties, vm_mor, ['name', 'snapshot'])
request = VI.RevertToSnapshot_TaskRequestMsg()
mor_snap = request.new__this(snapshot_mor)
mor_snap.set_attribute_type(snapshot_mor.get_attribute_type())
request.set_element__this(mor_snap)
vm_name = None
snapshot_name = None
vm_properties = yield vm_properties_future
for prop in vm_properties.PropSet:
if prop.Name == 'name':
vm_name = prop.Val
elif prop.Name == 'snapshot':
snapshot_dict = ActionHandler.build_snapshot_dict(prop.Val.RootSnapshotList)
snapshot_name = snapshot_dict[snapshot_mor].Name
TaskStatusHandler.update_task(task_id, 'Reverting {0} to {1}...'.format(vm_name, snapshot_name))
vi_task = self.server._proxy.RevertToSnapshot_Task(request)._returnval
vi_task = VITask(vi_task, self.server)
status = yield self.application.executor.submit(
vi_task.wait_for_state, [vi_task.STATE_SUCCESS,
vi_task.STATE_ERROR])
if status == vi_task.STATE_ERROR:
raise VIException(vi_task.get_error_message(),
FaultTypes.TASK_ERROR)
TaskStatusHandler.update_task(task_id, 'Successfully reverted {0} to {1}'.format(vm_name, snapshot_name))
TaskStatusHandler.delete_task(task_id)
self.send_vm_update(vm_id)