~bkidwell/vboxmanagelite/main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#!/usr/bin/env python

"""VBoxManage Lite 1.1

Copyright 2011 Brendan Kidwell

VBoxManage Lite is a wrapper script around VirtualBox's 'VBoxManage'
command, providing a more compact syntax for commonly used commands.

This software is licensed under the GNU General Public License version 3
<http://www.gnu.org/licenses/gpl-3.0.html>.


To install:

Copy to your ~/bin folder (make sure ~/bin is in your PATH).


History:

1.1   Optimized the 'status' command to only call VBoxManage once to get all
      machine statuses; runs faster now. Made the 'VBoxManage' command a
      configurable constant instead of hard-coded in three places.

1.0   Initial release

"""

import sys
import textwrap
import os
import commands
import re
import subprocess
from optparse import OptionParser
from UserDict import UserDict

scriptname = os.path.basename(sys.argv[0])
version = "1.1"

helptext = """Usage: %s COMMAND [options] [arguments]

VBoxManage Lite is a Wrapper around VBoxManage for common commands.

Commands:  list  start  stop  halt  reset  status

list                lists registered virtual machines
  -r, --running     include only running virtual machines in list
  -u, --uuid        show UUID
  -s, --status      show status

start MACHINE       starts MACHINE if it is not running
  -g, --gui         open a window on the desktop
  -b, --background  start in the background (default)

stop MACHINE        stops MACHINE (suspend)

halt MACHINE        halts MACHINE (power off)

reset MACHINE       resets MACHINE

status MACHINE      determine if MACHINE is running


Exit Codes (general):
  0  Command completed successfully.
  1  Virtual machine is already in the requested state.
  2  Command failed.
  3  Virtual machine doesn't exist.

Exit Codes for 'status' command:
  0  saved, powered off, aborted
  1  paused
  2  running
  3  not found
""" % scriptname

# This is the system command to call the VirtualBox backend
VBOXMANAGE = "VBoxManage"

def main():
	if len(sys.argv) < 2: help(1)
	
	cmd = sys.argv[1]
	args = sys.argv[2:]
	
	if cmd == "--version":
		print "VBoxManage Lite", version
		sys.exit(0)

	if cmd in ("help", "-h", "-?", "--help"):
		help(0)
		
	if cmd in ("list", "start", "stop", "halt", "reset", "status"):
		# call the chosen command's function
		(exitcode, output) = globals()["cmd_%s" % cmd](args)
		if output: print output
		sys.exit(exitcode)
	
	print "Invalid command specified."
	help(1)

def myparser(cmd):
	return OptionParser("Usage: %s %s" % (scriptname, help))

def cmd_list(args):
	parser = myparser("list [-rus]")
	parser.add_option("-r", "--running", action="store_const", dest="running", const=True, default=False)
	parser.add_option("-u", "--uuid", action="store_const", dest="uuid", const=True, default=False)
	parser.add_option("-s", "--status", action="store_const", dest="status", const=True, default=False)
	(options, args) = parser.parse_args(args)	
	
	if options.running: which = "runningvms"
	else:               which = "vms"

	output = commands.getoutput("%s list %s --long" % (VBOXMANAGE, which))

#	Output format:
#
#	Name:            $name\n
#	UUID:            $uuid\n
#	State:           $state (since $state_time)\n
#	$FieldName:      $value\n
#	\n
#	USB Device Filters:\n
#	\n
#	$usb_filters\n
#	\n
#	Shared folders:  $shared\n
#	\n
#	Guest:           ???\n
#	\n
#	Configured memory baloon size:     $baloon\n
#	\n
#	\n
#	[Repeat]

	class Machine(UserDict):
		def __init__(self, text):
			UserDict.__init__(self)
			for line in text.split("\n"):
				matches = re.search(r"^([^:]+):\s*(.*)$", line)
				if matches:
					(key, value) = ( matches.group(1).strip(), matches.group(2).strip() )
					# only record the first found value for each key
					if not key in self: self[key] = value
			if "Name" in self:
				self["Text"] = self["Name".strip('"')]
				self["Sort"] = self["Text"].lower()
			if "State" in self: self["Simple State"] = self["State"].split("(")[0].strip()
	machines = []
	
	for block in output.split("\n\n\n"):
		m = Machine(block)
		if "Name" in m: machines.append(m)

	getwidth = lambda: max([len(m["Text"]) for m in machines]) + 3

	if options.uuid:
		width = getwidth()
		for m in machines:
			m["Text"] = m["Text"].ljust(width) + m["UUID"]
	
	if options.status:
		width = getwidth()
		for m in machines:
			if m["Simple State"] == "running": m["Simple State"] = "\033[32mrunning\033[0m"
			if m["Simple State"] == "saved":   m["Simple State"] = "\033[33msaved\033[0m"
			m["Text"] = m["Text"].ljust(width) + m["Simple State"]
	
	return (0, "\n".join([
		m["Text"] for m in sorted(machines, key = lambda k: k["Sort"])
	]))

def getstate(name):
	"""returns "running", "paused", "aborted", "powered off"."""
	
	output = commands.getoutput('%s showvminfo "%s"' % (VBOXMANAGE, name))
	
	# search for line beginning with State:
	matches = re.search(r"^State:\s*(.*)$", output, re.MULTILINE)
	
	if matches == None: raise RuntimeError('"%s" was not found.' % name)
	
	# find first "(" and return everything before it
	return matches.group(1).split("(")[0].strip()

def cmd_status(args):
	name = args[0]
	
	try:
		state = getstate(name)
	except:
		return (3, sys.exc_info()[1])
	
	if state == "running": return (2, state)
	if state == "paused": return (1, state)
	if state in ("saved", "powered off", "aborted"): return (0, state)
	
	raise RuntimeError("Unexpected state value read from VBoxManage: %s" % state)

def cmd_start(args):
	parser = myparser("start [-gb] MACHINE")
	parser.add_option("-g", "--gui", action="store_const", dest="background", const=False, default=True)
	parser.add_option("-b", "--background", action="store_const", dest="background", const=True, default=True)
	(options, args) = parser.parse_args(args)

	name = args[0]
	
	try:    state = getstate(name)
	except: return (3, sys.exc_info()[1])
		
	if options.background: mode = "headless"
	else:                  mode = "gui"
	
	if state != "running":
		exitcode = subprocess.call([VBOXMANAGE, "startvm", name, "--type", mode])
		if exitcode: return (2, None)
		else:        return (0, None)
	else:
		return (1, '"%s" is already running.' % name)

def stop(name, action, noaction='"%s" is already %s.'):
	try:    state = getstate(name)
	except: return (3, sys.exc_info()[1])

	if state == "running":
		exitcode = subprocess.call([VBOXMANAGE, "controlvm", name, action])
		if exitcode: return (2, None)
		else:        return (0, None)
	else:
		return (1, noaction % (name, state))

def cmd_stop(args):
	return stop(args[0], "savestate")

def cmd_halt(args):
	return stop(args[0], "poweroff")

def cmd_reset(args):
	return stop(args[0], "reset", '"%s" is not running (%s).')

def help(exitcode):
	print helptext
	sys.exit(exitcode)


main()