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

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
#!/usr/bin/python -tt
#
# Script to set up a Xen guest and kick off an install
#
# Copyright 2005-2006  Red Hat, Inc.
# Jeremy Katz <katzj@redhat.com>
# Option handling added by Andrew Puch <apuch@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 time
import errno
import re
import logging
import optparse
from optparse import OptionGroup

import urlgrabber.progress as progress

import libvirt
import virtinst
import virtinst.CapabilitiesParser
import virtinst.cli as cli
import virtinst.util as util
import virtinst._util as _util
from virtinst.VirtualCharDevice import VirtualCharDevice
from virtinst.VirtualDevice import VirtualDevice
from virtinst.cli import fail, print_stdout, print_stderr

cli.setupGettext()

DEFAULT_POOL_PATH = "/var/lib/libvirt/images"
DEFAULT_POOL_NAME = "default"

install_methods = "--location URL, --cdrom CD/ISO, --pxe, --import, --boot hd|cdrom|..."
install_missing = (_("An install method must be specified\n(%(methods)s)") %
                   {"methods" : install_methods })
disk_missing = _("--disk storage must be specified (override with --nodisks)")

def install_specified(location, cdpath, pxe, import_install):
    return bool(pxe or cdpath or location or import_install)

def cdrom_specified(guest, diskopts=None):
    for disk in guest.disks:
        if disk.device == virtinst.VirtualDisk.DEVICE_CDROM:
            return True

    # Probably haven't set up disks yet
    if not guest.disks and diskopts:
        for opts in diskopts:
            if opts.count("device=cdrom"):
                return True

    return False

def storage_specified(files, disks, nodisks):
    return bool(files or disks or nodisks)

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)
        newpool = defpool.install(build=True, create=True)
        newpool.setAutostart(True)
    except Exception, e:
        raise RuntimeError(_("Couldn't create default storage pool '%s': %s") %
                             (DEFAULT_POOL_PATH, str(e)))

def supports_pxe(guest):
    """
    Return False if we are pretty sure the config doesn't support PXE
    """
    for nic in guest.get_devices("interface"):
        if nic.type == nic.TYPE_USER:
            continue
        if nic.type != nic.TYPE_VIRTUAL:
            return True

        try:
            xml = nic.conn.networkLookupByName(nic.network).XMLDesc(0)
            if util.get_xml_path(xml, "/network/ip/dhcp/bootp/@file"):
                return True

            forward = util.get_xml_path(xml, "/network/forward/@mode")
            if forward and forward != "nat":
                return True
        except:
            _util.log_exception("Error checking if PXE supported")
            return True

    return False

def parse_boot_option(guest, optstring):
    """
    Helper to parse --boot string
    """
    ignore, opts = cli.parse_optstr(optstring)
    optlist = map(lambda x: x[0], cli.parse_optstr_tuples(optstring))
    menu = None

    def set_param(paramname, dictname, val=None):
        val = cli.get_opt_param(opts, dictname, val)
        if val == None:
            return

        setattr(guest.installer.bootconfig, paramname, val)

    # Convert menu= value
    if "menu" in opts:
        menustr = opts["menu"]
        menu = None

        if menustr.lower() == "on":
            menu = True
        elif menustr.lower() == "off":
            menu = False
        else:
            menu = cli.yes_or_no_convert(menustr)

        if menu == None:
            fail(_("--boot menu must be 'on' or 'off'"))

    set_param("enable_bootmenu", "menu", menu)
    set_param("kernel", "kernel")
    set_param("initrd", "initrd")
    set_param("kernel_args", ["kernel_args", "extra_args"])

    # Build boot order
    if opts:
        boot_order = []
        for boot_dev in optlist:
            if not boot_dev in guest.installer.bootconfig.boot_devices:
                continue

            del(opts[boot_dev])
            if boot_dev not in boot_order:
                boot_order.append(boot_dev)

        guest.installer.bootconfig.bootorder = boot_order

    if opts:
        raise ValueError(_("Unknown options %s") % opts.keys())


def parse_char_option(guest, dev_type, optstring):
    """
    Helper to parse --serial/--parallel options
    """
    # Peel the char type off the front
    char_type, opts = cli.parse_optstr(optstring, remove_first=True)
    dev = VirtualCharDevice.get_dev_instance(guest.conn, dev_type, char_type)

    def set_param(paramname, dictname, val=None):
        val = cli.get_opt_param(opts, dictname, val)
        if val == None:
            return

        if not dev.supports_property(paramname):
            raise ValueError(_("%(chartype)s type %(devtype)s does not "
                                "support '%(optname)s' option.") %
                                {"devtype" : dev_type, "chartype": char_type,
                                 "optname" : dictname} )
        setattr(dev, paramname, val)

    def parse_host(key):
        host, ignore, port = cli.partition(opts.get(key), ":")
        if key in opts:
            del(opts[key])

        return host, port

    host, port = parse_host("host")
    bind_host, bind_port = parse_host("bind_host")
    target_addr, target_port = parse_host("target_address")

    set_param("source_path", "path")
    set_param("source_mode", "mode")
    set_param("protocol",   "protocol")
    set_param("source_host", "host", host)
    set_param("source_port", "host", port)
    set_param("bind_host", "bind_host", bind_host)
    set_param("bind_port", "bind_host", bind_port)
    set_param("target_name", "name")
    set_param("target_type", "target_type")
    set_param("target_address", "target_address", target_addr)
    set_param("target_port", "target_address", target_port)

    if opts:
        raise ValueError(_("Unknown options %s") % opts.keys())

    # Try to generate dev XML to perform upfront validation
    dev.get_xml_config()

    return dev

def get_chardevs(char_type, opts, guest):

    for optstr in cli.listify(opts):
        try:
            dev = parse_char_option(guest, char_type, optstr)
            guest.add_device(dev)
        except Exception, e:
            fail(_("Error in %(chartype)s device parameters: %(err)s") %
                 {"chartype": char_type, "err": str(e)})

def parse_watchdog(guest, optstring):
    # Peel the model type off the front
    model, opts = cli.parse_optstr(optstring, remove_first=True)
    dev = virtinst.VirtualWatchdog(guest.conn)

    def set_param(paramname, dictname, val=None):
        val = cli.get_opt_param(opts, dictname, val)
        if val == None:
            return

        setattr(dev, paramname, val)

    set_param("model", "model", model)
    set_param("action", "action")

    if opts:
        raise ValueError(_("Unknown options %s") % opts.keys())

    return dev

def get_watchdog(watchdogs, guest):
    for optstr in cli.listify(watchdogs):
        try:
            dev = parse_watchdog(guest, optstr)
            guest.add_device(dev)
        except Exception, e:
            fail(_("Error in watchdog device parameters: %s") % str(e))

def get_security(security, guest):
    seclist = cli.listify(security)
    secopts = seclist and seclist[0] or None
    if not secopts:
        return

    # Parse security opts
    ignore, opts = cli.parse_optstr(secopts)
    arglist = secopts.split(",")
    secmodel = guest.seclabel

    # Beware, adding boolean options here could upset label comma handling
    mode = cli.get_opt_param(opts, "type")
    label = cli.get_opt_param(opts, "label")

    # Try to fix up label if it contained commas
    if label:
        tmparglist = arglist[:]
        for idx in range(len(tmparglist)):
            arg = tmparglist[idx]
            if not arg.split("=")[0] == "label":
                continue

            for arg in tmparglist[idx + 1:]:
                if arg.count("="):
                    break

                if arg:
                    label += "," + arg
                    del(opts[arg])

            break

    if label:
        secmodel.label = label
        if not mode:
            mode = secmodel.SECLABEL_TYPE_STATIC
    if mode:
        secmodel.type = mode

    if opts:
        raise ValueError(_("Unknown options %s") % opts.keys())

    # Run for validation purposes
    secmodel.get_xml_config()

def parse_disk_option(guest, path, size):
    """helper to properly parse --disk options"""
    abspath = None
    voltuple = None
    volinst = None
    ro = False
    shared = False
    sparse = True
    option_whitelist = ["perms", "cache", "bus", "device", "size", "sparse",
                        "format", "driver_name", "driver_type"]

    # Strip media type
    path, ignore, optstr = cli.partition(path, ",")
    path_type = None
    if path.startswith("path="):
        path_type = "path="
    elif path.startswith("vol="):
        path_type = "vol="
    elif path.startswith("pool="):
        path_type = "pool="

    if path_type:
        path = path[len(path_type):]
    else:
        # Allow a default fallback mode --disk /some/path,foo,rah
        path_type = "path="

    # Parse out comma separated options
    ignore, opts = cli.parse_optstr(optstr)
    for opt_type, opt_val in opts.items():
        if opt_type not in option_whitelist:
            fail(_("Unknown --disk option '%s'.") % opt_type)

        if opt_type == "perms":
            if opt_val == "ro":
                ro = True
            elif opt_val == "sh":
                shared = True
            elif opt_val == "rw":
                pass  # It's default. Nothing to do.
            else:
                fail(_("Unknown '%s' value '%s'" % (opt_type, opt_val)))
        elif opt_type == "size":
            try:
                size = float(opt_val)
            except Exception, e:
                fail(_("Improper value for 'size': %s" % str(e)))
        elif opt_type == "sparse":
            if opt_val == "true":
                sparse = True
            elif opt_val == "false":
                sparse = False
            else:
                fail(_("Unknown '%s' value '%s'") % (opt_type, opt_val))

    # Set simple options from dictionary
    devtype = opts.get("device")
    bus     = opts.get("bus")
    cache   = opts.get("cache")
    fmt     = opts.get("format")
    drvname = opts.get("driver_name")
    drvtype = opts.get("driver_type")

    # We return (path, (poolname, volname), volinst, device, bus, readonly,
    #            shared)
    if path_type == "path=":
        abspath = os.path.abspath(path)
        if os.path.dirname(abspath) == DEFAULT_POOL_PATH:
            build_default_pool(guest)

    elif path_type == "pool=":
        if not size:
            raise ValueError(_("Size must be specified with all 'pool='"))
        if path == DEFAULT_POOL_NAME:
            build_default_pool(guest)
        vc = virtinst.Storage.StorageVolume.get_volume_for_pool(pool_name=path,
                                                                conn=guest.conn)
        vname = virtinst.Storage.StorageVolume.find_free_name(conn=guest.conn,
                                                              pool_name=path,
                                                              name=guest.name,
                                                              suffix=".img")
        volinst = vc(pool_name=path, name=vname, conn=guest.conn,
                     allocation=0, capacity=(size and
                                             size * 1024 * 1024 * 1024))
        if fmt:
            if not hasattr(volinst, "format"):
                raise ValueError(_("Format attribute not supported for this "
                                   "volume type"))
            setattr(volinst, "format", fmt)

        if not sparse:
            volinst.allocation = volinst.capacity

    elif path_type == "vol=":
        if not path.count("/"):
            raise ValueError(_("Storage volume must be specified as "
                               "vol=poolname/volname"))
        vollist = path.split("/")
        voltuple = (vollist[0], vollist[1])
        logging.debug("Parsed volume: as pool='%s' vol='%s'" % \
                      (voltuple[0], voltuple[1]))
        if voltuple[0] == DEFAULT_POOL_NAME:
            build_default_pool(guest)

    if not devtype:
        devtype = virtinst.VirtualDisk.DEVICE_DISK

    # Mapping to VirtualDisk __init__ options
    kwargs = { 'conn' : guest.conn,
               'path': path,
               'size': size,
               'sparse': sparse,
               'volInstall': volinst,
               'volName': voltuple,
               'readOnly': ro,
               'shareable': shared,
               'device': devtype,
               'bus': bus,
               'driverCache': cache,
               'format': fmt,
               'driverName': drvname,
               'driverType': drvtype}

    logging.debug("parse_disk: returning %s" % str(kwargs))
    return kwargs

def get_disk(disk, size, sparse, guest, conn, is_file_path):

    try:
        if is_file_path:
            kwargs = { 'conn': conn, 'path': disk, 'size': size,
                       'sparse': sparse,
                       'device': virtinst.VirtualDisk.DEVICE_DISK }
        else:
            kwargs = parse_disk_option(guest, disk, size)

        d = cli.disk_prompt(None, kwargs)

    except ValueError, e:
        fail(_("Error with storage parameters: %s" % str(e)))

    guest.disks.append(d)

def get_disks(file_paths, disk_paths, size, sparse, nodisks, guest, conn):
    if nodisks:
        if file_paths or disk_paths or size:
            fail(_("Cannot specify storage and use --nodisks"))
        return
    if (file_paths or size or sparse == False) and disk_paths:
        fail(_("Cannot mix --file, --nonsparse, or --file-size with --disk "
               "options. Use --disk PATH[,size=SIZE][,sparse=yes|no]"))
    if (not storage_specified(file_paths, disk_paths, nodisks) and
        not cli.is_prompt()):
        fail(disk_missing)

    is_file_path = (file_paths or (not disk_paths and cli.is_prompt()))
    disk = (file_paths or disk_paths)

    # ensure we have equal length lists
    if (type(disk) == type(size) == list):
        if len(disk) != len(size):
            fail(_("Need to pass size for each disk"))
    elif type(disk) == list:
        size = [ None ] * len(disk)
    elif type(size) == list:
        disk = [ None ] * len(size)

    if type(disk) == list or type(size) == list:
        map(lambda d, s: get_disk(d, s, sparse, guest, conn,
                                  is_file_path), disk, size)
    else:
        get_disk(disk, size, sparse, guest, conn, is_file_path)

def get_networks(macs, bridges, networks, nonetworks, guest):
    if nonetworks:
        if macs:
            fail(_("Cannot use --mac with --nonetworks"))
        if bridges:
            fail(_("Cannot use --bridges with --nonetworks"))
        if networks:
            fail(_("Cannot use --network with --nonetworks"))
        return
    net_kwargs = cli.digest_networks(guest.conn, macs, bridges, networks,
                                     nics=1)
    map(lambda kwargs: cli.get_network(kwargs, guest), net_kwargs)

def prompt_virt(caps, arch, req_virt_type, req_accel):

    supports_hvm   = False
    supports_pv    = False
    supports_accel = False
    for guest in caps.guests:
        if guest.os_type == "hvm":
            supports_hvm = True

        elif guest.os_type == "xen":
            if (len(guest.domains) and
                guest.domains[0].hypervisor_type == "kvm"):
                # Don't prompt user for PV w/ xenner
                continue
            supports_pv = True

    if not arch:
        arch = caps.host.arch

    if not req_virt_type:
        if supports_hvm and supports_pv:
            prompt_txt = _("Would you like a fully virtualized guest "
                           "(yes or no)? This will allow you to run "
                           "unmodified operating systems.")

            if cli.prompt_for_yes_or_no(prompt_txt, ""):
                req_virt_type = "hvm"
            else:
                req_virt_type = "xen"

        elif supports_hvm:
            req_virt_type = "hvm"

        elif supports_pv:
            req_virt_type = "xen"

    # See if that domain supports acceleration
    accel_type = ""
    for guest in caps.guests:
        if guest.os_type == req_virt_type and guest.arch == arch:
            for dom in guest.domains:
                if dom.is_accelerated():
                    supports_accel = True
                    accel_type = dom.hypervisor_type.upper()

    if supports_accel and not req_accel:
        prompt_txt = (_("Would you like to use %s acceleration? "
                        "(yes or no)") % accel_type)

        req_accel = cli.prompt_for_yes_or_no(prompt_txt, "")

    return (req_virt_type, req_accel)


def get_virt_type(conn, options):

    # Set up all virt/hypervisor parameters
    if options.fullvirt and options.paravirt:
        fail(_("Can't do both --hvm and --paravirt"))

    capabilities = virtinst.CapabilitiesParser.parse(conn.getCapabilities())

    # Accelerate request is now the default
    req_accel = True
    req_hv_type = options.hv_type and options.hv_type.lower() or None
    if options.fullvirt:
        req_virt_type = "hvm"
    elif options.paravirt:
        req_virt_type = "xen"
    else:
        # This should force capabilities to give us the most sensible default
        req_virt_type = None

    if cli.is_prompt():
        # User requested prompting but passed no virt type flag, ask for
        # needed info
        req_virt_type, req_accel = prompt_virt(capabilities, options.arch,
                                               req_virt_type, req_accel)

    logging.debug("Requesting virt method '%s', hv type '%s'." %
                  ((req_virt_type and req_virt_type or _("default")),
                   (req_hv_type and req_hv_type or _("default"))))

    arch = options.arch
    if re.match("i.86", arch or ""):
        arch = "i686"

    try:
        (capsguest,
         capsdomain) = virtinst.CapabilitiesParser.guest_lookup(
                        conn=conn,
                        caps=capabilities,
                        os_type=req_virt_type,
                        arch=arch,
                        type=req_hv_type,
                        accelerated=req_accel,
                        machine=options.machine)
    except Exception, e:
        fail(e)

    if (not req_virt_type and
        req_accel and
        _util.is_qemu(conn) and
        capsguest.arch in ["i686", "x86_64"] and
        not capsdomain.is_accelerated()):
        logging.warn("KVM acceleration not available, using '%s'" %
                     capsdomain.hypervisor_type)

    return (capsguest, capsdomain)


def get_install_media(location, cdpath, pxe, livecd, import_install,
                      guest, ishvm):

    found = False
    for m in [pxe, location, cdpath, import_install]:
        if m:
            if found:
                fail(_("Only one install method can be used (%(methods)s)") %
                       {"methods" : install_methods})
            found = True

    if not ishvm:
        if pxe:
            fail(_("Network PXE boot is not supported for paravirtualized "
                   "guests"))
        if cdpath or livecd:
            fail(_("Paravirtualized guests cannot install off cdrom media."))

    if location and virtinst.util.is_uri_remote(guest.conn.getURI()):
        fail(_("--location can not be specified for remote connections."))

    # Make sure some install option is specified
    cdinstall = (cdpath or False)
    if not install_specified(location, cdpath, pxe, import_install):
        cdinstall = cdrom_specified(guest)
        if not cdinstall and not cli.is_prompt():
            fail(install_missing)


    if pxe or import_install:
        return

    try:
        if not location and not cdinstall and cli.is_prompt():
            media_prompt(guest, ishvm)
        else:
            validate_install_media(guest, location, cdpath, cdinstall)
    except ValueError, e:
        fail(_("Error creating cdrom disk: %s" % str(e)))

def media_prompt(guest, ishvm):

    if ishvm:
        prompt_txt = _("What is the install CD-ROM/ISO or URL?")
    else:
        prompt_txt = _("What is the install URL?")

    while 1:
        location = None
        cdpath = None
        media = cli.prompt_for_input("", prompt_txt, None)

        if not len(media):
            continue

        if not ishvm or media.count(":/"):
            location = media
        else:
            cdpath = media

        try:
            validate_install_media(guest, location, cdpath)
        except Exception, e:
            logging.error(str(e))
            continue
        break

def validate_install_media(guest, location, cdpath, cdinstall=False):
    if cdinstall or cdpath:
        guest.installer.cdrom = True
    if location or cdpath:
        guest.installer.location = (location or cdpath)

    if hasattr(guest.installer, "check_location"):
        guest.installer.check_location()

### Option parsing
def parse_args():
    usage = "%prog --name NAME --ram RAM STORAGE INSTALL [options]"
    parser = cli.setupParser(usage)

    parser.add_option("", "--connect", type="string", dest="connect",
                      action="callback", callback=cli.check_before_store,
                      help=_("Connect to hypervisor with URI"),
                      default=None)

    geng = OptionGroup(parser, _("General Options"))
    geng.add_option("-n", "--name", type="string", dest="name",
                    action="callback", callback=cli.check_before_store,
                    help=_("Name of the guest instance"))
    geng.add_option("-r", "--ram", type="int", dest="memory",
                    help=_("Memory to allocate for guest instance in "
                           "megabytes"))
    cli.vcpu_cli_options(geng)
    geng.add_option("", "--description", type="string", dest="description",
                    action="callback", callback=cli.check_before_store,
                    help=_("Human readable description of the VM to store in "
                           "the generated XML."))
    geng.add_option("", "--security", type="string", dest="security",
                    action="callback", callback=cli.check_before_store,
                    help=_("Set domain security driver configuration."))
    parser.add_option_group(geng)

    insg = OptionGroup(parser, _("Installation Method Options"))
    insg.add_option("-c", "--cdrom", type="string", dest="cdrom",
                    action="callback", callback=cli.check_before_store,
                    help=_("CD-ROM installation media"))
    insg.add_option("-l", "--location", type="string", dest="location",
                    action="callback", callback=cli.check_before_store,
                    help=_("Installation source (eg, nfs:host:/path, "
                           "http://host/path, ftp://host/path)"))
    insg.add_option("", "--pxe", action="store_true", dest="pxe",
                    help=_("Boot from the network using the PXE protocol"))
    insg.add_option("", "--import", action="store_true", dest="import_install",
                    help=_("Build guest around an existing disk image"))
    insg.add_option("", "--livecd", action="store_true", dest="livecd",
                    help=_("Treat the CD-ROM media as a Live CD"))
    insg.add_option("-x", "--extra-args", type="string", dest="extra",
                    default="",
                    help=_("Additional arguments to pass to the install kernel "
                           "booted from --location"))
    insg.add_option("", "--initrd-inject", type="string",
                    dest="initrd_injections", action="callback",
                    callback=cli.check_before_append,
                    help=_("Add given file to root of initrd from --location"))
    insg.add_option("", "--os-type", type="string", dest="distro_type",
                    action="callback", callback=cli.check_before_store,
                    help=_("The OS type being installed, e.g. "
                           "'linux', 'unix', 'windows'"))
    insg.add_option("", "--os-variant", type="string", dest="distro_variant",
                    action="callback", callback=cli.check_before_store,
                    help=_("The OS variant being installed guests, "
                           "e.g. 'fedora6', 'rhel5', 'solaris10', 'win2k'"))
    insg.add_option("", "--boot", type="string", dest="bootopts", default="",
                    help=_("Optionally configure post-install boot order, "
                           "menu, permanent kernel boot, etc."))
    parser.add_option_group(insg)

    stog = OptionGroup(parser, _("Storage Configuration"))
    stog.add_option("", "--disk", type="string", dest="diskopts",
                    action="callback", callback=cli.check_before_append,
        help=_("Specify storage with various options. Ex.\n"
               "--disk path=/my/existing/disk\n"
               "--disk path=/my/new/disk,size=5 (in gigabytes)\n"
               "--disk vol=poolname:volname,device=cdrom,bus=scsi,..."))
    stog.add_option("", "--nodisks", action="store_true",
                    help=_("Don't set up any disks for the guest."))

    # Deprecated storage options
    stog.add_option("-f", "--file", type="string", dest="file_path",
                    action="callback", callback=cli.check_before_append,
                    help=optparse.SUPPRESS_HELP)
    stog.add_option("-s", "--file-size", type="float",
                    action="append", dest="disksize",
                    help=optparse.SUPPRESS_HELP)
    stog.add_option("", "--nonsparse", action="store_false",
                    default=True, dest="sparse",
                    help=optparse.SUPPRESS_HELP)
    parser.add_option_group(stog)

    netg = OptionGroup(parser, _("Networking Configuration"))
    netg.add_option("-w", "--network", type="string", dest="network",
                    action="callback", callback=cli.check_before_append,
      help=_("Specify a network interface. Ex:\n"
             "--network bridge=mybr0\n"
             "--network network=my_libvirt_virtual_net\n"
             "--network network=mynet,model=virtio,mac=00:11..."))
    netg.add_option("", "--nonetworks", action="store_true",
                    help=_("Don't create network interfaces for the guest."))

    # Deprecated net options
    netg.add_option("-b", "--bridge", type="string", dest="bridge",
                    action="callback", callback=cli.check_before_append,
                    help=optparse.SUPPRESS_HELP)
    netg.add_option("-m", "--mac", type="string", dest="mac",
                    action="callback", callback=cli.check_before_append,
                    help=optparse.SUPPRESS_HELP)
    parser.add_option_group(netg)

    vncg = cli.graphics_option_group(parser)
    vncg.add_option("", "--noautoconsole", action="store_false",
                    dest="autoconsole", default=True,
                    help=_("Don't automatically try to connect to the guest "
                           "console"))
    parser.add_option_group(vncg)

    devg = OptionGroup(parser, _("Device Options"))
    devg.add_option("", "--serial", type="string", dest="serials",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a serial device to the domain."))
    devg.add_option("", "--parallel", type="string", dest="parallels",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a parallel device to the domain."))
    geng.add_option("", "--channel", type="string", dest="channels",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a guest communication channel."))
    geng.add_option("", "--console", type="string", dest="consoles",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a text console connection between the guest "
                           "and host."))
    devg.add_option("", "--host-device", type="string", dest="hostdevs",
                    action="callback", callback=cli.check_before_append,
                    help=_("Physical host device to attach to the domain."))
    devg.add_option("", "--soundhw", type='string', action="callback",
                    callback=cli.check_before_append, dest="soundhw",
                    help=_("Use sound device emulation"))
    devg.add_option("", "--watchdog", type="string", dest="watchdog",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a watchdog device to the domain."))
    devg.add_option("", "--video", dest="video", type="string",
                    action="callback", callback=cli.check_before_append,
                    help=_("Specify video hardware type."))

    # Deprecated
    devg.add_option("", "--sound", action="store_true", dest="sound",
                    default=False, help=optparse.SUPPRESS_HELP)
    parser.add_option_group(devg)

    virg = OptionGroup(parser, _("Virtualization Platform Options"))
    virg.add_option("-v", "--hvm", action="store_true", dest="fullvirt",
                      help=_("This guest should be a fully virtualized guest"))
    virg.add_option("-p", "--paravirt", action="store_true", dest="paravirt",
                    help=_("This guest should be a paravirtualized guest"))
    virg.add_option("", "--virt-type", type="string", dest="hv_type",
                    default="",
                    help=_("Hypervisor name to use (kvm, qemu, xen, ...)"))
    virg.add_option("", "--accelerate", action="store_true",
                    dest="accelerate", default=False,
                    help=optparse.SUPPRESS_HELP)
    virg.add_option("", "--arch", type="string", dest="arch",
                    action="callback", callback=cli.check_before_store,
                    help=_("The CPU architecture to simulate"))
    virg.add_option("", "--machine", type="string", dest="machine",
                    action="callback", callback=cli.check_before_store,
                    help=_("The machine type to emulate"))
    virg.add_option("", "--noapic", action="store_true", dest="noapic",
                    default=False,
                    help=_("Disables APIC for fully virtualized guest "
                           "(overrides value in os-type/os-variant db)"))
    virg.add_option("", "--noacpi", action="store_true", dest="noacpi",
                    default=False,
                    help=_("Disables ACPI for fully virtualized guest "
                           "(overrides value in os-type/os-variant db)"))
    virg.add_option("-u", "--uuid", type="string", dest="uuid",
                    action="callback", callback=cli.check_before_store,
                    help=_("UUID for the guest."))
    parser.add_option_group(virg)

    misc = OptionGroup(parser, _("Miscellaneous Options"))
    misc.add_option("", "--autostart", action="store_true", default=False,
                    dest="autostart",
                    help=_("Have domain autostart on host boot up."))
    misc.add_option("", "--print-xml", action="store_true", dest="xmlonly",
                    help=_("Print the generated domain XML rather than define "
                           "the guest."))
    misc.add_option("", "--print-step", type="str", dest="xmlstep",
                    help=_("Print XML of a specific install step "
                           "(1, 2, 3, all) rather than define the guest."))
    misc.add_option("", "--noreboot", action="store_true", dest="noreboot",
                    help=_("Disables the automatic rebooting when the "
                           "installation is complete."))
    misc.add_option("", "--wait", type="int", dest="wait",
                    help=_("Time to wait (in minutes)"))
    misc.add_option("", "--dry-run", action="store_true", dest="dry",
                    help=_("Run through install process, but do not "
                           "create devices or define the guest."))
    misc.add_option("", "--force", action="store_true", dest="force",
                    help=_("Forces 'yes' for any applicable prompts, "
                           "terminates for all others"),
                      default=False)
    misc.add_option("-q", "--quiet", action="store_true", dest="quiet",
                    help=_("Suppress non-error output"))
    misc.add_option("", "--prompt", action="store_true", dest="prompt",
                    help=_("Request user input for ambiguous situations or "
                           "required options."), default=False)
    misc.add_option("-d", "--debug", action="store_true", dest="debug",
                    help=_("Print debugging information"))
    parser.add_option_group(misc)

    (options, cliargs) = parser.parse_args()
    return options, cliargs


def vnc_console(dom, uri):
    args = ["/usr/bin/virt-viewer"]
    if uri is not None and uri != "":
        args = args + [ "--connect", uri]
    args = args + [ "--wait", "%s" % dom.ID()]
    child = os.fork()
    if not child:
        try:
            os.execvp(args[0], args)
        except OSError, (err, msg):
            if err == errno.ENOENT:
                logging.warn(_("Unable to connect to graphical console: "
                               "virt-viewer not installed. Please install "
                               "the 'virt-viewer' package."))
            else:
                raise OSError(err, msg)
        os._exit(1)

    return child

def txt_console(dom, uri):
    args = ["/usr/bin/virsh"]
    if uri is not None and uri != "":
        args = args + [ "--connect", uri]
    args = args + [ "console", "%s" % dom.ID()]
    child = os.fork()
    if not child:
        os.execvp(args[0], args)
        os._exit(1)

    return child

def build_guest_instance(conn, options):
    capsguest, capsdomain = get_virt_type(conn, options)

    virt_type = capsguest.os_type
    hv_name = capsdomain.hypervisor_type
    logging.debug("Received virt method '%s'" % virt_type)
    logging.debug("Hypervisor name is '%s'" % hv_name)


    # Build the Installer instance
    if options.livecd:
        instclass = virtinst.LiveCDInstaller
    elif options.pxe:
        if options.nonetworks:
            fail(_("Can't use --pxe with --nonetworks"))

        instclass = virtinst.PXEInstaller
    elif options.cdrom or options.location:
        instclass = virtinst.DistroInstaller
    elif options.import_install or options.bootopts:
        if options.import_install and options.nodisks:
            fail(_("A disk device must be specified with --import."))
        options.import_install = True
        instclass = virtinst.ImportInstaller
    else:
        instclass = virtinst.DistroInstaller

    installer = instclass(type=hv_name, os_type=virt_type, conn=conn)
    installer.arch = capsguest.arch
    installer.initrd_injections = options.initrd_injections
    installer.machine = options.machine

    # Get Guest instance from installer parameters.
    guest = installer.guest_from_installer()


    # now let's get some of the common questions out of the way
    ishvm = bool(virt_type == "hvm")

    # Optional config
    get_networks(options.mac, options.bridge, options.network,
                 options.nonetworks, guest)
    cli.get_graphics(options.vnc, options.vncport, options.vnclisten,
                     options.nographics, options.sdl, options.keymap,
                     options.video, options.graphics, guest)

    cli.get_uuid(options.uuid, guest)
    cli.get_vcpus(options.vcpus, options.check_cpu, guest)
    cli.get_cpuset(options.cpuset, guest.memory, guest)
    cli.parse_cpu(guest, options.cpu)
    get_security(options.security, guest)
    parse_boot_option(guest, options.bootopts)

    get_watchdog(options.watchdog, guest)
    cli.get_sound(options.sound, options.soundhw, guest)
    get_chardevs(VirtualDevice.VIRTUAL_DEV_SERIAL, options.serials, guest)
    get_chardevs(VirtualDevice.VIRTUAL_DEV_PARALLEL, options.parallels, guest)
    get_chardevs(VirtualDevice.VIRTUAL_DEV_CHANNEL, options.channels, guest)
    get_chardevs(VirtualDevice.VIRTUAL_DEV_CONSOLE, options.consoles, guest)

    guest.autostart = options.autostart
    guest.description = options.description

    # Set host device info
    cli.get_hostdevs(options.hostdevs, guest)

    guest.extraargs = options.extra
    guest.features["acpi"] = not options.noacpi
    guest.features["apic"] = not options.noapic

    cli.set_os_variant(guest, options.distro_type, options.distro_variant)

    # Required config. Don't error right away if nothing is specified,
    # aggregate the errors to help first time users get it right
    msg = ""
    if not cli.is_prompt():
        if not options.name:
            msg += "\n" + cli.name_missing
        if not options.memory:
            msg += "\n" + cli.ram_missing
        if not storage_specified(options.file_path, options.diskopts,
                                 options.nodisks):
            msg += "\n" + disk_missing
        if ((not install_specified(options.location, options.cdrom,
                                   options.pxe, options.import_install)) and
            (not cdrom_specified(guest, options.diskopts))):
            msg += "\n" + install_missing
        if msg:
            fail(msg)

    cli.get_name(options.name, guest)
    cli.get_memory(options.memory, guest)
    get_disks(options.file_path, options.diskopts, options.disksize,
              options.sparse, options.nodisks, guest, conn)
    get_install_media(options.location, options.cdrom, options.pxe,
                      options.livecd, options.import_install,
                      guest, ishvm)

    if not options.location and options.extra:
        fail(_("--extra-args only work if specified with --location."))

    if options.pxe and not supports_pxe(guest):
        logging.warn(_("The guest's network configuration does not support "
                       "PXE"))

    return guest

def start_install(guest, continue_inst, options):
    def show_console(dom):
        if guest.graphics_dev:
            if guest.graphics_dev.type == virtinst.VirtualGraphics.TYPE_VNC:
                return vnc_console(dom, guest.conn.getURI())
            else:
                return None # SDL needs no viewer app
        else:
            return txt_console(dom, guest.conn.getURI())

    # There are two main cases we care about:
    #
    # Scripts: these should specify --wait always, maintaining the
    # semantics of virt-install exit implying the domain has finished
    # installing.
    #
    # Interactive: If this is a continue_inst domain, we default to
    # waiting.  Otherwise, we can exit before the domain has finished
    # installing. Passing --wait will give the above semantics.
    #
    wait_on_install = continue_inst
    wait_time = -1
    if options.wait != None:
        wait_on_install = True
        wait_time = options.wait * 60

    # If --wait specified, we don't want the default behavior of waiting
    # for virt-viewer to exit, since then we can't exit the app when time
    # expires
    wait_on_console = not wait_on_install

    # --wait 0 implies --noautoconsole
    options.autoconsole = (wait_time != 0) and options.autoconsole or False

    conscb = options.autoconsole and show_console or None
    meter = options.quiet and progress.BaseMeter() or progress.TextMeter()
    logging.debug("Guest.has_install_phase: %s" %
                  guest.installer.has_install_phase())

    # we've got everything -- try to start the install
    print_stdout(_("\nStarting install..."))

    try:
        start_time = time.time()

        # Do first install phase

        dom = guest.start_install(conscb, meter, wait=wait_on_console)
        dom = check_domain(guest, dom, conscb,
                           wait_on_install, wait_time, start_time)

        # This should be valid even before doing continue install
        if not guest.post_install_check():
            cli.install_fail(guest)

        if continue_inst:
            dom = guest.continue_install(conscb, meter, wait=wait_on_console)
            dom = check_domain(guest, dom, conscb,
                               wait_on_install, wait_time, start_time)

        if options.noreboot or not guest.installer.has_install_phase():
            # XXX: --noreboot doesn't work with say import/livecd. what
            # should it do? never startup the guest?
            print_stdout(
            _("Domain creation completed. You can restart your domain by "
              "running:\n  %s") % cli.virsh_start_cmd(guest))
        else:
            print_stdout(
                _("Guest installation complete... restarting guest."))
            dom.create()
            guest.connect_console(conscb)

    except KeyboardInterrupt, e:
        cli.log_exception()
        guest.terminate_console()
        print_stderr(_("Domain install interrupted."))
    except RuntimeError, e:
        fail(e)
    except SystemExit, e:
        sys.exit(e.code)
    except Exception, e:
        fail(e, do_exit=False)
        cli.install_fail(guest)

def check_domain(guest, dom, conscb, wait_for_install, wait_time, start_time):
    """
    Make sure domain ends up in expected state, and wait if for install
    to complete if requested
    """
    wait_forever = (wait_time < 0)

    # Wait a bit so info is accurate
    def check_domain_state():
        dominfo = dom.info()
        state = dominfo[0]

        if guest.domain_is_crashed():
            fail(_("Domain has crashed."))

        if guest.domain_is_shutdown():
            return dom, state

        return None, state

    do_sleep = bool(conscb)
    try:
        ret, state = check_domain_state()
        if ret:
            return ret
    except Exception, e:
        # Sometimes we see errors from libvirt here due to races
        logging.exception(e)
        do_sleep = True

    if do_sleep:
        # Sleep a bit and try again to be sure the HV has caught up
        time.sleep(2)

    ret, state = check_domain_state()
    if ret:
        return ret

    # Domain seems to be running
    logging.debug("Domain state after install: %s" % state)

    if not wait_for_install or wait_time == 0:
        # User either:
        #   used --noautoconsole
        #   used --wait 0
        #   killed console and guest is still running
        if not guest.installer.has_install_phase():
            return dom

        print_stdout(
            _("Domain installation still in progress. You can reconnect"
              " to \nthe console to complete the installation process."))
        sys.exit(0)

    timestr = (not wait_forever and
               _("%d minutes ") % (int(wait_time) / 60) or "")
    print_stdout(
        _("Domain installation still in progress. Waiting %s"
          "for installation to complete.") % timestr)

    # Wait loop
    while True:
        if guest.domain_is_shutdown():
            print_stdout(_("Domain has shutdown. Continuing."))
            try:
                # Lookup a new domain object incase current
                # one returned bogus data (see comment in
                # domain_is_shutdown
                dom = guest.conn.lookupByName(guest.name)
            except Exception, e:
                raise RuntimeError(_("Could not lookup domain after "
                                     "install: %s" % str(e)))
            break

        time_elapsed = (time.time() - start_time)
        if not wait_forever and time_elapsed >= wait_time:
            print_stdout(
                _("Installation has exceeded specified time limit. "
                        "Exiting application."))
            sys.exit(1)

        time.sleep(2)

    return dom

def xml_to_print(guest, continue_inst, xmlonly, xmlstep, dry):
    start_xml, final_xml = guest.start_install(dry=dry, return_xml=True)
    second_xml = None
    if not start_xml:
        start_xml = final_xml
        final_xml = None

    if continue_inst:
        second_xml, final_xml = guest.continue_install(dry=dry,
                                                       return_xml=True)

    if dry and not (xmlonly or xmlstep):
        print_stdout(_("Dry run completed successfully"))
        return

    # --xml-only
    if xmlonly and not xmlstep:
        if second_xml or final_xml:
            fail(_("--xml-only can only be used with guests that do not have "
                   "an installation phase (--import, --boot, etc.). To see all"
                   "all generated XML, please use --xml-step all."))
        return start_xml

    # --xml-step
    if xmlstep == "1":
        return start_xml
    if xmlstep == "2":
        if not (second_xml or final_xml):
            fail(_("Requested installation does not have XML step 2"))
        return second_xml or final_xml
    if xmlstep == "3":
        if not second_xml:
            fail(_("Requested installation does not have XML step 3"))
        return final_xml

    # "all" case
    xml = start_xml
    if second_xml:
        xml += second_xml
    if final_xml:
        xml += final_xml
    return xml

def main():
    cli.earlyLogging()
    options, cliargs = parse_args()

    # Default setup options
    options.quiet = options.xmlstep or options.xmlonly or options.quiet
    cli.setupLogging("virt-install", options.debug, options.quiet)
    if cliargs:
        fail(_("Unknown argument '%s'") % cliargs[0])

    cli.set_force(options.force)
    cli.set_prompt(options.prompt)
    conn = cli.getConnection(options.connect)

    if options.xmlstep not in [None, "1", "2", "3", "all"]:
        fail(_("--print-step must be 1, 2, 3, or all"))

    guest = build_guest_instance(conn, options)
    continue_inst = guest.get_continue_inst()

    if options.xmlstep or options.xmlonly or options.dry:
        xml = xml_to_print(guest, continue_inst,
                           options.xmlonly, options.xmlstep, options.dry)
        if xml:
            print_stdout(xml, do_force=True)
    else:
        start_install(guest, continue_inst, options)

    return 0

if __name__ == "__main__":
    try:
        sys.exit(main())
    except SystemExit, sys_e:
        sys.exit(sys_e.code)
    except KeyboardInterrupt:
        cli.log_exception()
        print_stderr(_("Installation aborted at user request"))
    except Exception, main_e:
        fail(main_e)