~ubuntu-branches/ubuntu/quantal/virtinst/quantal-proposed

« back to all changes in this revision

Viewing changes to virtinst/cli.py

  • Committer: Bazaar Package Importer
  • Author(s): Jean-Louis Dupond
  • Date: 2010-05-05 03:32:42 UTC
  • mfrom: (1.3.13 sid)
  • Revision ID: james.westby@ubuntu.com-20100505033242-um6f6pjcc89i07m0
Tags: 0.500.3-1ubuntu1
* Merge from debian unstable. (LP: #590068)  Remaining changes:
  - debian/patches/9001_Ubuntu.patch:
     + Added lucid and maverick to OS list and enable virtio for it.
  - debian/patches/0003-Fix-patch-to-keyboard-configuration.patch: disable
    as the keyboard config in Ubuntu is still in /etc/default/console-setup
    and this was causing virt-manager to always default to a en-us
    keyboard. (LP: #524318)
  - debian/control: added acl package to depends. (LP: #533048)
  - Demote virt-viewer to Suggests, as it's in universe.
  - Recommends libvirt-bin (LP: #215084)
* debian/patches/9002-add-ca-keymap.patch: dropped, its now in upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
import os, sys
23
23
import logging
24
24
import logging.handlers
25
 
import locale
 
25
import gettext, locale
26
26
import optparse
27
27
from optparse import OptionValueError, OptionParser
28
28
 
30
30
import _util
31
31
import virtinst
32
32
from virtinst import CapabilitiesParser, VirtualNetworkInterface, \
33
 
                     VirtualGraphics, VirtualAudio, VirtualDisk, User
 
33
                     VirtualGraphics, VirtualAudio, VirtualDisk, User, \
 
34
                     VirtualVideoDevice
34
35
from virtinst import _virtinst as _
35
36
 
36
37
MIN_RAM = 64
44
45
        _util.is_uri_remote = lambda uri_: True
45
46
    return uri
46
47
 
 
48
class VirtStreamHandler(logging.StreamHandler):
 
49
 
 
50
    def emit(self, record):
 
51
        """
 
52
        Based on the StreamHandler code from python 2.6: ripping out all
 
53
        the unicode handling and just uncoditionally logging seems to fix
 
54
        logging backtraces with unicode locales (for me at least).
 
55
 
 
56
        No doubt this is atrocious, but it WORKSFORME!
 
57
        """
 
58
        try:
 
59
            msg = self.format(record)
 
60
            stream = self.stream
 
61
            fs = "%s\n"
 
62
 
 
63
            stream.write(fs % msg)
 
64
 
 
65
            self.flush()
 
66
        except (KeyboardInterrupt, SystemExit):
 
67
            raise
 
68
        except:
 
69
            self.handleError(record)
 
70
 
47
71
class VirtOptionParser(OptionParser):
48
72
    '''Subclass to get print_help to work properly with non-ascii text'''
49
73
 
56
80
    def print_help(self, file=None):
57
81
        if file is None:
58
82
            file = sys.stdout
 
83
 
59
84
        encoding = self._get_encoding(file)
60
 
        file.write(self.format_help().encode(encoding, "replace"))
 
85
        helpstr = self.format_help()
 
86
        try:
 
87
            encodedhelp = helpstr.encode(encoding, "replace")
 
88
        except UnicodeError:
 
89
            # I don't know why the above fails hard, unicode makes my head
 
90
            # spin. Just printing the format_help() output seems to work
 
91
            # quite fine, with the occasional character ?.
 
92
            encodedhelp = helpstr
 
93
 
 
94
        file.write(encodedhelp)
61
95
 
62
96
class VirtHelpFormatter(optparse.IndentedHelpFormatter):
63
97
    """
64
98
    Subclass the default help formatter to allow printing newline characters
65
99
    in --help output. The way we do this is a huge hack :(
 
100
 
 
101
    Inspiration: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6df6e6b541a15bc2/09f28e26af0699b1
66
102
    """
67
103
    oldwrap = None
68
104
 
80
116
        ret = []
81
117
        for line in text.split("\n"):
82
118
            ret.extend(self.oldwrap(line, width))
83
 
        if ret:
84
 
            print "\n".join(ret)
85
119
        return ret
86
120
#
87
121
# Setup helpers
88
122
#
89
123
 
 
124
def setupParser(usage=None):
 
125
    parse_class = VirtOptionParser
 
126
 
 
127
    parser = parse_class(usage=usage,
 
128
                         formatter=VirtHelpFormatter(),
 
129
                         version=virtinst.__version__)
 
130
    return parser
 
131
 
 
132
def setupGettext():
 
133
    locale.setlocale(locale.LC_ALL, '')
 
134
    gettext.bindtextdomain(virtinst.gettext_app, virtinst.gettext_dir)
 
135
    gettext.install(virtinst.gettext_app, virtinst.gettext_dir)
 
136
 
90
137
def setupLogging(appname, debug=False):
91
138
    # set up logging
92
139
    vi_dir = os.path.expanduser("~/.virtinst")
93
 
    if not os.access(vi_dir,os.W_OK):
94
 
        os.mkdir(vi_dir, 0751)
 
140
    if not os.access(vi_dir, os.W_OK):
 
141
        if os.path.exists(vi_dir):
 
142
            raise RuntimeError("No write access to directory %s" % vi_dir)
 
143
 
 
144
        try:
 
145
            os.mkdir(vi_dir, 0751)
 
146
        except IOError, e:
 
147
            raise RuntimeError("Could not create directory %s: %s" %
 
148
                               (vi_dir, e))
 
149
 
95
150
 
96
151
    dateFormat = "%a, %d %b %Y %H:%M:%S"
97
152
    fileFormat = "[%(asctime)s " + appname + " %(process)d] %(levelname)s (%(module)s:%(lineno)d) %(message)s"
108
163
                                               dateFormat))
109
164
    rootLogger.addHandler(fileHandler)
110
165
 
111
 
    streamHandler = logging.StreamHandler(sys.stderr)
 
166
    streamHandler = VirtStreamHandler(sys.stderr)
112
167
    if debug:
113
168
        streamHandler.setLevel(logging.DEBUG)
114
169
        streamHandler.setFormatter(logging.Formatter(streamDebugFormat,
314
369
    errmsg = warning + _(" (Use --prompt or --force to override)")
315
370
 
316
371
    while 1:
317
 
        inp = prompt_for_input(errmsg, warning + question, None)
 
372
        msg = warning
 
373
        if question:
 
374
            msg += ("\n" + question)
 
375
 
 
376
        inp = prompt_for_input(errmsg, msg, None)
318
377
        try:
319
378
            res = yes_or_no(inp)
320
379
            break
365
424
# Specific function for disk prompting. Returns a validated VirtualDisk
366
425
# device.
367
426
#
368
 
def disk_prompt(prompt_txt, arg_dict, warn_overwrite=False, prompt_size=True):
 
427
def disk_prompt(prompt_txt, arg_dict, warn_overwrite=False, prompt_size=True,
 
428
                path_to_clone=None):
369
429
 
370
430
    retry_path = True
371
431
    conn = arg_dict.get("conn")
383
443
 
384
444
        msg = None
385
445
        patherr = _("A disk path must be specified.")
 
446
        if path_to_clone:
 
447
            patherr = (_("A disk path must be specified to clone '%s'.") %
 
448
                       path_to_clone)
 
449
 
386
450
        if not prompt_txt:
387
451
            msg = _("What would you like to use as the disk (file path)?")
388
452
            if not size is None:
673
737
 
674
738
    return net_init_dicts
675
739
 
676
 
def get_graphics(vnc, vncport, vnclisten, nographics, sdl, keymap, guest):
 
740
def get_graphics(vnc, vncport, vnclisten, nographics, sdl, keymap,
 
741
                 video_models, guest):
 
742
    video_models = video_models or []
 
743
 
677
744
    if ((vnc and nographics) or
678
745
        (vnc and sdl) or
679
746
        (sdl and nographics)):
680
747
        raise ValueError, _("Can't specify more than one of VNC, SDL, "
681
748
                            "or --nographics")
682
749
 
 
750
    for model in video_models:
 
751
        dev = virtinst.VirtualVideoDevice(guest.conn)
 
752
        dev.model_type = model
 
753
        guest.add_device(dev)
 
754
 
683
755
    if not (vnc or nographics or sdl):
684
756
        if "DISPLAY" in os.environ.keys():
685
757
            logging.debug("DISPLAY is set: graphics defaulting to VNC.")
692
764
        guest.graphics_dev = None
693
765
        return
694
766
 
 
767
    # After this point, we are using graphics, so add a video device
 
768
    # if one wasn't passed
 
769
    if not video_models:
 
770
        guest.add_device(VirtualVideoDevice(conn=guest.conn))
 
771
 
695
772
    if sdl is not None:
696
773
        guest.graphics_dev = VirtualGraphics(type=VirtualGraphics.TYPE_SDL)
697
774
        return
717
794
 
718
795
        guest.graphics_dev.keymap = use_keymap
719
796
 
720
 
def get_sound(sound, guest):
721
 
 
722
 
    # Sound is just a boolean value, so just specify a default of 'es1370'
723
 
    # model since this should provide audio out of the box for most modern
724
 
    # distros
725
 
    if sound:
726
 
        guest.sound_devs.append(VirtualAudio(model="es1370"))
 
797
def get_sound(old_sound_bool, sound_opts, guest):
 
798
    if not sound_opts:
 
799
        if old_sound_bool:
 
800
            # Use os default
 
801
            guest.sound_devs.append(VirtualAudio(conn=guest.conn))
 
802
        return
 
803
 
 
804
    for model in listify(sound_opts):
 
805
        dev = VirtualAudio(conn=guest.conn)
 
806
        dev.model = model
 
807
        guest.add_device(dev)
 
808
 
727
809
 
728
810
def get_hostdevs(hostdevs, guest):
729
811
    if not hostdevs:
734
816
                                                          name=devname)
735
817
        guest.hostdevs.append(dev)
736
818
 
737
 
def get_video(video_models, guest):
738
 
    if not video_models:
739
 
        return
740
 
 
741
 
    for model in video_models:
742
 
        dev = virtinst.VirtualVideoDevice(guest.conn)
743
 
        dev.model_type = model
744
 
        guest.add_device(dev)
745
 
 
746
819
### Option parsing
747
820
def check_before_store(option, opt_str, value, parser):
748
821
    if len(value) == 0: