ia64/xen-unstable

changeset 12104:d147be77861d

[XENAPI] Example tools to create/destroy/shutdown VMs

Example Session:

xapi.py vm-list
xapi.py host-info
xapi.py vm-create xapi.domcfg.py
xapi.py vbd-create GentooAPI xapi.vbdcfg.py
xapi.py vif-create GentooAPI xapi.vifcfg.py
xapi.py vm-start GentooAPI
xapi.py vm-shutdown GentooAPI
xapi.py vm-delete xapi.py

signed-off-by: Alastair Tse <atse@xensource.com>
author Alastair Tse <atse@xensource.com>
date Fri Oct 06 11:48:21 2006 +0100 (2006-10-06)
parents c383cb0945a7
children 52f449c9dcc5
files tools/python/scripts/xapi.domcfg.py tools/python/scripts/xapi.py tools/python/scripts/xapi.vbdcfg.py tools/python/scripts/xapi.vifcfg.py
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/tools/python/scripts/xapi.domcfg.py	Fri Oct 06 11:48:21 2006 +0100
     1.3 @@ -0,0 +1,39 @@
     1.4 +#
     1.5 +# VM Configuration for Xen API
     1.6 +#
     1.7 +
     1.8 +name_label =  'GentooAPI'
     1.9 +name_description =  'Gentoo VM via API'
    1.10 +user_version =  1
    1.11 +is_a_template =  False
    1.12 +memory_static_max =  32
    1.13 +memory_dynamic_max =  32
    1.14 +memory_dynamic_min =  32
    1.15 +memory_static_min =  32
    1.16 +VCPUs_policy =  ''
    1.17 +VCPUs_params =  ''
    1.18 +VCPUS_features_required =  ''
    1.19 +VCPUs_features_can_use =  ''
    1.20 +VCPUs_features_force_on =  ''
    1.21 +VCPUs_features_force_off =  ''
    1.22 +actions_after_shutdown =  'destroy'
    1.23 +actions_after_reboot =  'restart'
    1.24 +actions_after_suspend =  'destroy'
    1.25 +actions_after_crash =  'restart'
    1.26 +TPM_instance =  ''
    1.27 +TPM_backend =  ''
    1.28 +bios_boot =  ''
    1.29 +platform_std_VGA =  False
    1.30 +platform_serial =  ''
    1.31 +platform_localtime =  False
    1.32 +platform_clock_offset =  False
    1.33 +platform_enable_audio =  False
    1.34 +builder =  ''
    1.35 +boot_method =  '' # this will remove the kernel/initrd ??
    1.36 +kernel_kernel =  '/boot/vmlinuz-2.6.16.29-xen'
    1.37 +kernel_initrd =  '/root/initrd.img-2.6.16.29-xen.ramfs'
    1.38 +kernel_args =  'root=/dev/sda1 ro'
    1.39 +grub_cmdline =  ''
    1.40 +PCI_bus =  ''
    1.41 +other_config =  ''
    1.42 +
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/tools/python/scripts/xapi.py	Fri Oct 06 11:48:21 2006 +0100
     2.3 @@ -0,0 +1,207 @@
     2.4 +#!/usr/bin/python
     2.5 +#============================================================================
     2.6 +# This library is free software; you can redistribute it and/or
     2.7 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     2.8 +# License as published by the Free Software Foundation.
     2.9 +#
    2.10 +# This library is distributed in the hope that it will be useful,
    2.11 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    2.12 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    2.13 +# Lesser General Public License for more details.
    2.14 +#
    2.15 +# You should have received a copy of the GNU Lesser General Public
    2.16 +# License along with this library; if not, write to the Free Software
    2.17 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    2.18 +#============================================================================
    2.19 +# Copyright (C) 2006 XenSource Ltd.
    2.20 +#============================================================================
    2.21 +
    2.22 +from xen.util.xmlrpclib2 import ServerProxy
    2.23 +from optparse import *
    2.24 +from types import DictType
    2.25 +
    2.26 +HOST_INFO_FORMAT = '%-20s: %-50s'
    2.27 +VM_LIST_FORMAT = '%(name_label)-24s %(memory_actual)-5s %(vcpus_number)-5s'\
    2.28 +                 ' %(power_state)-5s %(uuid)-32s'
    2.29 +
    2.30 +LOGIN = ('atse', 'passwd')
    2.31 +
    2.32 +COMMANDS = {
    2.33 +    'host-info': ('', 'Get Xen Host Info'),
    2.34 +    'vm-list':   ('', 'List all domains.'),
    2.35 +    'vm-uuid':   ('<name>', 'UUID of a domain by name.'),
    2.36 +    'vm-name':   ('<uuid>', 'Name of UUID.'),
    2.37 +    'vm-start':  ('<name>', 'Start VM with name'),
    2.38 +    'vm-shutdown': ('<name>', 'Shutdown VM with name'),
    2.39 +    'vm-create': ('<pycfg>', 'Create VM with python config'),
    2.40 +    'vbd-create': ('<domname> <pycfg>', 'Create VBD attached to domname'),
    2.41 +    'vif-create': ('<domname> <pycfg>', 'Create VIF attached to domname'),
    2.42 +    'vm-delete': ('<domname>', 'Delete VM'),
    2.43 +}
    2.44 +
    2.45 +class OptionError(Exception):
    2.46 +    pass
    2.47 +
    2.48 +# 
    2.49 +# Extra utility functions
    2.50 +#
    2.51 +
    2.52 +def execute(fn, *args):
    2.53 +    result = fn(*args)
    2.54 +    if type(result) != DictType:
    2.55 +        raise TypeError("Function returned object of type: %s" %
    2.56 +                        str(type(result)))
    2.57 +    if 'Value' not in result:
    2.58 +        raise Exception(result['ErrorDescription'])
    2.59 +    return result['Value']
    2.60 +
    2.61 +
    2.62 +def _connect(*args):
    2.63 +    server = ServerProxy('httpu:///var/run/xend/xmlrpc.sock')        
    2.64 +    session = execute(server.Session.login_with_password, *LOGIN)
    2.65 +    host = execute(server.Session.get_this_host, session)
    2.66 +    return (server, session)
    2.67 +
    2.68 +def _stringify(adict):
    2.69 +    return dict([(k, str(v)) for k, v in adict.items()])
    2.70 +
    2.71 +def _read_python_cfg(filename):
    2.72 +    cfg_globals = {}
    2.73 +    execfile(filename, cfg_globals, {})
    2.74 +    return cfg_globals
    2.75 +
    2.76 +#
    2.77 +# Actual commands
    2.78 +#
    2.79 +
    2.80 +def xapi_host_info(*args):
    2.81 +    server, session = _connect()
    2.82 +    hosts = execute(server.Host.get_all, session)
    2.83 +    for host in hosts: # there is only one, but ..
    2.84 +        hostinfo = execute(server.Host.get_record, session, host)
    2.85 +        print HOST_INFO_FORMAT % ('Name', hostinfo['name_label'])
    2.86 +        print HOST_INFO_FORMAT % ('Version', hostinfo['software_version'])
    2.87 +        print HOST_INFO_FORMAT % ('CPUs', len(hostinfo['host_CPUs']))
    2.88 +        print HOST_INFO_FORMAT % ('VMs', len(hostinfo['resident_VMs']))
    2.89 +        print HOST_INFO_FORMAT % ('UUID', host)        
    2.90 +
    2.91 +def xapi_vm_list(*args):
    2.92 +    server, session = _connect()
    2.93 +    vm_uuids = execute(server.VM.get_all, session)
    2.94 +    print VM_LIST_FORMAT % {'name_label':'Name',
    2.95 +                            'memory_actual':'Mem',
    2.96 +                            'vcpus_number': 'VCPUs',
    2.97 +                            'power_state': 'State',
    2.98 +                            'uuid': 'UUID'}
    2.99 +    for uuid in vm_uuids:
   2.100 +        vm_info = execute(server.VM.get_record, session, uuid)
   2.101 +        print VM_LIST_FORMAT % _stringify(vm_info)
   2.102 +
   2.103 +def xapi_vm_create(*args):
   2.104 +    if len(args) < 1:
   2.105 +        raise OptionError("Configuration file not specified")
   2.106 +
   2.107 +    filename = args[0]
   2.108 +    cfg = _read_python_cfg(filename)
   2.109 +
   2.110 +    print 'Creating VM from %s ..' % filename
   2.111 +    server, session = _connect()
   2.112 +    uuid = execute(server.VM.create, session, cfg)
   2.113 +    print 'Done.'
   2.114 +    print uuid
   2.115 +
   2.116 +def xapi_vm_delete(*args):
   2.117 +    if len(args) < 1:
   2.118 +        raise OptionError("No domain name specified.")
   2.119 +    
   2.120 +    server, session = _connect()
   2.121 +    vm_uuid = execute(server.VM.get_by_label, session, args[0])
   2.122 +    print 'Destroying VM %s (%s)' % (args[0], vm_uuid)
   2.123 +    success = execute(server.VM.destroy, session, vm_uuid)
   2.124 +    print 'Done.'
   2.125 +    
   2.126 +
   2.127 +def xapi_vm_start(*args):
   2.128 +    if len(args) < 1:
   2.129 +        raise OptionError("No Domain name specified.")
   2.130 +    
   2.131 +    server, session = _connect()
   2.132 +    vm_uuid = execute(server.VM.get_by_label, session, args[0])
   2.133 +    print 'Starting VM %s (%s)' % (args[0], vm_uuid)
   2.134 +    success = execute(server.VM.start, session, vm_uuid)
   2.135 +    print 'Done.'
   2.136 +
   2.137 +def xapi_vm_shutdown(*args):
   2.138 +    if len(args) < 1:
   2.139 +        raise OptionError("No Domain name specified.")
   2.140 +
   2.141 +    server, session = _connect()
   2.142 +    vm_uuid = execute(server.VM.get_by_label, session, args[0])
   2.143 +    print 'Shutting down VM %s (%s)' % (args[0], vm_uuid)
   2.144 +    success = execute(server.VM.clean_shutdown, session, vm_uuid)
   2.145 +    print 'Done.'
   2.146 +
   2.147 +def xapi_vbd_create(*args):
   2.148 +    if len(args) < 2:
   2.149 +        raise OptionError("Configuration file not specified")
   2.150 +
   2.151 +    domname = args[0]
   2.152 +    filename = args[1]
   2.153 +    cfg = _read_python_cfg(filename)
   2.154 +    print 'Creating VBD from %s ..' % filename
   2.155 +    server, session = _connect()
   2.156 +    vm_uuid = execute(server.VM.get_by_label, session, domname)
   2.157 +    cfg['VM'] = vm_uuid
   2.158 +    vbd_uuid = execute(server.VBD.create, session, cfg)
   2.159 +    print 'Done.'
   2.160 +    print vbd_uuid
   2.161 +
   2.162 +def xapi_vif_create(*args):
   2.163 +    if len(args) < 2:
   2.164 +        raise OptionError("Configuration file not specified")
   2.165 +
   2.166 +    domname = args[0]
   2.167 +    filename = args[1]
   2.168 +    cfg = _read_python_cfg(filename)
   2.169 +    print 'Creating VIF from %s ..' % filename
   2.170 +    server, session = _connect()
   2.171 +    vm_uuid = execute(server.VM.get_by_label, session, domname)
   2.172 +    cfg['VM'] = vm_uuid
   2.173 +    vif_uuid = execute(server.VIF.create, session, cfg)
   2.174 +    print 'Done.'
   2.175 +    print vif_uuid        
   2.176 +
   2.177 +#
   2.178 +# Command Line Utils
   2.179 +#
   2.180 +
   2.181 +def usage(command = None):
   2.182 +    print 'Usage: xapi <subcommand> [options] [args]'
   2.183 +    print
   2.184 +    print 'Subcommands:'
   2.185 +    print
   2.186 +    sorted_commands = sorted(COMMANDS.keys())
   2.187 +    for command  in sorted_commands:
   2.188 +        args, description = COMMANDS[command]
   2.189 +        print '%-16s  %-40s' % (command, description)
   2.190 +    print
   2.191 +
   2.192 +def main(args):
   2.193 +
   2.194 +    if len(args) < 1 or args[0] in ('-h', '--help', 'help'):
   2.195 +        usage()
   2.196 +        sys.exit(1)
   2.197 +
   2.198 +    subcmd = args[0]
   2.199 +
   2.200 +    subcmd_func_name = 'xapi_' + subcmd.replace('-', '_')
   2.201 +    subcmd_func = globals().get(subcmd_func_name, None)
   2.202 +    if subcmd_func and callable(subcmd_func):
   2.203 +        subcmd_func(*args[1:])
   2.204 +    else:
   2.205 +        print 'Error: Unable to find subcommand \'%s\'' % subcmd
   2.206 +        usage()
   2.207 +    
   2.208 +if __name__ == "__main__":
   2.209 +    import sys
   2.210 +    main(sys.argv[1:])
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/tools/python/scripts/xapi.vbdcfg.py	Fri Oct 06 11:48:21 2006 +0100
     3.3 @@ -0,0 +1,12 @@
     3.4 +#
     3.5 +# Virtual Block Device (VBD) Xen API Configuration
     3.6 +# 
     3.7 +# Note: There is a non-API field here called "image" which is a backwards
     3.8 +#       compat addition so you can mount to old images.
     3.9 +# 
    3.10 +
    3.11 +VDI =  ''
    3.12 +device = 'sda1'
    3.13 +mode = 'RW'
    3.14 +driver = 'paravirtualised'
    3.15 +image = 'file:/root/gentoo-64-xenU.img'
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/tools/python/scripts/xapi.vifcfg.py	Fri Oct 06 11:48:21 2006 +0100
     4.3 @@ -0,0 +1,10 @@
     4.4 +#
     4.5 +# Virtual Network Interface Configuration for the Xen API
     4.6 +#
     4.7 +
     4.8 +name = ''
     4.9 +type = 'paravirtualised'
    4.10 +#device = 'eth0' # this is the dom0 device, not domU!
    4.11 +network = '' # ignored
    4.12 +MAC = ''
    4.13 +MTU = '1500'