XenServer Software Development Kit Guide 4.1.0
Using the API
20
import sys, time
import XenAPI
Next the commandline arguments containing a server URL, username, password and a number of iterations
are parsed. The username and password are used to establish a session which is passed to the function
main, which is called multiple times in a loop. Note the use of try: finally: to make sure the program
logs out of its session at the end.
if __name__ == "__main__":
if len(sys.argv) <> 5:
print "Usage:"
print sys.argv[0], " <url> <username> <password> <iterations>"
sys.exit(1)
url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
iterations = int(sys.argv[4])
# First acquire a valid session by logging in:
session = XenAPI.Session(url)
session.xenapi.login_with_password(username, password)
try:
for i in range(iterations):
main(session, i)
finally:
session.xenapi.session.logout()
The main function examines each running VM in the system, taking care to filter out control domains (which
are part of the system and not controllable by the user). A list of running VMs and their current hosts is
constructed.
def main(session, iteration):
# Find a non-template VM object
all = session.xenapi.VM.get_all()
vms = []
hosts = []
for vm in all:
record = session.xenapi.VM.get_record(vm)
if not(record["is_a_template"]) and \
not(record["is_control_domain"]) and \
record["power_state"] == "Running":
vms.append(vm)
hosts.append(record["resident_on"])
print "%d: Found %d suitable running VMs" % (iteration, len(vms))
Next the list of hosts is rotated:










