Beispiel #1
0
def main_menu(session):
    """Show the main menu of the program"""
    d = session['dialog']

    update_background_title(session)

    choices = [("Customize", "Customize image & cloud deployment options"),
               ("Register", "Register image to a cloud"),
               ("Extract", "Dump image to local file system"),
               ("Log", "Show current execution log"),
               ("Reset", "Reset everything and start over again"),
               ("Help", "Get help for using snf-image-creator")]

    default_item = "Customize"

    actions = {
        "Customize": customization_menu,
        "Register": kamaki_menu,
        "Extract": extract_image,
        "Log": show_log
    }
    title = "Image Creator for Synnefo (snf-image-creator v%s)" % version
    while 1:
        (code, choice) = d.menu(
            text="Choose one of the following or press <Exit> to exit.",
            width=WIDTH,
            choices=choices,
            cancel="Exit",
            height=13,
            default_item=default_item,
            menu_height=len(choices),
            title=title)

        if code in (d.CANCEL, d.ESC):
            if confirm_exit(d):
                break
        elif choice == "Reset":
            if confirm_reset(d):
                d.infobox("Resetting snf-image-creator. Please wait ...",
                          width=SMALL_WIDTH)
                raise Reset
        elif choice == "Help":
            d.msgbox(
                "For help, check the online documentation:\n\nhttp://www"
                ".synnefo.org/docs/snf-image-creator/latest/",
                width=WIDTH,
                title="Help")
        elif choice in actions:
            actions[choice](session)

        if len(choice):
            default_item = choice
Beispiel #2
0
def main_menu(session):
    """Show the main menu of the program"""
    d = session['dialog']

    update_background_title(session)

    choices = [("Customize", "Customize image & cloud deployment options"),
               ("Register", "Register image to a cloud"),
               ("Extract", "Dump image to local file system"),
               ("Log", "Show current execution log"),
               ("Reset", "Reset everything and start over again"),
               ("Help", "Get help for using snf-image-creator")]

    default_item = "Customize"

    actions = {"Customize": customization_menu, "Register": kamaki_menu,
               "Extract": extract_image, "Log": show_log}
    title = "Image Creator for Synnefo (snf-image-creator v%s)" % version
    while 1:
        (code, choice) = d.menu(
            text="Choose one of the following or press <Exit> to exit.",
            width=WIDTH, choices=choices, cancel="Exit", height=13,
            default_item=default_item, menu_height=len(choices),
            title=title)

        if code in (d.CANCEL, d.ESC):
            if confirm_exit(d):
                break
        elif choice == "Reset":
            if confirm_reset(d):
                d.infobox("Resetting snf-image-creator. Please wait ...",
                          width=SMALL_WIDTH)
                raise Reset
        elif choice == "Help":
            d.msgbox("For help, check the online documentation:\n\nhttp://www"
                     ".synnefo.org/docs/snf-image-creator/latest/",
                     width=WIDTH, title="Help")
        elif choice in actions:
            actions[choice](session)

        if len(choice):
            default_item = choice
Beispiel #3
0
def create_image(d, media, out, tmp, snapshot):
    """Create an image out of `media'"""
    d.setBackgroundTitle('snf-image-creator')

    gauge = GaugeOutput(d, "Initialization", "Initializing...")
    out.append(gauge)
    disk = Disk(media, out, tmp)

    # pylint: disable=unused-argument
    def signal_handler(signum, frame):
        gauge.cleanup()
        disk.cleanup()

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    try:

        device = disk.file if not snapshot else disk.snapshot()

        image = disk.get_image(device)

        gauge.cleanup()
        out.remove(gauge)

        # Make sure the signal handler does not call gauge.cleanup again
        def dummy(self):  # pylint: disable=unused-argument
            pass
        gauge.cleanup = type(GaugeOutput.cleanup)(dummy, gauge, GaugeOutput)

        session = {"dialog": d,
                   "disk": disk,
                   "image": image}

        if image.is_unsupported():

            session['excluded_tasks'] = [-1]
            session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]

            msg = "The system on the input media is not supported." \
                "\n\nReason: %s\n\n" \
                "We highly recommend not to create an image out of this, " \
                "since the image won't be cleaned up and you will not be " \
                "able to configure it during the deployment. Press <YES> if " \
                "you still want to continue with the image creation process." \
                % image._unsupported

            if d.yesno(msg, width=WIDTH, defaultno=1, height=12) == d.OK:
                main_menu(session)

            d.infobox("Thank you for using snf-image-creator. Bye", width=53)
            return 0

        msg = "snf-image-creator detected a %s system on the input media. " \
              "Would you like to run a wizard to assist you through the " \
              "image creation process?\n\nChoose <Wizard> to run the wizard," \
              " <Expert> to run snf-image-creator in expert mode or press " \
              "ESC to quit the program." \
              % (image.ostype.capitalize() if image.ostype == image.distro or
                 image.distro == "unknown" else "%s (%s)" %
                 (image.ostype.capitalize(), image.distro.capitalize()))

        update_background_title(session)

        while True:
            code = d.yesno(msg, width=WIDTH, height=12, yes_label="Wizard",
                           no_label="Expert")
            if code == d.OK:
                if start_wizard(session):
                    break
            elif code == d.CANCEL:
                main_menu(session)
                break

            if confirm_exit(d):
                break

        d.infobox("Thank you for using snf-image-creator. Bye", width=53)
    finally:
        disk.cleanup()

    return 0
Beispiel #4
0
def dialog_main(media, **kwargs):
    """Main function for the dialog-based version of the program"""

    tmpdir = kwargs['tmpdir'] if 'tmpdir' in kwargs else None
    snapshot = kwargs['snapshot'] if 'snapshot' in kwargs else True
    logfile = kwargs['logfile'] if 'logfile' in kwargs else None
    syslog = kwargs['syslog'] if 'syslog' in kwargs else False

    # In openSUSE dialog is buggy under xterm
    if os.environ['TERM'] == 'xterm':
        os.environ['TERM'] = 'linux'

    d = dialog.Dialog(dialog="dialog")

    # Add extra button in dialog library if missing
    if 'extra_button' not in dialog._common_args_syntax:
        dialog._common_args_syntax["extra_button"] = \
            lambda enable: dialog._simple_option("--extra-button", enable)
    if 'extra_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["extra_label"] = \
            lambda string: ("--extra-label", string)

    # Allow yes-no label overwriting if missing
    if 'yes_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["yes_label"] = \
            lambda string: ("--yes-label", string)
    if 'no_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["no_label"] = \
            lambda string: ("--no-label", string)

    # Add exit label overwriting if missing
    if 'exit_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["exit_label"] = \
            lambda string: ("--exit-label", string)

    # Monkey-patch pythondialog to include support for form dialog boxes
    if not hasattr(d, 'form'):
        d.form = types.MethodType(_dialog_form, d)

    # Add sort dialog constants if missing
    if not hasattr(d, 'OK'):
        d.OK = d.DIALOG_OK

    if not hasattr(d, 'CANCEL'):
        d.CANCEL = d.DIALOG_CANCEL

    if not hasattr(d, 'ESC'):
        d.ESC = d.DIALOG_ESC

    if not hasattr(d, 'EXTRA'):
        d.EXTRA = d.DIALOG_EXTRA

    if not hasattr(d, 'HELP'):
        d.HELP = d.DIALOG_HELP

    d.setBackgroundTitle('snf-image-creator')

    # Pick input media
    while True:
        media = select_file(d, init=media, ftype="br", bundle_host=True,
                            title="Please select an input media.")
        if media is None:
            if confirm_exit(
                    d, "You canceled the media selection dialog box."):
                return 0
            continue
        break

    tmplog = None if logfile else tempfile.NamedTemporaryFile(prefix='fatal-',
                                                              delete=False)

    logs = []
    try:
        stream = logfile if logfile else tmplog
        logs.append(SimpleOutput(colored=False, stderr=stream, stdout=stream,
                                 timestamp=True))
        if syslog:
            logs.append(SyslogOutput())

        while 1:
            try:
                out = CompositeOutput(logs)
                out.info("Starting %s v%s ..." % (PROGNAME, version))
                ret = create_image(d, media, out, tmpdir, snapshot)
                break
            except Reset:
                for log in logs:
                    log.info("Resetting everything ...")
    except FatalError as error:
        for log in logs:
            log.error(str(error))
        msg = 'A fatal error occured. See %s for a full log.' % log.stderr.name
        d.infobox(msg, width=WIDTH, title="Fatal Error")
        return 1
    else:
        if tmplog:
            os.unlink(tmplog.name)
    finally:
        if tmplog:
            tmplog.close()

    return ret
def create_image(d, media, out, tmp, snapshot):
    """Create an image out of `media'"""
    d.setBackgroundTitle('snf-image-creator')

    gauge = GaugeOutput(d, "Initialization", "Initializing...")
    out.append(gauge)
    disk = Disk(media, out, tmp)

    # pylint: disable=unused-argument
    def signal_handler(signum, frame):
        gauge.cleanup()
        disk.cleanup()

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    try:

        device = disk.file if not snapshot else disk.snapshot()

        image = disk.get_image(device)

        gauge.cleanup()
        out.remove(gauge)

        # Make sure the signal handler does not call gauge.cleanup again
        def dummy(self):  # pylint: disable=unused-argument
            pass

        gauge.cleanup = type(GaugeOutput.cleanup)(dummy, gauge, GaugeOutput)

        session = {"dialog": d, "disk": disk, "image": image}

        if image.is_unsupported():

            session['excluded_tasks'] = [-1]
            session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]

            msg = "The system on the input media is not supported." \
                "\n\nReason: %s\n\n" \
                "We highly recommend not to create an image out of this, " \
                "since the image won't be cleaned up and you will not be " \
                "able to configure it during the deployment. Press <YES> if " \
                "you still want to continue with the image creation process." \
                % image._unsupported

            if d.yesno(msg, width=WIDTH, defaultno=1, height=12) == d.OK:
                main_menu(session)

            d.infobox("Thank you for using snf-image-creator. Bye", width=53)
            return 0

        msg = "snf-image-creator detected a %s system on the input media. " \
              "Would you like to run a wizard to assist you through the " \
              "image creation process?\n\nChoose <Wizard> to run the wizard," \
              " <Expert> to run snf-image-creator in expert mode or press " \
              "ESC to quit the program." \
              % (image.ostype.capitalize() if image.ostype == image.distro or
                 image.distro == "unknown" else "%s (%s)" %
                 (image.ostype.capitalize(), image.distro.capitalize()))

        update_background_title(session)

        while True:
            code = d.yesno(msg,
                           width=WIDTH,
                           height=12,
                           yes_label="Wizard",
                           no_label="Expert")
            if code == d.OK:
                if start_wizard(session):
                    break
            elif code == d.CANCEL:
                main_menu(session)
                break

            if confirm_exit(d):
                break

        d.infobox("Thank you for using snf-image-creator. Bye", width=53)
    finally:
        disk.cleanup()

    return 0
def dialog_main(media, **kwargs):
    """Main function for the dialog-based version of the program"""

    tmpdir = kwargs['tmpdir'] if 'tmpdir' in kwargs else None
    snapshot = kwargs['snapshot'] if 'snapshot' in kwargs else True
    logfile = kwargs['logfile'] if 'logfile' in kwargs else None
    syslog = kwargs['syslog'] if 'syslog' in kwargs else False

    # In openSUSE dialog is buggy under xterm
    if os.environ['TERM'] == 'xterm':
        os.environ['TERM'] = 'linux'

    d = dialog.Dialog(dialog="dialog")

    # Add extra button in dialog library if missing
    if 'extra_button' not in dialog._common_args_syntax:
        dialog._common_args_syntax["extra_button"] = \
            lambda enable: dialog._simple_option("--extra-button", enable)
    if 'extra_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["extra_label"] = \
            lambda string: ("--extra-label", string)

    # Allow yes-no label overwriting if missing
    if 'yes_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["yes_label"] = \
            lambda string: ("--yes-label", string)
    if 'no_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["no_label"] = \
            lambda string: ("--no-label", string)

    # Add exit label overwriting if missing
    if 'exit_label' not in dialog._common_args_syntax:
        dialog._common_args_syntax["exit_label"] = \
            lambda string: ("--exit-label", string)

    # Monkey-patch pythondialog to include support for form dialog boxes
    if not hasattr(d, 'form'):
        d.form = types.MethodType(_dialog_form, d)

    # Add sort dialog constants if missing
    if not hasattr(d, 'OK'):
        d.OK = d.DIALOG_OK

    if not hasattr(d, 'CANCEL'):
        d.CANCEL = d.DIALOG_CANCEL

    if not hasattr(d, 'ESC'):
        d.ESC = d.DIALOG_ESC

    if not hasattr(d, 'EXTRA'):
        d.EXTRA = d.DIALOG_EXTRA

    if not hasattr(d, 'HELP'):
        d.HELP = d.DIALOG_HELP

    d.setBackgroundTitle('snf-image-creator')

    # Pick input media
    while True:
        media = select_file(d,
                            init=media,
                            ftype="br",
                            bundle_host=True,
                            title="Please select an input media.")
        if media is None:
            if confirm_exit(d, "You canceled the media selection dialog box."):
                return 0
            continue
        break

    tmplog = None if logfile else tempfile.NamedTemporaryFile(prefix='fatal-',
                                                              delete=False)

    logs = []
    try:
        stream = logfile if logfile else tmplog
        logs.append(
            SimpleOutput(colored=False,
                         stderr=stream,
                         stdout=stream,
                         timestamp=True))
        if syslog:
            logs.append(SyslogOutput())

        while 1:
            try:
                out = CompositeOutput(logs)
                out.info("Starting %s v%s ..." % (PROGNAME, version))
                ret = create_image(d, media, out, tmpdir, snapshot)
                break
            except Reset:
                for log in logs:
                    log.info("Resetting everything ...")
    except FatalError as error:
        for log in logs:
            log.error(str(error))
        msg = 'A fatal error occured. See %s for a full log.' % log.stderr.name
        d.infobox(msg, width=WIDTH, title="Fatal Error")
        return 1
    else:
        if tmplog:
            os.unlink(tmplog.name)
    finally:
        if tmplog:
            tmplog.close()

    return ret