psphere documentation contents¶
Introduction¶
This is the documentation for psphere, native Python bindings for the vSphere Web Services SDK/VMware Infrastructure SDK.
Notes¶
psphere implements the following VMware SDKs:
- VMware Infrastructure SDK 2.5
- VMware vSphere Web Services SDK 4.0 and later
I’m currently developing against vCenter 4.1 so please raise any bugs for other versions.
See the vSphere Web Services SDK Documentation for further information on VMware SDKs at http://www.vmware.com/support/developer/vc-sdk/.
Installing psphere¶
# pip install -U psphere
Developing psphere¶
If you want to use the latest development branch:
$ git clone https://github.com/jkinred/psphere
$ cd psphere
$ sudo python setup.py install
$ ./examples/connect.py --server yourserver.esx.com --username youruser --password yourpass
Successfully connected to https://yourserver.esx.com/sdk
Server time is 2010-09-05 00:14:06.037575
Usage¶
See First steps with psphere for an introductory tutorial. It also contains links to more advanced sections in this manual.
Examples¶
First steps with psphere¶
This document is meant to give a tutorial-like overview of the main psphere objects and the common tasks that psphere is used for.
The green arrows designate “more info” links leading to more detailed sections about the described task.
Vendor documentation¶
VMware provides very good documentation for the VMware vSphere API. It is suggested that you at least read the introductory documents to gain a conceptual understanding of the API.
Throughout this documentation there are links to the API reference documentation.
See useful references.
The Client object¶
The Client object is the entry point into psphere. Through it you can login to a vSphere server and obtain Python objects representing managed objects. You can then access information about and execute methods on those objects.
Read more about the Vim attributes and methods.
Hello World in psphere¶
Not quite, but logging into the server and printing the current time is close:
>>> from psphere.client import Client
>>> client = Client("your.esxserver.com", "Administrator", "strongpass")
>>> servertime = client.si.CurrentTime()
>>> print(servertime)
2010-09-04 18:35:12.062575
>>> client.logout()
General programming pattern¶
Create a new Client:
>>> from psphere.client import Client
>>> client = Client("your.esxserver.com", "Administrator", "strongpass")
...check out the rootFolder of the content attribute, it’s a Python object:
>>> client.si.content.rootFolder.__class__
<class 'psphere.managedobjects.Folder'>
...access properties of it:
>>> print(client.si.content.rootFolder.name)
Datacenters
...invoke a method:
>>> new_folder = client.si.content.rootFolder.CreateFolder(name="New")
>>> print(new_folder.name)
New
>>> task = new_folder.Destroy_Task()
>>> print(task.info.state)
success
...log out of the server:
>>> client.logout()
Finding a ManagedEntity¶
Managed Object’s which extend the ManagedEntity class are the most commonly used objects in the vSphere API. These include Managed Object’s such as HostSystem’s and VirtualMachine’s.
psphere makes it easy to find Managed Entity’s by providing a get() classmethod to find them:
>>> from psphere.client import Client
>>> from psphere.managedobjects import VirtualMachine
>>> client = Client("your.esxserver.com", "Administrator", "strongpass")
>>> vm = VirtualMachine.get(client, name="genesis")
>>> vm.__class__
<class 'psphere.managedobjects.VirtualMachine'>
>>> vm.name
bennevis
>>> vm.summary.guest.ipAddress
10.183.11.85
>>> vm.config.hardware.memoryMB
4096
There is also the all() method to get all entities of that type:
>>> vms = VirtualMachine.all(client)
Lazy loading of properties and pre-loading properties¶
At this point we have to delve into a more complicated aspect of vSphere and how psphere handles it. You do not need to worry about this, psphere will just work for you – albeit inefficiently in some cases.
The vSphere SDK architecture provides abstract “views” of server side objects, some of these objects can be quite substantial, both in size and server resources required to collect them.
If you retrieve substantial objects then your scripts will be slow and you will generate load on your vSphere server.
psphere deals with this by lazily loading objects on access. In most cases this is fine, but you can achieve substantial speed-ups – especially for lists of managed objects – by pre-loading objects you know that you are going to access.
For example, a HostSystem has a “vm” property which is a list of VirtualMachine objects on that host. If you know you are going to loop over all those VM’s and print their name, you can preload the name property using the preload method:
>>> hs = HostSystem.get(client, name="myhost")
>>> hs.preload("vm", properties=["name"])
>>> for vm in hs.vm:
>>> print(vm.name)
>>> ...
Caching¶
Once lazily loaded or pre-loaded, attributes will be cached for a pre-defined time (5 minutes, which is not configurable but will be in the next release).
To update the cache for a specific property of an object, use the update() method with the properties parameter:
>>> hs.update(properties=["name"])
To update the cache for all cached properties of an object, use the update() method with no parameters:
>>> hs.update()
To clear the property cache for an object, use the flush_cache() method:
>>> hs.flush_cache()
Error handling¶
At time of writing, the vSphere SDK raises 435 types of exception. Rather than duplicate these in psphere, the API instead raises a single fault called VimFault when any vSphere related fault is detected. The VimFault exception contains the following attributes:
- fault: The fault object
- fault_type: The class name of the fault (the name you will find in the vSphere documentation)
All other properties which are listed in the API reference will be available as attributes of the fault object.
Handling exceptions¶
>>> try:
>>> operation()
>>> except VimFault, e:
>>> e.fault_code
InvalidProperty
>>> e.fault.name
name
Datastore examples¶
WARNING!!!! Not updated for new API!
This page provides examples for working with datastores.
Finding a datastore¶
You can find a datastore in a ComputeResource using the find_datastore convenience method:
>>> from psphere.client import Client
>>> from psphere.managedobjects import Datastore
>>> client = Client("server.esx.com", "Administrator", "strongpass")
>>> datastore = Datastore.get(name="nas03")
>>> print(datastore.summary.name)
nas03
>>> print("%iGB" % (datastore.summary.freeSpace/1073741824))
13203GB
Finding all VMs attached to a datastore¶
Just look at the vm property of the Datastore managed object:
>>> for vm in datastore.vm:
>>> try:
>>> print(vm.name)
>>> print(vm.summary.config.guestId)
>>> except AttributeError:
>>> print("Unknown")
>>> print("----------")
sdi3extapp01
sles10_64Guest
----------
sdi3ppcapp01
sles10_64Guest
----------
sdi3oamapp01
sles10_64Guest
----------
hudmas01
rhel5Guest
----------
sandbox5
rhel5Guest
----------
HostSystem examples¶
This page provides examples for working with HostSystem views. The examples accumulate as they go so make sure you reference the previous examples.
Finding a single HostSystem by name¶
Connect to the server and find the HostSystem view:
>>> from psphere.client import Client
>>> from psphere.managedobjects import HostSystem
>>> client = Client("server.esx.com", "Administrator", "strongpass")
>>> hs = HostSystem.get(client, name="k2")
>>> print(hs.name)
k2
>>> print(hs.summary.hardware.model)
Sun Fire X4440
Finding all HostSystem’s¶
Use the .all() method which can be found on all objects extending ManagedEntity:
>>> hs_list = HostSystem.all(client)
>>> len(hs_list)
3
>>> for hs in hs_list:
>>> print(hs.name)
host1
host2
host3
How many VirtualMachine’s on a HostSystem?¶
Just count the number of VirtualMachine‘s objects in the vm property:
>>> len(host_system.vm)
40
Listing VirtualMachine’s on a HostSystem¶
The HostSystem.vm attribute contains a list of VirtualMachine objects.
>>> for vm in host_system.vm:
>>> try:
>>> print(vm.name)
>>> print(vm.summary.config.memorySizeMB)
>>> except AttributeError:
>>> print('No value')
>>> print('---------')
genesis
2048
---------
sdv1sdfsas04
'No value'
---------
pelmo
4096
---------
sdi2brmapp01
4096
---------
ssi5oamapp01
4096
---------
twynam
1024
---------
API Documentation¶
This page documents the psphere API.
psphere.client
- A client for communicating with a vSphere server¶
The main module for accessing a vSphere server.
Module author: Jonathan Kinred <jonathan.kinred@gmail.com>
-
class
psphere.client.
Client
(server=None, username=None, password=None, wsdl_location='local', timeout=30, plugins=[])¶ A client for communicating with a VirtualCenter/ESX/ESXi server
>>> from psphere.client import Client >>> Client = Client(server="esx.foo.com", username="me", password="pass")
Parameters: - server (str) – The server of the server. e.g. https://esx.foo.com/sdk
- username (str) – The username to connect with
- password (str) – The password to connect with
- wsdl_location (The string “local” (default) or “remote”) – Whether to use the provided WSDL or load the server WSDL
- timeout (int (default=30)) – The timeout to use when connecting to the server
- plugins (list of classes) – The plugins classes that will be used to process messages before send them to the web service
-
create
(type_, **kwargs)¶ Create a SOAP object of the requested type.
>>> client.create('VirtualE1000')
Parameters: - type (str) – The type of SOAP object to create.
- kwargs (TODO) – TODO
-
find_entity_view
(view_type, begin_entity=None, filter={}, properties=None)¶ Find a ManagedEntity of the requested type.
Traverses the MOB looking for an entity matching the filter.
Parameters: - view_type (str) – The type of ManagedEntity to find.
- begin_entity (ManagedObjectReference or None) – The MOR to start searching for the entity. The default is to start the search at the root folder.
- filter (dict) – Key/value pairs to filter the results. The key is a valid parameter of the ManagedEntity type. The value is what that parameter should match.
Returns: If an entity is found, a ManagedEntity matching the search.
Return type: ManagedEntity
-
find_entity_views
(view_type, begin_entity=None, properties=None)¶ Find all ManagedEntity’s of the requested type.
Parameters: - view_type (str) – The type of ManagedEntity’s to find.
- begin_entity (ManagedObjectReference or None) – The MOR to start searching for the entity. The default is to start the search at the root folder.
Returns: A list of ManagedEntity’s
Return type: list
-
get_search_filter_spec
(begin_entity, property_spec)¶ Build a PropertyFilterSpec capable of full inventory traversal.
By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity.
Parameters: - begin_entity (ManagedEntity) – The place in the MOB to start the search.
- property_spec (TODO) – TODO
Returns: A PropertyFilterSpec, suitable for recursively searching under the given ManagedEntity.
Return type: PropertyFilterSpec
-
get_view
(mo_ref, properties=None)¶ Get a view of a vSphere managed object.
Parameters: - mo_ref (ManagedObjectReference) – The MOR to get a view of
- properties (list) – A list of properties to retrieve from the server
Returns: A view representing the ManagedObjectReference.
Return type: ManagedObject
-
get_views
(mo_refs, properties=None)¶ Get a list of local view’s for multiple managed objects.
Parameters: - mo_refs (ManagedObjectReference) – The list of ManagedObjectReference’s that views are to be created for.
- properties (list) – The properties to retrieve in the views.
Returns: A list of local instances representing the server-side managed objects.
Return type: list of ManagedObject’s
-
invoke
(method, _this, **kwargs)¶ Invoke a method on the server.
>>> client.invoke('CurrentTime', client.si)
Parameters: - method (str) – The method to invoke, as found in the SDK.
- _this (ManagedObject) – The managed object reference against which to invoke the method.
- kwargs (TODO) – The arguments to pass to the method, as found in the SDK.
-
invoke_task
(method, **kwargs)¶ Execute a *_Task method and wait for it to complete.
Parameters: - method (str) – The *_Task method to invoke.
- kwargs (TODO) – The arguments to pass to the method.
-
login
(username=None, password=None)¶ Login to a vSphere server.
>>> client.login(username='Administrator', password='strongpass')
Parameters: - username (str) – The username to authenticate as.
- password (str) – The password to authenticate with.
-
logout
()¶ Logout of a vSphere server.