本文整理汇总了Python中pysphere.vi_mor.VIMor类的典型用法代码示例。如果您正苦于以下问题:Python VIMor类的具体用法?Python VIMor怎么用?Python VIMor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VIMor类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_vapp_by_name
def get_vapp_by_name(self, name, datacenter=None, from_mor=None):
"""
Returns an instance of VIVApp. Where its name matches @name.
The vApp is searched throughout all the datacenters, unless the name or
MOR of the datacenter the vApp belongs to is provided. The first instance
matching @name is returned. If @from_mor, datacenter is ignored.
NOTE: As names might be duplicated is recommended to use get_vm_by_path
instead.
"""
if not self.__logged:
raise VIException("Must call 'connect' before invoking this method",
FaultTypes.NOT_CONNECTED)
try:
nodes = [None, ]
if from_mor and VIMor.is_mor(from_mor):
nodes = [from_mor, ]
else:
if datacenter and VIMor.is_mor(datacenter):
nodes = [datacenter]
elif datacenter:
dc = self.get_datacenters()
nodes = [k for k, v in dc.iteritems() if v == datacenter]
for node in nodes:
vms = self._get_managed_objects(MORTypes.VirtualApp,
from_mor=node)
for k, v in vms.iteritems():
if v == name:
return VIVApp(self, k)
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例2: handler_delete_snapshot
def handler_delete_snapshot(self, task_id, parameters):
snapshot_id = parameters['snapshot_id']
vm_id = parameters['vm_id']
snapshot_mor = VIMor(snapshot_id, MORTypes.VirtualMachineSnapshot)
request = VI.RemoveSnapshot_TaskRequestMsg()
mor_snap = request.new__this(snapshot_mor)
mor_snap.set_attribute_type(snapshot_mor.get_attribute_type())
request.set_element__this(mor_snap)
request.set_element_removeChildren(False)
TaskStatusHandler.update_task(task_id, 'Starting background task...')
task = (yield self.application.executor.submit(self.server._proxy.RemoveSnapshot_Task, request))._returnval
TaskStatusHandler.update_task(task_id, 'Background task started, waiting for completion...')
vi_task = yield self.application.executor.submit(VITask, 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, 'Snapshot deleted')
TaskStatusHandler.delete_task(task_id)
self.send_vm_update(vm_id)
示例3: 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)
示例4: _create_filter
def _create_filter(self, property_names=[],
from_node=None, obj_type='ManagedEntity', partial_updates=True):
"""Creates filter with given parameters and returns its MOR"""
try:
if not from_node:
from_node = self._do_service_content.RootFolder
elif isinstance(from_node, tuple) and len(from_node) == 2:
from_node = VIMor(from_node[0], from_node[1])
elif not VIMor.is_mor(from_node):
raise VIException("from_node must be a MOR object or a "
"(<str> mor_id, <str> mor_type) tuple",
FaultTypes.PARAMETER_ERROR)
request = VI.CreateFilterRequestMsg()
_this = request.new__this(self._do_service_content.PropertyCollector)
_this.set_attribute_type(MORTypes.PropertyCollector)
request.set_element__this(_this)
request.set_element_partialUpdates(partial_updates)
spec = request.new_spec()
propSet = spec.new_propSet()
propSet.set_element_type(obj_type)
propSet.set_element_pathSet(property_names)
spec.set_element_propSet([propSet])
objects_set = self._get_traversal_objects_set(spec, from_node)
spec.set_element_objectSet(objects_set)
request.set_element_spec(spec)
mor = self._proxy.CreateFilter(request)._returnval
return mor
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例5: get_datastore_by_name
def get_datastore_by_name(self, name, datacenter=None):
"""
Returns an instance of VIDatastore, where its name matches @name.
The datastore is searched throughout all the datacenters, unless the
name or the MOR of the datacenter (the datastore belongs to) is given.
The first instance matching @name is returned.
"""
if not self.__logged:
raise VIException("Must call 'connect' before invoking this method",
FaultTypes.NOT_CONNECTED)
try:
if datacenter:
if VIMor.is_mor(datacenter):
nodes = [datacenter]
else:
dc = self.get_datacenters()
nodes = [(k,v) for k,v in dc.iteritems() if v == datacenter]
else:
nodes = self.get_datacenters().iteritems()
# todo: use self.get_datastores() instead, if possible
for node in nodes:
datacenter_mor, datacenter_name = node
datastores = self._get_managed_objects(MORTypes.Datastore,
from_mor=datacenter_mor)
for k,v in datastores.iteritems():
if v == name:
return VIDatastore(self, datacenter_name, v)
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例6: handler_create_snapshot
def handler_create_snapshot(self, task_id, parameters):
vm_id = parameters['vm_id']
snapshot_name = parameters['snapshot_name']
snapshot_description = parameters['snapshot_description']
vm_mor = VIMor(vm_id, MORTypes.VirtualMachine)
request = VI.CreateSnapshot_TaskRequestMsg()
mor_vm = request.new__this(vm_mor)
mor_vm.set_attribute_type(vm_mor.get_attribute_type())
request.set_element__this(mor_vm)
request.set_element_name(snapshot_name)
if snapshot_description:
request.set_element_description(snapshot_description)
request.set_element_memory(True)
request.set_element_quiesce(False)
vi_task = self.server._proxy.CreateSnapshot_Task(request)._returnval
vi_task = VITask(vi_task, self.server)
state = None
while state not in (vi_task.STATE_SUCCESS, vi_task.STATE_ERROR):
time.sleep(1)
state = yield self.application.executor.submit(vi_task.get_state)
progress = yield self.application.executor.submit(vi_task.get_progress)
progress = progress or 100
TaskStatusHandler.update_task(task_id, 'Creating snapshot %s, %d%%...' % (snapshot_name, progress))
if state == vi_task.STATE_ERROR:
error_message = yield self.application.executor.submit(vi_task.get_error_message)
TaskStatusHandler.update_task(task_id, 'Error creating snapshot {0}: {1}'.format(
snapshot_name, error_message))
TaskStatusHandler.delete_task(task_id)
raise Exception(error_message)
TaskStatusHandler.update_task(task_id, 'Snapshot %s created!' % (snapshot_name,))
TaskStatusHandler.delete_task(task_id)
self.send_vm_update(vm_id)
示例7: 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)
示例8: _retrieve_properties_traversal
def _retrieve_properties_traversal(self, property_names=[],
from_node=None, obj_type='ManagedEntity'):
"""Uses VI API's property collector to retrieve the properties defined
in @property_names of Managed Objects of type @obj_type ('ManagedEntity'
by default). Starts the search from the managed object reference
@from_node (RootFolder by default). Returns the corresponding
objectContent data object."""
try:
if not from_node:
from_node = self._do_service_content.RootFolder
elif isinstance(from_node, tuple) and len(from_node) == 2:
from_node = VIMor(from_node[0], from_node[1])
elif not VIMor.is_mor(from_node):
raise VIException("from_node must be a MOR object or a "
"(<str> mor_id, <str> mor_type) tuple",
FaultTypes.PARAMETER_ERROR)
request, request_call = self._retrieve_property_request()
_this = request.new__this(
self._do_service_content.PropertyCollector)
_this.set_attribute_type(MORTypes.PropertyCollector)
request.set_element__this(_this)
do_PropertyFilterSpec_specSet = request.new_specSet()
props_set = []
do_PropertySpec_propSet = do_PropertyFilterSpec_specSet.new_propSet()
do_PropertySpec_propSet.set_element_type(obj_type)
do_PropertySpec_propSet.set_element_pathSet(property_names)
props_set.append(do_PropertySpec_propSet)
objects_set = self._get_traversal_objects_set(do_PropertyFilterSpec_specSet, from_node)
do_PropertyFilterSpec_specSet.set_element_propSet(props_set)
do_PropertyFilterSpec_specSet.set_element_objectSet(objects_set)
request.set_element_specSet([do_PropertyFilterSpec_specSet])
return request_call(request)
except (VI.ZSI.FaultException), e:
raise VIApiException(e)
示例9: _get_vm_for_uuid
def _get_vm_for_uuid(self, uuid, datacenter=None):
"""
Retrieve VM for the provided UUID.
:type uuid: ``str``
"""
server = self.connection.client
dc_list = []
if datacenter and VIMor.is_mor(datacenter):
dc_list.append(datacenter)
else:
dc = server.get_datacenters()
if datacenter:
dc_list = [k for k, v in dc.iteritems() if v == datacenter]
else:
dc_list = list(dc.iterkeys())
for mor_dc in dc_list:
request = VI.FindByUuidRequestMsg()
search_index = server._do_service_content.SearchIndex
mor_search_index = request.new__this(search_index)
mor_search_index.set_attribute_type(MORTypes.SearchIndex)
request.set_element__this(mor_search_index)
mor_datacenter = request.new_datacenter(mor_dc)
mor_datacenter.set_attribute_type(MORTypes.Datacenter)
request.set_element_datacenter(mor_datacenter)
request.set_element_vmSearch(True)
request.set_element_uuid(uuid)
try:
vm = server._proxy.FindByUuid(request)._returnval
except VI.ZSI.FaultException:
pass
else:
if vm:
return VIVirtualMachine(server, vm)
return None
示例10: get_vm_by_path
def get_vm_by_path(self, path, datacenter=None):
"""Returns an instance of VIVirtualMachine. Where its path matches
@path. The VM is searched througout all the datacenters, unless the
name or MOR of the datacenter the VM belongs to is provided."""
if not self.__logged:
raise VIException("Must call 'connect' before invoking this method",
FaultTypes.NOT_CONNECTED)
try:
dc_list = []
if datacenter and VIMor.is_mor(datacenter):
dc_list.append(datacenter)
else:
dc = self.get_datacenters()
if datacenter:
dc_list = [k for k,v in dc.items() if v==datacenter]
else:
dc_list = list(dc.keys())
for mor_dc in dc_list:
request = VI.FindByDatastorePathRequestMsg()
mor_search_index = request.new__this(
self._do_service_content.SearchIndex)
mor_search_index.set_attribute_type(MORTypes.SearchIndex)
request.set_element__this(mor_search_index)
mor_datacenter = request.new_datacenter(mor_dc)
mor_datacenter.set_attribute_type(MORTypes.Datacenter)
request.set_element_datacenter(mor_datacenter)
request.set_element_path(path)
try:
vm = self._proxy.FindByDatastorePath(request)._returnval
except VI.ZSI.FaultException:
pass
else:
if vm:
return VIVirtualMachine(self, vm)
except (VI.ZSI.FaultException) as e:
raise VIApiException(e)
raise VIException("Could not find a VM with path '%s'" % path,
FaultTypes.OBJECT_NOT_FOUND)
示例11: _retrieve_properties_traversal
def _retrieve_properties_traversal(self, property_names=[],
from_node=None, obj_type='ManagedEntity'):
"""Uses VI API's property collector to retrieve the properties defined
in @property_names of Managed Objects of type @obj_type ('ManagedEntity'
by default). Starts the search from the managed object reference
@from_node (RootFolder by default). Returns the corresponding
objectContent data object."""
try:
if not from_node:
from_node = self._do_service_content.RootFolder
elif isinstance(from_node, tuple) and len(from_node) == 2:
from_node = VIMor(from_node[0], from_node[1])
elif not VIMor.is_mor(from_node):
raise VIException("from_node must be a MOR object or a "
"(<str> mor_id, <str> mor_type) tuple",
FaultTypes.PARAMETER_ERROR)
request, request_call = self._retrieve_property_request()
_this = request.new__this(
self._do_service_content.PropertyCollector)
_this.set_attribute_type(MORTypes.PropertyCollector)
request.set_element__this(_this)
do_PropertyFilterSpec_specSet = request.new_specSet()
props_set = []
do_PropertySpec_propSet =do_PropertyFilterSpec_specSet.new_propSet()
do_PropertySpec_propSet.set_element_type(obj_type)
do_PropertySpec_propSet.set_element_pathSet(property_names)
props_set.append(do_PropertySpec_propSet)
objects_set = []
do_ObjectSpec_objSet = do_PropertyFilterSpec_specSet.new_objectSet()
mor_obj = do_ObjectSpec_objSet.new_obj(from_node)
mor_obj.set_attribute_type(from_node.get_attribute_type())
do_ObjectSpec_objSet.set_element_obj(mor_obj)
do_ObjectSpec_objSet.set_element_skip(False)
#Recurse through all ResourcePools
rp_to_rp = VI.ns0.TraversalSpec_Def('rpToRp').pyclass()
rp_to_rp.set_element_name('rpToRp')
rp_to_rp.set_element_type(MORTypes.ResourcePool)
rp_to_rp.set_element_path('resourcePool')
rp_to_rp.set_element_skip(False)
rp_to_vm= VI.ns0.TraversalSpec_Def('rpToVm').pyclass()
rp_to_vm.set_element_name('rpToVm')
rp_to_vm.set_element_type(MORTypes.ResourcePool)
rp_to_vm.set_element_path('vm')
rp_to_vm.set_element_skip(False)
spec_array_resource_pool = [do_ObjectSpec_objSet.new_selectSet(),
do_ObjectSpec_objSet.new_selectSet()]
spec_array_resource_pool[0].set_element_name('rpToRp')
spec_array_resource_pool[1].set_element_name('rpToVm')
rp_to_rp.set_element_selectSet(spec_array_resource_pool)
#Traversal through resource pool branch
cr_to_rp = VI.ns0.TraversalSpec_Def('crToRp').pyclass()
cr_to_rp.set_element_name('crToRp')
cr_to_rp.set_element_type(MORTypes.ComputeResource)
cr_to_rp.set_element_path('resourcePool')
cr_to_rp.set_element_skip(False)
spec_array_computer_resource =[do_ObjectSpec_objSet.new_selectSet(),
do_ObjectSpec_objSet.new_selectSet()]
spec_array_computer_resource[0].set_element_name('rpToRp');
spec_array_computer_resource[1].set_element_name('rpToVm');
cr_to_rp.set_element_selectSet(spec_array_computer_resource)
#Traversal through host branch
cr_to_h = VI.ns0.TraversalSpec_Def('crToH').pyclass()
cr_to_h.set_element_name('crToH')
cr_to_h.set_element_type(MORTypes.ComputeResource)
cr_to_h.set_element_path('host')
cr_to_h.set_element_skip(False)
#Traversal through hostFolder branch
dc_to_hf = VI.ns0.TraversalSpec_Def('dcToHf').pyclass()
dc_to_hf.set_element_name('dcToHf')
dc_to_hf.set_element_type(MORTypes.Datacenter)
dc_to_hf.set_element_path('hostFolder')
dc_to_hf.set_element_skip(False)
spec_array_datacenter_host = [do_ObjectSpec_objSet.new_selectSet()]
spec_array_datacenter_host[0].set_element_name('visitFolders')
dc_to_hf.set_element_selectSet(spec_array_datacenter_host)
#Traversal through vmFolder branch
dc_to_vmf = VI.ns0.TraversalSpec_Def('dcToVmf').pyclass()
dc_to_vmf.set_element_name('dcToVmf')
dc_to_vmf.set_element_type(MORTypes.Datacenter)
dc_to_vmf.set_element_path('vmFolder')
dc_to_vmf.set_element_skip(False)
spec_array_datacenter_vm = [do_ObjectSpec_objSet.new_selectSet()]
spec_array_datacenter_vm[0].set_element_name('visitFolders')
dc_to_vmf.set_element_selectSet(spec_array_datacenter_vm)
#Traversal through datastore branch
#.........这里部分代码省略.........
示例12: get_registered_vms
def get_registered_vms(self, datacenter=None, cluster=None,
resource_pool=None, status=None,
advanced_filters=None):
"""Returns a list of VM Paths.
@datacenter: name or MORs to filter VMs registered in that datacenter
@cluster: name or MORs to filter VMs registered in that cluster. If set
datacenter is ignored.
@resource_pool: name path or MORs to filter VMs registered in that
resource pool. If set, both, @datacenter and @cluster are ignored.
@status: either 'poweredOn', 'poweredOff', or 'suspended' to retrieve
only VMs in that power state
@advanced_filters: dictionary
"""
if not self.__logged:
raise VIException("Must call 'connect' before invoking this method",
FaultTypes.NOT_CONNECTED)
try:
if not advanced_filters or not isinstance(advanced_filters, dict):
advanced_filters={}
if status:
advanced_filters['runtime.powerState'] = [status]
property_filter = list(advanced_filters.iterkeys())
if not 'config.files.vmPathName' in property_filter:
property_filter.insert(0, 'config.files.vmPathName')
#Root MOR filters
ret = []
nodes = [None]
if resource_pool and VIMor.is_mor(resource_pool):
nodes = [resource_pool]
elif resource_pool:
nodes = [k for k,v in self.get_resource_pools().iteritems()
if v==resource_pool]
elif cluster and VIMor.is_mor(cluster):
nodes = [cluster]
elif cluster:
nodes = [k for k,v in self.get_clusters().iteritems()
if v==cluster]
elif datacenter and VIMor.is_mor(datacenter):
nodes = [datacenter]
elif datacenter:
nodes = [k for k,v in self.get_datacenters().iteritems()
if v==datacenter]
for node in nodes:
obj_content = self._retrieve_properties_traversal(
property_names=property_filter,
from_node=node,
obj_type=MORTypes.VirtualMachine)
if not obj_content:
continue
for obj in obj_content:
try:
prop_set = obj.PropSet
except AttributeError:
continue
ppath = None
filter_match = dict([(k, False)
for k in advanced_filters.iterkeys()])
for item in prop_set:
if item.Name == 'config.files.vmPathName':
ppath = item.Val
elif item.Name in filter_match:
expected = advanced_filters.get(item.Name)
if not isinstance(expected, list):
expected = [expected]
if item.Val in expected:
filter_match[item.Name] = True
if all(filter_match.values()):
ret.append(ppath)
return ret
except (VI.ZSI.FaultException), e:
raise VIApiException(e)