ia64/xen-unstable

view tools/python/scripts/xapi.py @ 12106:858218d94516

[XENAPI] Added hard shutdown (aka. vm-destroy)

Signed-off-by: Alastair Tse <atse@xensource.com>
author Alastair Tse <atse@xensource.com>
date Fri Oct 06 11:57:16 2006 +0100 (2006-10-06)
parents d147be77861d
children 18506db37dc2
line source
1 #!/usr/bin/python
2 #============================================================================
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of version 2.1 of the GNU Lesser General Public
5 # License as published by the Free Software Foundation.
6 #
7 # This library is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 # Lesser General Public License for more details.
11 #
12 # You should have received a copy of the GNU Lesser General Public
13 # License along with this library; if not, write to the Free Software
14 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15 #============================================================================
16 # Copyright (C) 2006 XenSource Ltd.
17 #============================================================================
19 from xen.util.xmlrpclib2 import ServerProxy
20 from optparse import *
21 from types import DictType
23 HOST_INFO_FORMAT = '%-20s: %-50s'
24 VM_LIST_FORMAT = '%(name_label)-24s %(memory_actual)-5s %(vcpus_number)-5s'\
25 ' %(power_state)-5s %(uuid)-32s'
27 LOGIN = ('atse', 'passwd')
29 COMMANDS = {
30 'host-info': ('', 'Get Xen Host Info'),
31 'vm-list': ('', 'List all domains.'),
32 'vm-uuid': ('<name>', 'UUID of a domain by name.'),
33 'vm-name': ('<uuid>', 'Name of UUID.'),
34 'vm-start': ('<name>', 'Start VM with name'),
35 'vm-shutdown': ('<name>', 'Shutdown VM with name'),
36 'vm-create': ('<pycfg>', 'Create VM with python config'),
37 'vbd-create': ('<domname> <pycfg>', 'Create VBD attached to domname'),
38 'vif-create': ('<domname> <pycfg>', 'Create VIF attached to domname'),
39 'vm-delete': ('<domname>', 'Delete VM'),
40 'vm-destroy': ('<name>', 'Hard shutdown a VM with name'),
41 }
43 class OptionError(Exception):
44 pass
46 #
47 # Extra utility functions
48 #
50 def execute(fn, *args):
51 result = fn(*args)
52 if type(result) != DictType:
53 raise TypeError("Function returned object of type: %s" %
54 str(type(result)))
55 if 'Value' not in result:
56 raise Exception(result['ErrorDescription'])
57 return result['Value']
60 def _connect(*args):
61 server = ServerProxy('httpu:///var/run/xend/xmlrpc.sock')
62 session = execute(server.Session.login_with_password, *LOGIN)
63 host = execute(server.Session.get_this_host, session)
64 return (server, session)
66 def _stringify(adict):
67 return dict([(k, str(v)) for k, v in adict.items()])
69 def _read_python_cfg(filename):
70 cfg_globals = {}
71 execfile(filename, cfg_globals, {})
72 return cfg_globals
74 #
75 # Actual commands
76 #
78 def xapi_host_info(*args):
79 server, session = _connect()
80 hosts = execute(server.Host.get_all, session)
81 for host in hosts: # there is only one, but ..
82 hostinfo = execute(server.Host.get_record, session, host)
83 print HOST_INFO_FORMAT % ('Name', hostinfo['name_label'])
84 print HOST_INFO_FORMAT % ('Version', hostinfo['software_version'])
85 print HOST_INFO_FORMAT % ('CPUs', len(hostinfo['host_CPUs']))
86 print HOST_INFO_FORMAT % ('VMs', len(hostinfo['resident_VMs']))
87 print HOST_INFO_FORMAT % ('UUID', host)
89 def xapi_vm_list(*args):
90 server, session = _connect()
91 vm_uuids = execute(server.VM.get_all, session)
92 print VM_LIST_FORMAT % {'name_label':'Name',
93 'memory_actual':'Mem',
94 'vcpus_number': 'VCPUs',
95 'power_state': 'State',
96 'uuid': 'UUID'}
97 for uuid in vm_uuids:
98 vm_info = execute(server.VM.get_record, session, uuid)
99 print VM_LIST_FORMAT % _stringify(vm_info)
101 def xapi_vm_create(*args):
102 if len(args) < 1:
103 raise OptionError("Configuration file not specified")
105 filename = args[0]
106 cfg = _read_python_cfg(filename)
108 print 'Creating VM from %s ..' % filename
109 server, session = _connect()
110 uuid = execute(server.VM.create, session, cfg)
111 print 'Done.'
112 print uuid
114 def xapi_vm_delete(*args):
115 if len(args) < 1:
116 raise OptionError("No domain name specified.")
118 server, session = _connect()
119 vm_uuid = execute(server.VM.get_by_label, session, args[0])
120 print 'Destroying VM %s (%s)' % (args[0], vm_uuid)
121 success = execute(server.VM.destroy, session, vm_uuid)
122 print 'Done.'
125 def xapi_vm_start(*args):
126 if len(args) < 1:
127 raise OptionError("No Domain name specified.")
129 server, session = _connect()
130 vm_uuid = execute(server.VM.get_by_label, session, args[0])
131 print 'Starting VM %s (%s)' % (args[0], vm_uuid)
132 success = execute(server.VM.start, session, vm_uuid)
133 print 'Done.'
135 def xapi_vm_shutdown(*args):
136 if len(args) < 1:
137 raise OptionError("No Domain name specified.")
139 server, session = _connect()
140 vm_uuid = execute(server.VM.get_by_label, session, args[0])
141 print 'Shutting down VM %s (%s)' % (args[0], vm_uuid)
142 success = execute(server.VM.clean_shutdown, session, vm_uuid)
143 print 'Done.'
145 def xapi_vm_destroy(*args):
146 if len(args) < 1:
147 raise OptionError("No Domain name specified.")
149 server, session = _connect()
150 vm_uuid = execute(server.VM.get_by_label, session, args[0])
151 print 'Shutting down VM with force %s (%s)' % (args[0], vm_uuid)
152 success = execute(server.VM.hard_shutdown, session, vm_uuid)
153 print 'Done.'
155 def xapi_vbd_create(*args):
156 if len(args) < 2:
157 raise OptionError("Configuration file not specified")
159 domname = args[0]
160 filename = args[1]
161 cfg = _read_python_cfg(filename)
162 print 'Creating VBD from %s ..' % filename
163 server, session = _connect()
164 vm_uuid = execute(server.VM.get_by_label, session, domname)
165 cfg['VM'] = vm_uuid
166 vbd_uuid = execute(server.VBD.create, session, cfg)
167 print 'Done.'
168 print vbd_uuid
170 def xapi_vif_create(*args):
171 if len(args) < 2:
172 raise OptionError("Configuration file not specified")
174 domname = args[0]
175 filename = args[1]
176 cfg = _read_python_cfg(filename)
177 print 'Creating VIF from %s ..' % filename
178 server, session = _connect()
179 vm_uuid = execute(server.VM.get_by_label, session, domname)
180 cfg['VM'] = vm_uuid
181 vif_uuid = execute(server.VIF.create, session, cfg)
182 print 'Done.'
183 print vif_uuid
185 #
186 # Command Line Utils
187 #
189 def usage(command = None):
190 print 'Usage: xapi <subcommand> [options] [args]'
191 print
192 print 'Subcommands:'
193 print
194 sorted_commands = sorted(COMMANDS.keys())
195 for command in sorted_commands:
196 args, description = COMMANDS[command]
197 print '%-16s %-40s' % (command, description)
198 print
200 def main(args):
202 if len(args) < 1 or args[0] in ('-h', '--help', 'help'):
203 usage()
204 sys.exit(1)
206 subcmd = args[0]
208 subcmd_func_name = 'xapi_' + subcmd.replace('-', '_')
209 subcmd_func = globals().get(subcmd_func_name, None)
210 if subcmd_func and callable(subcmd_func):
211 subcmd_func(*args[1:])
212 else:
213 print 'Error: Unable to find subcommand \'%s\'' % subcmd
214 usage()
216 if __name__ == "__main__":
217 import sys
218 main(sys.argv[1:])