This repository was archived by the owner on Mar 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.py
More file actions
1976 lines (1567 loc) · 58.7 KB
/
cli.py
File metadata and controls
1976 lines (1567 loc) · 58.7 KB
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
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
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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
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
493
494
495
496
497
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
531
532
533
534
535
536
537
538
539
540
541
542
543
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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Utility functions for the command line drivers
#
# Copyright 2006-2007 Red Hat, Inc.
# Jeremy Katz <katzj@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
import os
import sys
import logging
import logging.handlers
import gettext
import locale
import re
import difflib
import tempfile
import optparse
import shlex
import libvirt
import virtinst
from virtinst import _util
from _util import log_exception
from _util import listify
from virtinst import _gettext as _
from virtinst import Guest
from virtinst import VirtualNetworkInterface
from virtinst import VirtualGraphics
from virtinst import VirtualAudio
from virtinst import VirtualDisk
from virtinst import VirtualCharDevice
from virtinst import VirtualDevice
from virtinst import User
DEFAULT_POOL_PATH = "/var/lib/libvirt/images"
DEFAULT_POOL_NAME = "default"
MIN_RAM = 64
force = False
quiet = False
doprompt = True
####################
# CLI init helpers #
####################
class VirtStreamHandler(logging.StreamHandler):
def emit(self, record):
"""
Based on the StreamHandler code from python 2.6: ripping out all
the unicode handling and just uncoditionally logging seems to fix
logging backtraces with unicode locales (for me at least).
No doubt this is atrocious, but it WORKSFORME!
"""
try:
msg = self.format(record)
stream = self.stream
fs = "%s\n"
stream.write(fs % msg)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
class VirtOptionParser(optparse.OptionParser):
'''Subclass to get print_help to work properly with non-ascii text'''
def _get_encoding(self, f):
encoding = getattr(f, "encoding", None)
if not encoding:
(dummy, encoding) = locale.getlocale()
if not encoding:
encoding = "UTF-8"
return encoding
def print_help(self, file=None):
if file is None:
file = sys.stdout
encoding = self._get_encoding(file)
helpstr = self.format_help()
try:
encodedhelp = helpstr.encode(encoding, "replace")
except UnicodeError:
# I don't know why the above fails hard, unicode makes my head
# spin. Just printing the format_help() output seems to work
# quite fine, with the occasional character ?.
encodedhelp = helpstr
file.write(encodedhelp)
class VirtHelpFormatter(optparse.IndentedHelpFormatter):
"""
Subclass the default help formatter to allow printing newline characters
in --help output. The way we do this is a huge hack :(
Inspiration: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6df6e6b541a15bc2/09f28e26af0699b1
"""
oldwrap = None
def format_option(self, option):
self.oldwrap = optparse.textwrap.wrap
ret = []
try:
optparse.textwrap.wrap = self._textwrap_wrapper
ret = optparse.IndentedHelpFormatter.format_option(self, option)
finally:
optparse.textwrap.wrap = self.oldwrap
return ret
def _textwrap_wrapper(self, text, width):
ret = []
for line in text.split("\n"):
ret.extend(self.oldwrap(line, width))
return ret
def setupParser(usage=None):
parse_class = VirtOptionParser
parser = parse_class(usage=usage,
formatter=VirtHelpFormatter(),
version=virtinst.__version__)
return parser
def setupGettext():
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain("virtinst")
gettext.install("virtinst")
def earlyLogging():
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
def setupLogging(appname, debug=False, do_quiet=False):
global quiet
quiet = do_quiet
vi_dir = os.path.expanduser("~/.virtinst")
if not os.access(vi_dir, os.W_OK):
if os.path.exists(vi_dir):
raise RuntimeError("No write access to directory %s" % vi_dir)
try:
os.mkdir(vi_dir, 0751)
except IOError, e:
raise RuntimeError("Could not create directory %s: %s" %
(vi_dir, e))
dateFormat = "%a, %d %b %Y %H:%M:%S"
fileFormat = ("[%(asctime)s " + appname + " %(process)d] "
"%(levelname)s (%(module)s:%(lineno)d) %(message)s")
streamErrorFormat = "%(levelname)-8s %(message)s"
filename = os.path.join(vi_dir, appname + ".log")
rootLogger = logging.getLogger()
# Undo early logging
for handler in rootLogger.handlers:
rootLogger.removeHandler(handler)
rootLogger.setLevel(logging.DEBUG)
fileHandler = logging.handlers.RotatingFileHandler(filename, "ae",
1024 * 1024, 5)
fileHandler.setFormatter(logging.Formatter(fileFormat,
dateFormat))
rootLogger.addHandler(fileHandler)
streamHandler = VirtStreamHandler(sys.stderr)
if debug:
streamHandler.setLevel(logging.DEBUG)
streamHandler.setFormatter(logging.Formatter(fileFormat,
dateFormat))
else:
if quiet:
level = logging.ERROR
else:
level = logging.WARN
streamHandler.setLevel(level)
streamHandler.setFormatter(logging.Formatter(streamErrorFormat))
rootLogger.addHandler(streamHandler)
# Register libvirt handler
def libvirt_callback(ignore, err):
if err[3] != libvirt.VIR_ERR_ERROR:
# Don't log libvirt errors: global error handler will do that
logging.warn("Non-error from libvirt: '%s'", err[2])
libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
# Register python error handler to log exceptions
def exception_log(type, val, tb):
import traceback
s = traceback.format_exception(type, val, tb)
logging.exception("".join(s))
sys.__excepthook__(type, val, tb)
sys.excepthook = exception_log
# Log the app command string
logging.debug("Launched with command line:\n%s", " ".join(sys.argv))
#######################################
# Libvirt connection helpers #
#######################################
_virtinst_uri_magic = "__virtinst_test__"
def _is_virtinst_test_uri(uri):
return uri and uri.startswith(_virtinst_uri_magic)
def _open_test_uri(uri):
"""
This hack allows us to fake various drivers via passing a magic
URI string to virt-*. Helps with testing
"""
uri = uri.replace(_virtinst_uri_magic, "")
ret = uri.split(",", 1)
uri = ret[0]
opts = parse_optstr(len(ret) > 1 and ret[1] or "")
conn = open_connection(uri)
def sanitize_xml(xml):
orig = xml
xml = re.sub("arch='.*'", "arch='i686'", xml)
xml = re.sub("domain type='.*'", "domain type='test'", xml)
xml = re.sub("machine type='.*'", "", xml)
xml = re.sub(">exe<", ">hvm<", xml)
logging.debug("virtinst test sanitizing diff\n:%s",
"\n".join(difflib.unified_diff(orig.split("\n"),
xml.split("\n"))))
return xml
# Need tmpfile names to be deterministic
if "predictable" in opts:
def fakemkstemp(prefix, *args, **kwargs):
ignore = args
ignore = kwargs
filename = os.path.join(".", prefix)
return os.open(filename, os.O_RDWR | os.O_CREAT), filename
tempfile.mkstemp = fakemkstemp
_util.randomMAC = lambda type_: "00:11:22:33:44:55"
_util.uuidToString = lambda r: "00000000-1111-2222-3333-444444444444"
# Fake remote status
if "remote" in opts:
_util.is_uri_remote = lambda uri_: True
# Fake capabilities
if "caps" in opts:
capsxml = file(opts["caps"]).read()
conn.getCapabilities = lambda: capsxml
if ("qemu" in opts) or ("xen" in opts) or ("lxc" in opts):
conn.getVersion = lambda: 10000000000
origcreate = conn.createLinux
origdefine = conn.defineXML
def newcreate(xml, flags):
xml = sanitize_xml(xml)
return origcreate(xml, flags)
def newdefine(xml):
xml = sanitize_xml(xml)
return origdefine(xml)
conn.createLinux = newcreate
conn.defineXML = newdefine
if "qemu" in opts:
conn.getURI = lambda: "qemu+abc:///system"
if "xen" in opts:
conn.getURI = lambda: "xen+abc:///"
if "lxc" in opts:
conn.getURI = lambda: "lxc+abc:///"
# These need to come after the HV setter, since that sets a default
# conn version
if "connver" in opts:
ver = int(opts["connver"])
def newconnversion():
return ver
conn.getVersion = newconnversion
if "libver" in opts:
ver = int(opts["libver"])
def newlibversion(drv=None):
if drv:
return (ver, ver)
return ver
libvirt.getVersion = newlibversion
setattr(conn, "_virtinst__fake_conn", True)
return conn
def getConnection(uri):
if (uri and not User.current().has_priv(User.PRIV_CREATE_DOMAIN, uri)):
fail(_("Must be root to create Xen guests"))
# Hack to facilitate virtinst unit testing
if _is_virtinst_test_uri(uri):
return _open_test_uri(uri)
logging.debug("Requesting libvirt URI %s", (uri or "default"))
conn = open_connection(uri)
logging.debug("Received libvirt URI %s", conn.getURI())
return conn
def open_connection(uri):
open_flags = 0
valid_auth_options = [libvirt.VIR_CRED_AUTHNAME,
libvirt.VIR_CRED_PASSPHRASE,
libvirt.VIR_CRED_EXTERNAL]
authcb = do_creds
authcb_data = None
return libvirt.openAuth(uri, [valid_auth_options, authcb, authcb_data],
open_flags)
def do_creds(creds, cbdata):
try:
return _do_creds(creds, cbdata)
except:
log_exception("Error in creds callback.")
raise
def _do_creds(creds, cbdata_ignore):
if (len(creds) == 1 and
creds[0][0] == libvirt.VIR_CRED_EXTERNAL and
creds[0][2] == "PolicyKit"):
return _do_creds_polkit(creds[0][1])
for cred in creds:
if cred[0] == libvirt.VIR_CRED_EXTERNAL:
return -1
return _do_creds_authname(creds)
# PolicyKit auth
def _do_creds_polkit(action):
if os.getuid() == 0:
logging.debug("Skipping policykit check as root")
return 0 # Success
logging.debug("Doing policykit for %s", action)
import subprocess
import commands
bin_path = "/usr/bin/polkit-auth"
if not os.path.exists(bin_path):
logging.debug("%s not present, skipping polkit auth.", bin_path)
return 0
cmdstr = "%s %s" % (bin_path, "--explicit")
output = commands.getstatusoutput(cmdstr)
if output[1].count(action):
logging.debug("User already authorized for %s.", action)
# Hide spurious output from polkit-auth
popen_stdout = subprocess.PIPE
popen_stderr = subprocess.PIPE
else:
popen_stdout = None
popen_stderr = None
# Force polkit prompting to be text mode. Not strictly required, but
# launching a dialog is overkill.
env = os.environ.copy()
env["POLKIT_AUTH_FORCE_TEXT"] = "set"
cmd = [bin_path, "--obtain", action]
proc = subprocess.Popen(cmd, env=env, stdout=popen_stdout,
stderr=popen_stderr)
out, err = proc.communicate()
if out and popen_stdout:
logging.debug("polkit-auth stdout: %s", out)
if err and popen_stderr:
logging.debug("polkit-auth stderr: %s", err)
return 0
# SASL username/pass auth
def _do_creds_authname(creds):
retindex = 4
for cred in creds:
credtype, prompt, ignore, ignore, ignore = cred
prompt += ": "
res = cred[retindex]
if credtype == libvirt.VIR_CRED_AUTHNAME:
res = raw_input(prompt)
elif credtype == libvirt.VIR_CRED_PASSPHRASE:
import getpass
res = getpass.getpass(prompt)
else:
logging.debug("Unknown auth type in creds callback: %d", credtype)
return -1
cred[retindex] = res
return 0
##############################
# Misc CLI utility functions #
##############################
def fail(msg, do_exit=True):
"""
Convenience function when failing in cli app
"""
logging.error(msg)
log_exception()
if do_exit:
_fail_exit()
def print_stdout(msg, do_force=False):
if do_force or not quiet:
print msg
def print_stderr(msg):
logging.debug(msg)
print >> sys.stderr, msg
def _fail_exit():
sys.exit(1)
def nice_exit():
print_stdout(_("Exiting at user request."))
sys.exit(0)
def virsh_start_cmd(guest):
return ("virsh --connect %s start %s" % (guest.get_uri(), guest.name))
def install_fail(guest):
virshcmd = virsh_start_cmd(guest)
print_stderr(
_("Domain installation does not appear to have been successful.\n"
"If it was, you can restart your domain by running:\n"
" %s\n"
"otherwise, please restart your installation.") % virshcmd)
sys.exit(1)
def build_default_pool(guest):
if not virtinst.util.is_storage_capable(guest.conn):
# VirtualDisk will raise an error for us
return
pool = None
try:
pool = guest.conn.storagePoolLookupByName(DEFAULT_POOL_NAME)
except libvirt.libvirtError:
pass
if pool:
return
try:
logging.debug("Attempting to build default pool with target '%s'",
DEFAULT_POOL_PATH)
defpool = virtinst.Storage.DirectoryPool(conn=guest.conn,
name=DEFAULT_POOL_NAME,
target_path=DEFAULT_POOL_PATH)
defpool.install(build=True, create=True, autostart=True)
except Exception, e:
raise RuntimeError(_("Couldn't create default storage pool '%s': %s") %
(DEFAULT_POOL_PATH, str(e)))
def partition(string, sep):
if not string:
return (None, None, None)
if string.count(sep):
splitres = string.split(sep, 1)
ret = (splitres[0], sep, splitres[1])
else:
ret = (string, None, None)
return ret
#######################
# CLI Prompting utils #
#######################
def set_force(val=True):
global force
force = val
def set_prompt(prompt=True):
# Set whether we allow prompts, or fail if a prompt pops up
global doprompt
doprompt = prompt
def is_prompt():
return doprompt
def yes_or_no_convert(s):
if s is None:
return None
s = s.lower()
if s in ("y", "yes", "1", "true", "t"):
return True
elif s in ("n", "no", "0", "false", "f"):
return False
return None
def yes_or_no(s):
ret = yes_or_no_convert(s)
if ret == None:
raise ValueError(_("A yes or no response is required"))
return ret
def prompt_for_input(noprompt_err, prompt="", val=None, failed=False):
if val is not None:
return val
if force or not is_prompt():
if failed:
# We already failed validation in a previous function, just exit
_fail_exit()
fail(noprompt_err)
print_stdout(prompt + " ", do_force=True)
sys.stdout.flush()
return sys.stdin.readline().strip()
def prompt_for_yes_or_no(warning, question):
"""catches yes_or_no errors and ensures a valid bool return"""
if force:
logging.debug("Forcing return value of True to prompt '%s'")
return True
errmsg = warning + _(" (Use --prompt or --force to override)")
while 1:
msg = warning
if question:
msg += ("\n" + question)
inp = prompt_for_input(errmsg, msg, None)
try:
res = yes_or_no(inp)
break
except ValueError, e:
logging.error(e)
continue
return res
def prompt_loop(prompt_txt, noprompt_err, passed_val, obj, param_name,
err_txt="%s", func=None):
"""
Prompt the user with 'prompt_txt' for a value. Set 'obj'.'param_name'
to the entered value. If it errors, use 'err_txt' to print a error
message, and then re prompt.
"""
failed = False
while True:
passed_val = prompt_for_input(noprompt_err, prompt_txt, passed_val,
failed)
try:
if func:
return func(passed_val)
setattr(obj, param_name, passed_val)
break
except (ValueError, RuntimeError), e:
logging.error(err_txt, e)
passed_val = None
failed = True
# Specific function for disk prompting. Returns a validated VirtualDisk
# device.
#
def disk_prompt(conn, origpath, origsize, origsparse,
prompt_txt=None,
warn_overwrite=False, check_size=True,
path_to_clone=None, origdev=None):
askmsg = _("Do you really want to use this disk (yes or no)")
retry_path = True
no_path_needed = (origdev and
(origdev.vol_install or
origdev.vol_object or
origdev.can_be_empty()))
def prompt_path(chkpath, chksize):
"""
Prompt for disk path if necc
"""
msg = None
patherr = _("A disk path must be specified.")
if path_to_clone:
patherr = (_("A disk path must be specified to clone '%s'.") %
path_to_clone)
if not prompt_txt:
msg = _("What would you like to use as the disk (file path)?")
if not chksize is None:
msg = _("Please enter the path to the file you would like to "
"use for storage. It will have size %sGB.") % chksize
if not no_path_needed:
path = prompt_for_input(patherr, prompt_txt or msg, chkpath)
else:
path = None
return path
def prompt_size(chkpath, chksize, path_exists):
"""
Prompt for disk size if necc.
"""
sizeerr = _("A size must be specified for non-existent disks.")
size_prompt = _("How large would you like the disk (%s) to "
"be (in gigabytes)?") % chkpath
if (not chkpath or
path_exists or
chksize is not None or
not check_size):
return False, chksize
try:
chksize = prompt_loop(size_prompt, sizeerr, chksize, None, None,
func=float)
return False, chksize
except Exception, e:
# Path is probably bogus, raise the error
fail(str(e), do_exit=not is_prompt())
return True, chksize
def prompt_path_exists(dev):
"""
Prompt if disk file already exists and preserve mode is not used
"""
does_collide = (path_exists and
dev.type == dev.TYPE_FILE and
dev.device == dev.DEVICE_DISK)
msg = (_("This will overwrite the existing path '%s'" % dev.path))
if not does_collide:
return False
if warn_overwrite or is_prompt():
return not prompt_for_yes_or_no(msg, askmsg)
return False
def prompt_inuse_conflict(dev):
"""
Check if disk is inuse by another guest
"""
msg = (_("Disk %s is already in use by another guest" % dev.path))
if not dev.is_conflict_disk(conn):
return False
return not prompt_for_yes_or_no(msg, askmsg)
def prompt_size_conflict(dev):
"""
Check if specified size exceeds available storage
"""
isfatal, errmsg = dev.is_size_conflict()
if isfatal:
fail(errmsg, do_exit=not is_prompt())
return True
if errmsg:
return not prompt_for_yes_or_no(errmsg, askmsg)
return False
while 1:
# If we fail within the loop, reprompt for size and path
if not retry_path:
origpath = None
origsize = None
retry_path = False
# Get disk path
path = prompt_path(origpath, origsize)
path_exists = VirtualDisk.path_exists(conn, path)
# Get storage size
didfail, size = prompt_size(path, origsize, path_exists)
if didfail:
continue
# Build disk object for validation
try:
if origdev:
dev = origdev
if path is not None:
dev.path = path
if size is not None:
dev.size = size
else:
dev = VirtualDisk(conn=conn, path=path, size=size,
sparse=origsparse)
except ValueError, e:
if is_prompt():
logging.error(e)
continue
else:
fail(_("Error with storage parameters: %s" % str(e)))
# Check if path exists
if prompt_path_exists(dev):
continue
# Check disk in use by other guests
if prompt_inuse_conflict(dev):
continue
# Check if disk exceeds available storage
if prompt_size_conflict(dev):
continue
# Passed all validation, return disk instance
return dev
#######################
# Validation wrappers #
#######################
name_missing = _("--name is required")
ram_missing = _("--ram amount in MB is required")
def get_name(name, guest, image_name=None):
prompt_txt = _("What is the name of your virtual machine?")
err_txt = name_missing
if name is None:
name = image_name
prompt_loop(prompt_txt, err_txt, name, guest, "name")
def get_memory(memory, guest, image_memory=None):
prompt_txt = _("How much RAM should be allocated (in megabytes)?")
err_txt = ram_missing
def check_memory(mem):
mem = int(mem)
if mem < MIN_RAM:
raise ValueError(_("Installs currently require %d megs "
"of RAM.") % MIN_RAM)
guest.memory = mem
if memory is None and image_memory is not None:
memory = int(image_memory) / 1024
prompt_loop(prompt_txt, err_txt, memory, guest, "memory",
func=check_memory)
def get_uuid(uuid, guest):
if uuid:
try:
guest.uuid = uuid
except ValueError, e:
fail(e)
def get_vcpus(guest, vcpus, check_cpu, image_vcpus=None):
"""
@param vcpus: value of the option '--vcpus' (str or None)
@param check_cpu: Whether to check that the number virtual cpus requested
does not exceed physical CPUs (bool)
@param guest: virtinst.Guest instance (object)
@param image_vcpus: ? (It's not used currently and should be None.)
"""
if vcpus is None:
if image_vcpus is not None:
vcpus = image_vcpus
else:
vcpus = ""
parse_vcpu(guest, vcpus, image_vcpus)
if check_cpu:
hostinfo = guest.conn.getInfo()
pcpus = hostinfo[4] * hostinfo[5] * hostinfo[6] * hostinfo[7]
if guest.vcpus > pcpus:
msg = _("You have asked for more virtual CPUs (%d) than there "
"are physical CPUs (%d) on the host. This will work, "
"but performance will be poor. ") % (guest.vcpus, pcpus)
askmsg = _("Are you sure? (yes or no)")
if not prompt_for_yes_or_no(msg, askmsg):
nice_exit()
def get_cpuset(guest, cpuset):
conn = guest.conn
if cpuset and cpuset != "auto":
guest.cpuset = cpuset
elif cpuset == "auto":
tmpset = None
try:
tmpset = Guest.generate_cpuset(conn, guest.memory)
except Exception, e:
logging.debug("Not setting cpuset: %s", str(e))
if tmpset:
logging.debug("Auto cpuset is: %s", tmpset)
guest.cpuset = tmpset
return
def _default_network_opts(guest):
opts = ""
if User.current().has_priv(User.PRIV_CREATE_NETWORK, guest.get_uri()):
net = _util.default_network(guest.conn)
opts = "%s=%s" % (net[0], net[1])
else:
opts = "user"
return opts
def digest_networks(guest, options, numnics=1):
macs = listify(options.mac)
networks = listify(options.network)
bridges = listify(options.bridge)
if bridges and networks:
fail(_("Cannot mix both --bridge and --network arguments"))
if bridges:
# Convert old --bridges to --networks
networks = map(lambda b: "bridge:" + b, bridges)
def padlist(l, padsize):
l = listify(l)
l.extend((padsize - len(l)) * [None])
return l
# If a plain mac is specified, have it imply a default network
networks = padlist(networks, max(len(macs), numnics))
macs = padlist(macs, len(networks))
for idx in range(len(networks)):
if networks[idx] is None:
networks[idx] = _default_network_opts(guest)
return networks, macs
def get_networks(guest, networks, macs):
for idx in range(len(networks)):
mac = macs[idx]
netstr = networks[idx]
try:
dev = parse_network(guest, netstr, mac=mac)
guest.add_device(dev)
except Exception, e:
fail(_("Error in network device parameters: %s") % str(e))
def set_os_variant(guest, distro_type, distro_variant):
if not distro_type and not distro_variant:
# Default to distro autodetection
guest.set_os_autodetect(True)
return
if (distro_type and str(distro_type).lower() != "none"):
guest.set_os_type(distro_type)
if (distro_variant and str(distro_variant).lower() != "none"):
guest.set_os_variant(distro_variant)
def digest_graphics(guest, options, default_override=None):
vnc = options.vnc
vncport = options.vncport
vnclisten = options.vnclisten
nographics = options.nographics
sdl = options.sdl
keymap = options.keymap
graphics = options.graphics
if graphics and (vnc or sdl or keymap or vncport or vnclisten):
fail(_("Cannot mix --graphics and old style graphical options"))
optnum = sum(map(bool, [vnc, nographics, sdl, graphics]))
if optnum > 1:
raise ValueError(_("Can't specify more than one of VNC, SDL, "
"--graphics or --nographics"))
if graphics:
return graphics
if optnum == 0:
# If no graphics specified, choose a default
if default_override is True:
vnc = True
elif default_override is False:
nographics = True
else:
if guest.installer.is_container():
logging.debug("Container guest, defaulting to nographics")
nographics = True
elif "DISPLAY" in os.environ.keys():
logging.debug("DISPLAY is set: graphics defaulting to VNC.")
vnc = True
else:
logging.debug("DISPLAY is not set: defaulting to nographics.")
nographics = True
# Build a --graphics command line from old style opts
optstr = ((vnc and "vnc") or
(sdl and "sdl") or
(nographics and ("none")))
if vnclisten:
optstr += ",listen=%s" % vnclisten
if vncport:
optstr += ",port=%s" % vncport
if keymap:
optstr += ",keymap=%s" % keymap
logging.debug("--graphics compat generated: %s", optstr)
return [optstr]
def get_graphics(guest, graphics):
for optstr in graphics:
try:
dev = parse_graphics(guest, optstr)
except Exception, e:
fail(_("Error in graphics device parameters: %s") % str(e))
if dev:
guest.add_device(dev)
def get_video(guest, video_models=None):
video_models = video_models or []
if guest.get_devices(VirtualDevice.VIRTUAL_DEV_GRAPHICS):
if not video_models:
video_models.append(None)
for model in video_models:
guest.add_device(parse_video(guest, model))
def get_sound(old_sound_bool, sound_opts, guest):
if not sound_opts:
if old_sound_bool:
# Use os default
guest.sound_devs.append(VirtualAudio(conn=guest.conn))
return
for opts in listify(sound_opts):
guest.add_device(parse_sound(guest, opts))
def get_hostdevs(hostdevs, guest):
if not hostdevs:
return
for devname in hostdevs:
guest.add_device(parse_hostdev(guest, devname))
def get_smartcard(guest, sc_opts):
for sc in listify(sc_opts):
try:
dev = parse_smartcard(guest, sc)
except Exception, e:
fail(_("Error in smartcard device parameters: %s") % str(e))
if dev:
guest.add_device(dev)