summaryrefslogtreecommitdiff
path: root/virt-install
blob: ca78d1ef1edbb799e5b4f1ddcc9edffc1e5fb7b4 (plain)
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
#!/usr/bin/python -tt
#
# Copyright 2005-2013 Red Hat, Inc.
#
# 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 argparse
import logging
import os
import re
import sys
import time

import libvirt
import urlgrabber.progress as progress

import virtinst
import virtinst.cli as cli
from virtinst.cli import fail, print_stdout, print_stderr


##############################
# Validation utility helpers #
##############################

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, disk=None):
    disks = guest.get_devices("disk")

    for disk in disks:
        if disk.device == virtinst.VirtualDisk.DEVICE_CDROM:
            return True

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

    return False


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


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:
            netobj = nic.conn.networkLookupByName(nic.source)
            xmlobj = virtinst.Network(nic.conn, parsexml=netobj.XMLDesc(0))
            if xmlobj.can_pxe():
                return True
        except:
            logging.debug("Error checking if PXE supported", exc_info=True)
            return True

    return False


def check_cdrom_option_error(options):
    if options.cdrom_short and options.cdrom:
        fail("Cannot specify both -c and --cdrom")

    if options.cdrom_short:
        if "://" in options.cdrom_short:
            fail("-c specified with what looks like a URI. Did you mean "
                 "to use --connect? If not, use --cdrom instead")
        options.cdrom = options.cdrom_short

    if not options.cdrom:
        return

    # Catch a strangely common error of users passing -vcpus=2 instead of
    # --vcpus=2. The single dash happens to map to enough shortened options
    # that things can fail weirdly if --paravirt is also specified.
    for vcpu in [o for o in sys.argv if o.startswith("-vcpu")]:
        if options.cdrom == vcpu[3:]:
            fail("You specified -vcpus, you want --vcpus")


##############################
# Device validation wrappers #
##############################

def convert_old_sound(options):
    if options.soundhw:
        return
    if not options.old_sound_bool:
        return
    options.soundhw = "default"


def convert_old_init(options):
    if not options.init:
        return
    if not options.boot:
        options.boot = ""
    options.boot += ",init=%s" % options.init
    logging.debug("Converted old --init to --boot %s", options.boot)


def get_disks(guest, disks, nodisks, need_storage):
    if nodisks:
        return

    if not disks and need_storage and cli.is_prompt():
        disks = [None]

    for disk in disks:
        try:
            if disk is None:
                dev = None
                sparse = True
                size = None
                path = None
            else:
                # We skip validation here, since we may have converted
                # --file-size to --disk size=8 which doesn't validate on
                # its own.
                dev = cli.parse_disk(guest, disk,
                                     virtinst.VirtualDisk(guest.conn),
                                     validate=False)
                size = dev.cli_size
                path = dev.path
                sparse = dev.get_sparse()

            d = cli.disk_prompt(guest.conn, path, size, sparse, origdev=dev)
            d.validate()
        except ValueError, e:
            fail(_("Error with storage parameters: %s" % str(e)))

        guest.add_device(d)


def convert_old_disks(options):
    if options.disk or options.nodisks:
        return

    paths = virtinst.util.listify(options.file_paths)
    sizes = virtinst.util.listify(options.disksize)

    def padlist(l, padsize):
        l = virtinst.util.listify(l)
        l.extend((padsize - len(l)) * [None])
        return l

    disklist = padlist(paths, max(0, len(sizes)))
    sizelist = padlist(sizes, len(disklist))

    opts = []
    for idx in range(len(disklist)):
        optstr = ""
        if disklist[idx]:
            optstr += "path=%s" % disklist[idx]
        if sizelist[idx]:
            if optstr:
                optstr += ","
            optstr += "size=%s" % sizelist[idx]
        if options.sparse is False:
            if optstr:
                optstr += ","
            optstr += "sparse=no"
        logging.debug("Converted to new style: --disk %s", optstr)
        opts.append(optstr)

    options.disk = opts
    options.file_paths = []
    options.disksize = None
    options.sparse = True


########################
# Virt type validation #
########################

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.cpu.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_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_no(prompt_txt, "")

    return (req_virt_type, req_accel)


def get_guest(conn, options):
    # Set up all virt/hypervisor parameters
    if sum([bool(f) for f in [options.fullvirt,
                              options.paravirt,
                              options.container]]) > 1:
        fail(_("Can't do more than one of --hvm, --paravirt, or --container"))

    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"
    elif options.container:
        req_virt_type = "exe"
    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(conn.caps, 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) = conn.caps.guest_lookup(
                        os_type=req_virt_type,
                        arch=arch,
                        typ=req_hv_type,
                        accelerated=req_accel,
                        machine=options.machine)
        guest = conn.caps.build_virtinst_guest(conn, capsguest, capsdomain)
        guest.os.machine = options.machine
    except Exception, e:
        fail(e)

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

    return guest


##################################
# Install media setup/validation #
##################################

def get_install_media(guest, location, cdpath, need_install):
    manual_cdrom = cdrom_specified(guest)
    cdinstall = bool(not location and (cdpath or cdrom_specified(guest)))

    if not (location or cdpath or manual_cdrom or need_install):
        return

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


def media_prompt(guest):
    if guest.os.is_hvm():
        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 guest.os.is_hvm() 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)
    guest.installer.check_location(guest)


#############################
# General option validation #
#############################

def validate_required_options(options, guest):
    # Required config. Don't error right away if nothing is specified,
    # aggregate the errors to help first time users get it right
    msg = ""
    need_storage = False
    need_install = False

    if not options.name:
        msg += "\n" + cli.name_missing

    if not options.memory:
        msg += "\n" + cli.memory_missing

    if (not guest.os.is_container() and
        not storage_specified(options.disk,
                              options.nodisks,
                              options.filesystem)):
        msg += "\n" + disk_missing
        need_storage = True

    if (not guest.os.is_container() and
        (not install_specified(options.location, options.cdrom,
                               options.pxe, options.import_install)) and
        (not cdrom_specified(guest, options.disk))):
        msg += "\n" + install_missing
        need_install = True

    if msg and not cli.is_prompt():
        fail(msg)

    return need_storage, need_install


def check_option_collisions(options, guest):
    # Disk collisions
    if options.nodisks and (options.file_paths or
                            options.disk or
                            options.disksize):
        fail(_("Cannot specify storage and use --nodisks"))

    if ((options.file_paths or options.disksize or not options.sparse) and
        options.disk):
        fail(_("Cannot mix --file, --nonsparse, or --file-size with --disk "
               "options. Use --disk PATH[,size=SIZE][,sparse=yes|no]"))

    # Network collisions
    if options.nonetworks:
        if options.mac:
            fail(_("Cannot use --mac with --nonetworks"))
        if options.bridge:
            fail(_("Cannot use --bridge with --nonetworks"))
        if options.network:
            fail(_("Cannot use --network with --nonetworks"))
        return

    # Install collisions
    if sum([bool(l) for l in [options.pxe, options.location,
                      options.cdrom, options.import_install]]) > 1:
        fail(_("Only one install method can be used (%(methods)s)") %
             {"methods" : install_methods})

    if (guest.os.is_container() and
        install_specified(options.location, options.cdrom,
                          options.pxe, options.import_install)):
        fail(_("Install methods (%s) cannot be specified for "
               "container guests") % install_methods)

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

    if (options.location and
        guest.conn.is_remote() and not
        guest.conn.support_remote_url_install()):
        fail(_("Libvirt version does not support remote --location installs"))

    if not options.location and options.extra_args:
        fail(_("--extra-args only work if specified with --location."))
    if not options.location and options.initrd_inject:
        fail(_("--initrd-inject only works if specified with --location."))


##########################
# Guest building helpers #
##########################

def build_installer(options, conn, virt_type):
    # 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.boot:
        if options.import_install and options.nodisks:
            fail(_("A disk device must be specified with --import."))
        options.import_install = True
        instclass = virtinst.ImportInstaller
    elif virt_type == "exe":
        instclass = virtinst.ContainerInstaller
    else:
        instclass = virtinst.DistroInstaller

    # Only set installer params here that impact the hw config, not
    # anything to do with install media
    installer = instclass(conn)

    return installer


def build_guest_instance(conn, options, parsermap):
    guest = get_guest(conn, options)

    logging.debug("Received virt method '%s'", guest.type)
    logging.debug("Hypervisor name is '%s'", guest.os.os_type)

    guest.installer = build_installer(options, conn, guest.os.os_type)

    cli.convert_old_memory(options)
    convert_old_sound(options)
    cli.convert_old_networks(guest, options, not options.nonetworks and 1 or 0)
    cli.convert_old_graphics(guest, options)
    convert_old_disks(options)
    cli.convert_old_features(options)
    cli.convert_old_cpuset(options)
    convert_old_init(options)

    # non-xml install options
    guest.installer.extraargs = options.extra_args
    guest.installer.initrd_injections = options.initrd_inject
    cli.set_os_variant(guest, options.distro_type, options.distro_variant)
    guest.autostart = options.autostart

    cli.get_name(guest, options.name)

    if options.uuid:
        guest.uuid = options.uuid
    # This might be difficult to convert into options.metadata
    if options.description:
        guest.description = options.description

    # We don't want to auto-parse --disk, but we wanted it for earlier
    # parameter introspection
    del(parsermap["disk"])
    cli.parse_option_strings(parsermap, options, guest, None)

    guest.add_default_input_device()
    guest.add_default_console_device()
    guest.add_default_video_device()
    guest.add_default_usb_controller()
    guest.add_default_channels()

    if cli.is_prompt():
        cli.get_memory(guest, guest.memory and (guest.memory / 1024) or None)

    # Do this after setting up all optional parameters, so we report error
    # about those first.
    need_storage, need_install = validate_required_options(options, guest)

    get_disks(guest, options.disk, options.nodisks, need_storage)
    get_install_media(guest, options.location, options.cdrom, need_install)

    # Various little validations about option collisions. Need to do
    # this after setting guest.installer at least
    check_option_collisions(options, guest)

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

    return guest


###########################
# Install process helpers #
###########################

def _run_console(args):
    logging.debug("Running: %s", " ".join(args))
    child = os.fork()
    if child:
        return child

    os.execvp(args[0], args)
    os._exit(1)  # pylint: disable=W0212


def vnc_console(dom, uri):
    args = ["/usr/bin/virt-viewer",
            "--connect", uri,
            "--wait", str(dom.ID())]

    if not os.path.exists(args[0]):
        logging.warn(_("Unable to connect to graphical console: "
                       "virt-viewer not installed. Please install "
                       "the 'virt-viewer' package."))
        return None

    return _run_console(args)


def txt_console(dom, uri):
    args = ["/usr/bin/virsh",
            "--connect", uri,
            "console", str(dom.ID())]

    return _run_console(args)


def domain_is_crashed(domain):
    """
    Return True if the created domain object is in a crashed state
    """
    if not domain:
        return False

    dominfo = domain.info()
    state = dominfo[0]

    return state == libvirt.VIR_DOMAIN_CRASHED


def domain_is_shutdown(domain):
    """
    Return True if the created domain object is shutdown
    """
    if not domain:
        return False

    dominfo = domain.info()

    state    = dominfo[0]
    cpu_time = dominfo[4]

    if state == libvirt.VIR_DOMAIN_SHUTOFF:
        return True

    # If 'wait' was specified, the dom object we have was looked up
    # before initially shutting down, which seems to bogus up the
    # info data (all 0's). So, if it is bogus, assume the domain is
    # shutdown. We will catch the error later.
    return state == libvirt.VIR_DOMAIN_NOSTATE and cpu_time == 0


def connect_console(domain, consolecb, wait):
    """
    Launched the passed console callback for the already defined
    domain. If domain isn't running, return an error.
    """
    child = None
    if consolecb:
        child = consolecb(domain)

    if not child or not wait:
        return

    # If we connected the console, wait for it to finish
    try:
        os.waitpid(child, 0)
    except OSError, e:
        logging.debug("waitpid: %s: %s", e.errno, e.message)


def start_install(guest, continue_inst, options):
    def show_console(dom):
        xmlobj = virtinst.Guest(guest.conn, parsexml=dom.XMLDesc(0))
        gdev = xmlobj.get_devices("graphics")
        if not gdev:
            logging.debug("Connecting to text console")
            return txt_console(dom, guest.conn.getURI())

        gtype = gdev[0].type
        if gtype in [virtinst.VirtualGraphics.TYPE_VNC,
                     virtinst.VirtualGraphics.TYPE_SPICE]:
            logging.debug("Launching virt-viewer for graphics type '%s'",
                          gtype)
            return vnc_console(dom, guest.conn.getURI())
        else:
            logging.debug("No viewer to launch for graphics type '%s'",
                          gtype)
            return None

    # 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 is not 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(fo=sys.stdout))
    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(meter=meter, noboot=options.noreboot)
        connect_console(dom, conscb, wait_on_console)
        dom = check_domain(guest, dom, conscb,
                           wait_on_install, wait_time, start_time)

        if continue_inst:
            dom = guest.continue_install(meter=meter)
            connect_console(dom, conscb, 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():
            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()
            connect_console(dom, conscb, wait=True)

    except KeyboardInterrupt:
        logging.debug("", exc_info=True)
        print_stderr(_("Domain install interrupted."))
        raise
    except RuntimeError, e:
        fail(e)
    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 domain_is_crashed(guest.domain):
            fail(_("Domain has crashed."))

        if domain_is_shutdown(guest.domain):
            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 "
          "%(time_string)s for installation to complete.") %
        {"time_string": timestr})

    # Wait loop
    while True:
        if domain_is_shutdown(guest.domain):
            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


########################
# XML printing helpers #
########################

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

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

    # --print-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


#######################
# CLI option handling #
#######################

def parse_args():
    parser = cli.setupParser(
        "%(prog)s --name NAME --ram RAM STORAGE INSTALL [options]",
        _("Create a new virtual machine from specified install media."),
        introspection_epilog=True)
    cli.add_connect_option(parser)

    geng = parser.add_argument_group(_("General Options"))
    geng.add_argument("-n", "--name",
                    help=_("Name of the guest instance"))
    cli.add_memory_option(geng, backcompat=True)
    cli.vcpu_cli_options(geng)
    cli.add_metadata_option(geng)
    geng.add_argument("-u", "--uuid", help=argparse.SUPPRESS)
    geng.add_argument("--description", help=argparse.SUPPRESS)
    cli.add_guest_xml_options(geng)

    insg = parser.add_argument_group(_("Installation Method Options"))
    insg.add_argument("-c", dest="cdrom_short", help=argparse.SUPPRESS)
    insg.add_argument("--cdrom", help=_("CD-ROM installation media"))
    insg.add_argument("-l", "--location",
                    help=_("Installation source (eg, nfs:host:/path, "
                           "http://host/path, ftp://host/path)"))
    insg.add_argument("--pxe", action="store_true",
                    help=_("Boot from the network using the PXE protocol"))
    insg.add_argument("--import", action="store_true", dest="import_install",
                    help=_("Build guest around an existing disk image"))
    insg.add_argument("--livecd", action="store_true",
                    help=_("Treat the CD-ROM media as a Live CD"))
    insg.add_argument("-x", "--extra-args",
                    help=_("Additional arguments to pass to the install kernel "
                           "booted from --location"))
    insg.add_argument("--initrd-inject", action="append",
                    help=_("Add given file to root of initrd from --location"))
    cli.add_distro_options(insg)
    cli.add_boot_option(insg)
    insg.add_argument("--init", help=argparse.SUPPRESS)

    stog = parser.add_argument_group(_("Storage Configuration"))
    cli.add_disk_option(stog)
    stog.add_argument("--nodisks", action="store_true",
                    help=_("Don't set up any disks for the guest."))
    cli.add_fs_option(stog)

    # Deprecated storage options
    stog.add_argument("-f", "--file", dest="file_paths", action="append",
                    help=argparse.SUPPRESS)
    stog.add_argument("-s", "--file-size", type=float,
                    action="append", dest="disksize",
                    help=argparse.SUPPRESS)
    stog.add_argument("--nonsparse", action="store_false",
                    default=True, dest="sparse",
                    help=argparse.SUPPRESS)

    netg = cli.network_option_group(parser)

    netg.add_argument("--nonetworks", action="store_true",
                    help=_("Don't create network interfaces for the guest."))

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

    devg = parser.add_argument_group(_("Device Options"))
    cli.add_device_options(devg)

    # Deprecated
    devg.add_argument("--sound", action="store_true", dest="old_sound_bool",
                    default=False, help=argparse.SUPPRESS)

    virg = parser.add_argument_group(_("Virtualization Platform Options"))
    virg.add_argument("-v", "--hvm", action="store_true", dest="fullvirt",
                      help=_("This guest should be a fully virtualized guest"))
    virg.add_argument("-p", "--paravirt", action="store_true",
                    help=_("This guest should be a paravirtualized guest"))
    virg.add_argument("--container", action="store_true", default=False,
                    help=_("This guest should be a container guest"))
    virg.add_argument("--virt-type", dest="hv_type",
                    default="",
                    help=_("Hypervisor name to use (kvm, qemu, xen, ...)"))
    virg.add_argument("--accelerate", action="store_true", default=False,
                     help=argparse.SUPPRESS)
    virg.add_argument("--arch",
                    help=_("The CPU architecture to simulate"))
    virg.add_argument("--machine",
                    help=_("The machine type to emulate"))
    cli.add_old_feature_options(virg)

    misc = parser.add_argument_group(_("Miscellaneous Options"))
    misc.add_argument("--autostart", action="store_true", dest="autostart",
                    default=False,
                    help=_("Have domain autostart on host boot up."))
    misc.add_argument("--wait", type=int, dest="wait",
                    help=_("Minutes to wait for install to complete."))

    cli.add_misc_options(misc, prompt=True, printxml=True, printstep=True,
                         noreboot=True, dryrun=True)

    return parser.parse_args()


###################
# main() handling #
###################

def main(conn=None):
    cli.earlyLogging()
    options = parse_args()

    # Default setup options
    options.quiet = options.xmlstep or options.xmlonly or options.quiet

    cli.setupLogging("virt-install", options.debug, options.quiet)

    check_cdrom_option_error(options)

    if options.distro_variant == "list":
        logging.debug("OS list requested")
        for t in virtinst.osdict.list_os(list_types=True):
            for v in virtinst.osdict.list_os(typename=t.name):
                print "%-20s : %s" % (v.name, v.label)
        return 0

    cli.set_force(options.force)
    cli.set_prompt(options.prompt)

    parsermap = cli.build_parser_map(options)
    if cli.check_option_introspection(options, parsermap):
        return 0

    if conn is None:
        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, parsermap)
    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:
        logging.debug("", exc_info=True)
        print_stderr(_("Installation aborted at user request"))
    except Exception, main_e:
        fail(main_e)