1
2
3
4
5
6
7
8
9
|
#!/usr/bin/python
""" vws - script to control QEMU/KVM virtual workstations """
from ConfigParser import ConfigParser
from argparse import ArgumentParser, Namespace
import fcntl
import socket, select
import errno
import re
import os, sys, time, os.path
|
>
>
|
1
2
3
4
5
6
7
8
9
10
11
|
#!/usr/bin/python
""" vws - script to control QEMU/KVM virtual workstations """
# pylint: disable=bad-builtin
# pylint: good-names: i,j,k,f,r,ex
from ConfigParser import ConfigParser
from argparse import ArgumentParser, Namespace
import fcntl
import socket, select
import errno
import re
import os, sys, time, os.path
|
︙ | | | ︙ | |
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
""" Connects to monitor of VM in vm_dir and returns connected socket"""
sock = socket.socket(socket.AF_UNIX)
monitor_path = os.path.join(vm_dir, "monitor")
if not os.access(monitor_path, os.W_OK):
return None
try:
sock.connect(monitor_path)
except IOError as e:
if e.errno == errno.ECONNREFUSED:
# virtal machine is not running
return None
else:
raise e
r, w, x = select.select([sock], [], [], 0.001)
if sock in r:
greeting = sock.recv(1024)
return sock
def send_command(sock, command):
""" Sends monitor command to given socket and returns answer """
fcntl.flock(sock, fcntl.LOCK_EX)
try:
sock.send(command + "\n")
|
|
|
|
|
|
|
|
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
""" Connects to monitor of VM in vm_dir and returns connected socket"""
sock = socket.socket(socket.AF_UNIX)
monitor_path = os.path.join(vm_dir, "monitor")
if not os.access(monitor_path, os.W_OK):
return None
try:
sock.connect(monitor_path)
except IOError as ex:
if ex.errno == errno.ECONNREFUSED:
# virtal machine is not running
return None
else:
raise ex
readfd, dummy_w, dummy_x = select.select([sock], [], [], 0.001)
if sock in readfd:
dummy_greeting = sock.recv(1024)
return sock
def send_command(sock, command):
""" Sends monitor command to given socket and returns answer """
fcntl.flock(sock, fcntl.LOCK_EX)
try:
sock.send(command + "\n")
|
︙ | | | ︙ | |
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
|
def spiceurl(options):
""" Returns spice URI for given (as set of parsed args) VM """
output = send_command(options.sock, "info spice")
url = None
for line in output.split("\n"):
if url is not None:
continue
n = line.find("address:")
if n != -1:
url = line[n+9:]
if url.startswith('*:'):
url = "localhost"+url[1:]
if url is None:
return None
return "spice://" + url.rstrip('\r')
def list_bridges():
lst = []
with os.popen(config.get('tools', 'bridge_list'), "r") as f:
for line in f:
n = line.find('\t')
if n <= 0:
continue
name = line[:n]
if name == "bridge name":
continue
lst.append(name)
return lst
def validate_size(size):
return re.match('\\d+[KMG]', size) is not None
def get_drives(vm_dir):
""" Return list of drive files in the VW directory """
result = []
with open(vm_dir + "/start") as f:
for line in f:
if (re.match("\\s*-drive .*", line) and
line.find("media=disk") > -1):
m = re.search("file=([^,\\s]*)", line)
if m:
result.append(m.group(1))
return result
def snapshot_mode(sock):
""" Returns True if VM is running in snapshot mode """
answer = send_command(sock, "info block")
return re.search(": /tmp", answer) is not None
#
# command implementation
#
def cmd_spiceuri(options):
print spiceurl(options)
def cmd_start(options):
if options.stopped:
arg = ""
if options.cdrom:
arg = " -cdrom " + options.cdrom[0]
if options.snapshot:
arg = arg+" -snapshot"
if options.args:
|
|
|
|
>
|
|
|
>
|
|
|
>
>
|
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
|
def spiceurl(options):
""" Returns spice URI for given (as set of parsed args) VM """
output = send_command(options.sock, "info spice")
url = None
for line in output.split("\n"):
if url is not None:
continue
idx = line.find("address:")
if idx != -1:
url = line[idx+9:]
if url.startswith('*:'):
url = "localhost"+url[1:]
if url is None:
return None
return "spice://" + url.rstrip('\r')
def list_bridges():
""" Return list of bridge network interfaces present in the system """
lst = []
with os.popen(config.get('tools', 'bridge_list'), "r") as f:
for line in f:
idx = line.find('\t')
if idx <= 0:
continue
name = line[:idx]
if name == "bridge name":
continue
lst.append(name)
return lst
def validate_size(size):
""" Checks if size argument has proper format """
return re.match('\\d+[KMG]', size) is not None
def get_drives(vm_dir):
""" Return list of drive files in the VW directory """
result = []
with open(vm_dir + "/start") as f:
for line in f:
if (re.match("\\s*-drive .*", line) and
line.find("media=disk") > -1):
match = re.search("file=([^,\\s]*)", line)
if match:
result.append(match.group(1))
return result
def snapshot_mode(sock):
""" Returns True if VM is running in snapshot mode """
answer = send_command(sock, "info block")
return re.search(": /tmp", answer) is not None
#
# command implementation
#
def cmd_spiceuri(options):
""" vws spiceuri """
print spiceurl(options)
def cmd_start(options):
""" vws start """
if options.stopped:
arg = ""
if options.cdrom:
arg = " -cdrom " + options.cdrom[0]
if options.snapshot:
arg = arg+" -snapshot"
if options.args:
|
︙ | | | ︙ | |
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
|
if options.gui:
uri = spiceurl(options)
os.system((config.get('tools', 'viewer') + "&") % uri)
elif not options.stopped:
print >>sys.stderr, "VM already running"
def cmd_stop(options):
if snapshot_mode(options.sock) or options.hard:
print send_command(options.sock, 'quit')
else:
print send_command(options.sock, 'system_powerdown')
def cmd_monitor(options):
try:
print "(qemu) ",
sys.stdout.flush()
while True:
r, w, x = select.select([sys.stdin, options.sock], [], [])
if sys.stdin in r:
cmd = sys.stdin.readline()
# Check for eof
if len(cmd) == 0:
break
answer = send_command(options.sock, cmd.rstrip())
n = answer.index('\n')
print answer[n+1:],
sys.stdout.flush()
elif options.sock in r:
print "UNSOLICITED MESSAGE %" + options.sock.readline().rstrip()
except KeyboardInterrupt:
print "Keyboard interrupt"
sys.exit()
def cmd_reset(options):
print send_command(options.sock, 'system_reset')
def cmd_save(options):
answer = send_command(options.sock, 'savevm')
if re.search("Error", answer):
print >>sys.stderr, answer
sys.exit(1)
else:
send_command(options.sock, 'quit')
def cmd_cdrom(options):
if options.id is None:
# Search for devices which could be interpreted as CDROM
devlist = send_command(options.sock, "info block")
for dev in re.findall("([-\\w]+): [^\n]+\n Removable device:",
devlist):
if re.search("cd", dev):
options.id = dev
|
>
>
>
|
>
|
|
|
|
>
>
>
|
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
|
if options.gui:
uri = spiceurl(options)
os.system((config.get('tools', 'viewer') + "&") % uri)
elif not options.stopped:
print >>sys.stderr, "VM already running"
def cmd_stop(options):
""" vws stop """
if snapshot_mode(options.sock) or options.hard:
print send_command(options.sock, 'quit')
else:
print send_command(options.sock, 'system_powerdown')
def cmd_monitor(options):
""" vws monitor """
try:
print "(qemu) ",
sys.stdout.flush()
while True:
readfd, dummy_w, dummy_x = select.select([sys.stdin, options.sock],
[], [])
if sys.stdin in readfd:
cmd = sys.stdin.readline()
# Check for eof
if len(cmd) == 0:
break
answer = send_command(options.sock, cmd.rstrip())
idx = answer.index('\n')
print answer[idx+1:],
sys.stdout.flush()
elif options.sock in readfd:
print "UNSOLICITED MESSAGE %" + options.sock.readline().rstrip()
except KeyboardInterrupt:
print "Keyboard interrupt"
sys.exit()
def cmd_reset(options):
""" vws reset """
print send_command(options.sock, 'system_reset')
def cmd_save(options):
""" vws save """
answer = send_command(options.sock, 'savevm')
if re.search("Error", answer):
print >>sys.stderr, answer
sys.exit(1)
else:
send_command(options.sock, 'quit')
def cmd_cdrom(options):
""" vws cdrom """
if options.id is None:
# Search for devices which could be interpreted as CDROM
devlist = send_command(options.sock, "info block")
for dev in re.findall("([-\\w]+): [^\n]+\n Removable device:",
devlist):
if re.search("cd", dev):
options.id = dev
|
︙ | | | ︙ | |
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
|
answer = send_command(options.sock, "eject " + options.id)
else:
answer = send_command(options.sock, "change %s %s" %
(options.id, options.file))
print answer
def find_usb(options, devices):
if hasattr("pattern", options):
for dev in devices:
if re.search(options.pattern, dev[1]):
options.address = dev[0]
break
elif not hasattr("address", options):
print >>sys.stderr, ("Address or search pattern for device " +
"is not specified")
sys.exit(1)
else:
return options.address
def get_host_devices():
global config
f = os.popen(config.get('tools', "lsusb"), "r")
l = []
for dev in f:
m = re.match('Bus (\\d+) Device (\\d+): (.*)$', dev)
if m:
if m.group(3).endswith("root hub"):
continue
l.append((m.group(1) + "." + m.group(2), m.group(3)))
f.close()
return l
def get_vm_devices(sock):
answer = send_command(sock, "info usb")
l = []
for dev in answer.split("\n"):
m = re.match('Device (\\d+\\.\\d+), .*?, Product (.*)$', dev)
if m:
l.append((m.group(1), m.group(2)))
return l
def cmd_usb_insert(options):
address = find_usb(options, get_host_devices())
answer = send_command(options.sock, "usb_add host:%s" % address)
print answer
def cmd_usb_list(options):
for addr, descr in get_host_devices():
print addr, ": ", descr
def cmd_usb_attached(options):
for t in get_vm_devices(options.sock):
print "Address %s : %s" % (t[0], t[1])
def cmd_usb_remove(options):
address = find_usb(options, get_vm_devices(options.sock))
answer = send_command(options.sock, "usb_del %s" % address)
print answer
def cmd_list(options):
count = 0
search_path = [os.environ['HOME'] + "/VWs",
config.get("directories", "SharedVMs"),
config.get("directories", "AutostartVMs")]
for dirname in search_path:
if not os.access(dirname + "/.", os.X_OK):
continue
|
>
>
>
>
>
>
|
|
|
|
|
|
>
|
|
|
|
|
>
|
>
>
|
|
>
>
|
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
|
answer = send_command(options.sock, "eject " + options.id)
else:
answer = send_command(options.sock, "change %s %s" %
(options.id, options.file))
print answer
def find_usb(options, devices):
""" Search for pattern or address given in options in the
given list of devices.
List should be produced by get_host_devices() or
get_vm_devices()
"""
if hasattr("pattern", options):
for dev in devices:
if re.search(options.pattern, dev[1]):
options.address = dev[0]
break
elif not hasattr("address", options):
print >>sys.stderr, ("Address or search pattern for device " +
"is not specified")
sys.exit(1)
else:
return options.address
def get_host_devices():
""" Parses output of lsusb into list of tuples "address" "descr" """
global config
f = os.popen(config.get('tools', "lsusb"), "r")
lst = []
for dev in f:
match = re.match('Bus (\\d+) Device (\\d+): (.*)$', dev)
if match:
if match.group(3).endswith("root hub"):
continue
lst.append((match.group(1) + "." + match.group(2), match.group(3)))
f.close()
return lst
def get_vm_devices(sock):
""" Parses output of info usb monitor command into list of devices"""
answer = send_command(sock, "info usb")
lst = []
for dev in answer.split("\n"):
match = re.match('Device (\\d+\\.\\d+), .*?, Product (.*)$', dev)
if match:
lst.append((match.group(1), match.group(2)))
return lst
def cmd_usb_insert(options):
""" vws usb insert """
address = find_usb(options, get_host_devices())
answer = send_command(options.sock, "usb_add host:%s" % address)
print answer
def cmd_usb_list(dummy_options):
""" vws usb list - just list all host devices """
for addr, descr in get_host_devices():
print addr, ": ", descr
def cmd_usb_attached(options):
""" vws usb attached - list devices assigned to given vm """
for dev in get_vm_devices(options.sock):
print "Address %s : %s" % (dev[0], dev[1])
def cmd_usb_remove(options):
""" vws usb remove """
address = find_usb(options, get_vm_devices(options.sock))
answer = send_command(options.sock, "usb_del %s" % address)
print answer
def cmd_list(options):
""" vws list """
count = 0
search_path = [os.environ['HOME'] + "/VWs",
config.get("directories", "SharedVMs"),
config.get("directories", "AutostartVMs")]
for dirname in search_path:
if not os.access(dirname + "/.", os.X_OK):
continue
|
︙ | | | ︙ | |
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
|
print "%*s %s" % (-maxlen, f[0], f[1])
else:
print f[0]
if not count:
sys.exit(1)
def cmd_screenshot(options):
from os.path import abspath
filename = abspath(options.filename)
print send_command(options.sock, "screendump " + filename)
def cmd_record(options):
from os.path import abspath
filename = abspath(options.filename)
print send_command(options.sock, "wavcapture " + filename)
def cmd_stoprecord(options):
answer = send_command(options.sock, "info capture")
m = re.search('\\[(\\d+)\\]: ', answer)
if not m:
print >>sys.stderr, "No sound recording in progress"
sys.exit(1)
else:
print send_command(options.sock, "stopcapture " + m.group(1))
def cmd_version(options):
print VERSION
def cmd_snapshot(options):
if not options.stopped:
print >>sys.stderr, "Cannot make snapshot of running VW"
sys.exit(1)
drives = get_drives(options.dir)
os.chdir(options.dir)
newnames = {}
for i in drives:
name, ext = os.path.splitext(i)
newnames[i] = name + "." + options.snapname + ext
if os.path.exists(newnames[i]):
print >>sys.stderr, "Snapshot %s already exists", options.snapname
return 1
for i in drives:
os.rename(i, newnames[i])
os.system("qemu-img create -f qcow2 -b \"%s\" \"%s\"" %
(newnames[i], i))
return 0
def cmd_snapshots(options):
os.chdir(options.dir)
drives = get_drives(options.dir)
lst = []
info = {}
with os.popen("qemu-img info --backing-chain " + drives[0], "r") as f:
for line in f:
if line.find(": ") != -1:
var, val = line.strip().split(": ")
if val != "":
info[var] = val
elif line[0] == '\n':
lst.append(info)
info = {}
lst.append(info)
for d in lst:
print "%-30s %+8s %+8s" % (d["image"], d["virtual size"],
d["disk size"])
def get_backing(drive):
with os.popen('qemu-img info "%s"' % drive, "r") as f:
for line in f:
m = re.match("backing.file: (.*)$", line)
if m:
return m.group(1)
return None
def cmd_revert(options):
" Removes latest snapshot images and creates new ones instead "
if not options.stopped:
print >>sys.stderr, "Cannot revert running VW to snapshot"
sys.exit(1)
os.chdir(options.dir)
for drive in get_drives(options.dir):
# Check if first has backing file
backing = get_backing(drive)
if not backing:
print >>sys.stderr, "Drive %s has no snapshots" % drive
continue
# Unlink current image
os.unlink(drive)
# create new image with same backing file
os.system('qemu-img create -f qcow2 -b "%s" "%s"' % (backing, drive))
def cmd_commit(options):
#
# Commits last snapshot changes into it's backing file
#
if options.stopped:
#
# Stoppend vm - last snapshot is commited into its backing file.
# Backing file is made current drive image
#
os.chdir(options.dir)
found = 0
|
>
>
>
|
|
|
|
>
>
>
|
|
|
>
>
>
|
|
|
>
|
>
>
<
>
|
<
>
>
|
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
|
print "%*s %s" % (-maxlen, f[0], f[1])
else:
print f[0]
if not count:
sys.exit(1)
def cmd_screenshot(options):
""" vws screenshot """
from os.path import abspath
filename = abspath(options.filename)
print send_command(options.sock, "screendump " + filename)
def cmd_record(options):
""" vws record """
from os.path import abspath
filename = abspath(options.filename)
print send_command(options.sock, "wavcapture " + filename)
def cmd_stoprecord(options):
""" vws stoprecord """
answer = send_command(options.sock, "info capture")
match = re.search('\\[(\\d+)\\]: ', answer)
if not match:
print >>sys.stderr, "No sound recording in progress"
sys.exit(1)
else:
print send_command(options.sock, "stopcapture " + match.group(1))
def cmd_version(dummy_options):
""" vws cersion """
print VERSION
def cmd_snapshot(options):
""" vws snapshot - create snapshot """
if not options.stopped:
print >>sys.stderr, "Cannot make snapshot of running VW"
sys.exit(1)
drives = get_drives(options.dir)
os.chdir(options.dir)
newnames = {}
for i in drives:
name, ext = os.path.splitext(i)
newnames[i] = name + "." + options.snapname + ext
if os.path.exists(newnames[i]):
print >>sys.stderr, "Snapshot %s already exists", options.snapname
return 1
for i in drives:
os.rename(i, newnames[i])
os.system("qemu-img create -f qcow2 -b \"%s\" \"%s\"" %
(newnames[i], i))
return 0
def cmd_snapshots(options):
""" vws snapshots - list existing snapshots """
os.chdir(options.dir)
drives = get_drives(options.dir)
lst = []
info = {}
with os.popen("qemu-img info --backing-chain " + drives[0], "r") as f:
for line in f:
if line.find(": ") != -1:
var, val = line.strip().split(": ")
if val != "":
info[var] = val
elif line[0] == '\n':
lst.append(info)
info = {}
lst.append(info)
for snap in lst:
print "%-30s %+8s %+8s" % (snap["image"], snap["virtual size"],
snap["disk size"])
def get_backing(drive):
""" find if partucular virtual drive has backing file and returns
its name
"""
with os.popen('qemu-img info "%s"' % drive, "r") as f:
for line in f:
match = re.match("backing.file: (.*)$", line)
if match:
return match.group(1)
return None
def cmd_revert(options):
""" reverts to last snapshot:
Removes latest snapshot images and creates new ones instead
number of snapshots in the stack is not changed by this command
"""
if not options.stopped:
print >>sys.stderr, "Cannot revert running VW to snapshot"
sys.exit(1)
os.chdir(options.dir)
for drive in get_drives(options.dir):
# Check if first has backing file
backing = get_backing(drive)
if not backing:
print >>sys.stderr, "Drive %s has no snapshots" % drive
continue
# Unlink current image
os.unlink(drive)
# create new image with same backing file
os.system('qemu-img create -f qcow2 -b "%s" "%s"' % (backing, drive))
def cmd_commit(options):
"""
Commits last snapshot changes into it's backing file
There would be one snapshot less for virtual machine
"""
if options.stopped:
#
# Stoppend vm - last snapshot is commited into its backing file.
# Backing file is made current drive image
#
os.chdir(options.dir)
found = 0
|
︙ | | | ︙ | |
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
|
else:
if snapshot_mode(options.sock):
send_command(options.sock, "commit")
else:
print >>sys.stderr, "VM is not running in snapshot mode"
sys.exit(1)
template = """#!/bin/sh
# Get machine name from current directory name
NAME=$(basename $(pwd))
# if remote access is enabled, then there should be
# SPICE_PASSWORD=password
QEMU_AUDIO_DRV=spice
export QEMU_AUDIO_DRV
if [ -n "$SPICE_PASSWORD" ]; then
|
|
|
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
|
else:
if snapshot_mode(options.sock):
send_command(options.sock, "commit")
else:
print >>sys.stderr, "VM is not running in snapshot mode"
sys.exit(1)
TEMPLATE = """#!/bin/sh
# Get machine name from current directory name
NAME=$(basename $(pwd))
# if remote access is enabled, then there should be
# SPICE_PASSWORD=password
QEMU_AUDIO_DRV=spice
export QEMU_AUDIO_DRV
if [ -n "$SPICE_PASSWORD" ]; then
|
︙ | | | ︙ | |
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
|
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \\
-chardev spicevmc,name=usbredir,id=usbredirchardev1 \\
-device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \\
-daemonize -pidfile pid
"""
def cmd_create(parsed_args):
BADSIZE = "Invalid size of %s specifed %s. Should have K, M or G suffix"
global template
if not parsed_args.image and not validate_size(parsed_args.size):
print >>sys.stderr, BADSIZE % ("disk", parsed_args.size)
sys.exit(1)
if not validate_size(parsed_args.mem):
print >>sys.stderr, BADSIZE % ("memory", parsed_args.size)
sys.exit(1)
drivename = "drive0.qcow2"
options = {'qemubinary':'qemu-system-x86_64',
"accel":"-enable-kvm",
"memory":"1024M",
"vga":'qxl',
"drive":"-drive media=disk,index=0,if={interface},file={image}",
"cdrom":"-drive media=cdrom,index=2,if=ide",
"sound":"-soundhw hda",
"usb":"-usb"}
macaddr = ":".join(map(lambda x: "%02x" % ord(x),
chr(0x52) + os.urandom(5)))
if parsed_args.shared:
machinedir = os.path.join(config.get("directories", "SharedVMs"),
parsed_args.machine)
dirmode = 0755
else:
machinedir = os.path.join(os.environ["HOME"], "VWs",
parsed_args.machine)
|
>
|
<
|
|
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
|
-device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on \\
-chardev spicevmc,name=usbredir,id=usbredirchardev1 \\
-device usb-redir,chardev=usbredirchardev1,id=usbredirdev1 \\
-daemonize -pidfile pid
"""
def cmd_create(parsed_args):
""" vws create - create new VM """
BADSIZE = "Invalid size of %s specifed %s. Should have K, M or G suffix"
global TEMPLATE
if not parsed_args.image and not validate_size(parsed_args.size):
print >>sys.stderr, BADSIZE % ("disk", parsed_args.size)
sys.exit(1)
if not validate_size(parsed_args.mem):
print >>sys.stderr, BADSIZE % ("memory", parsed_args.size)
sys.exit(1)
drivename = "drive0.qcow2"
options = {'qemubinary':'qemu-system-x86_64',
"accel":"-enable-kvm",
"memory":"1024M",
"vga":'qxl',
"drive":"-drive media=disk,index=0,if={interface},file={image}",
"cdrom":"-drive media=cdrom,index=2,if=ide",
"sound":"-soundhw hda",
"usb":"-usb"}
macaddr = ":".join(["%02x" % ord(x) for x in chr(0x52) + os.urandom(5)])
if parsed_args.shared:
machinedir = os.path.join(config.get("directories", "SharedVMs"),
parsed_args.machine)
dirmode = 0755
else:
machinedir = os.path.join(os.environ["HOME"], "VWs",
parsed_args.machine)
|
︙ | | | ︙ | |
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
|
os.chdir(machinedir)
else:
print >>sys.stderr, "Creating new image file of %s" % parsed_args.size
os.chdir(machinedir)
os.system("qemu-img create -f qcow2 %s %s" %
(drivename, parsed_args.size))
options["drive"] = options["drive"].format(**driveopts)
if hasattr(parsed_args, "debug") and parsed_args.debug:
print repr(driveopts), repr(options["drive"])
print repr(options)
with open("start", "w") as script:
script.write(template.format(**options))
os.chmod('start', dirmode)
# If installation media is specified vws start for new vm
if parsed_args.install:
start_opts = Namespace(machine=parsed_args.machine,
command='start', cdrom=[parsed_args.install],
dir=machinedir, stopped=True, snapshot=False,
args="", gui=True)
try:
cmd_start(start_opts)
finally:
start_opts.sock.shutdown(socket.SHUT_RDWR)
#
# Utility functions for arg parsing
#
def new_command(cmds, name, **kwargs):
"""
Adds a subparser and adds a machine name argument to it
"""
p = cmds.add_parser(name, **kwargs)
p.add_argument('machine', type=str, help='name of vm to operate on')
return p
#
# prepare defaults for config
#
arch = os.uname()[4]
if re.match("i[3-9]86", arch):
arch = "i386"
|
>
|
>
|
|
|
|
|
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
|
os.chdir(machinedir)
else:
print >>sys.stderr, "Creating new image file of %s" % parsed_args.size
os.chdir(machinedir)
os.system("qemu-img create -f qcow2 %s %s" %
(drivename, parsed_args.size))
# pylint: disable=star-args
options["drive"] = options["drive"].format(**driveopts)
if hasattr(parsed_args, "debug") and parsed_args.debug:
print repr(driveopts), repr(options["drive"])
print repr(options)
with open("start", "w") as script:
script.write(TEMPLATE.format(**options))
os.chmod('start', dirmode)
# If installation media is specified vws start for new vm
if parsed_args.install:
start_opts = Namespace(machine=parsed_args.machine,
command='start', cdrom=[parsed_args.install],
dir=machinedir, stopped=True, snapshot=False,
args="", gui=True)
try:
cmd_start(start_opts)
finally:
# pylint: disable=no-member
start_opts.sock.shutdown(socket.SHUT_RDWR)
#
# Utility functions for arg parsing
#
def new_command(cmd_parser, name, **kwargs):
"""
Adds a subparser and adds a machine name argument to it
"""
parser = cmd_parser.add_parser(name, **kwargs)
parser.add_argument('machine', type=str, help='name of vm to operate on')
return parser
#
# prepare defaults for config
#
arch = os.uname()[4]
if re.match("i[3-9]86", arch):
arch = "i386"
|
︙ | | | ︙ | |