Allow image creation from unsupported media
[snf-image-creator] / image_creator / dialog_main.py
index 21fa873..0586327 100644 (file)
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
-
+# -*- coding: utf-8 -*-
+#
 # Copyright 2012 GRNET S.A. All rights reserved.
 #
 # Redistribution and use in source and binary forms, with or
 # interpreted as representing official policies, either expressed
 # or implied, of GRNET S.A.
 
+"""This module is the entrance point for the dialog-based version of the
+snf-image-creator program. The main function will create a dialog where the
+user is asked if he wants to use the program in expert or wizard mode.
+"""
+
 import dialog
 import sys
 import os
@@ -40,6 +46,7 @@ import stat
 import textwrap
 import signal
 import optparse
+import types
 
 from image_creator import __version__ as version
 from image_creator.util import FatalError
@@ -48,15 +55,14 @@ from image_creator.output.cli import SimpleOutput
 from image_creator.output.dialog import GaugeOutput
 from image_creator.output.composite import CompositeOutput
 from image_creator.disk import Disk
-from image_creator.os_type import os_cls
-from image_creator.dialog_wizard import wizard
+from image_creator.dialog_wizard import start_wizard
 from image_creator.dialog_menu import main_menu
 from image_creator.dialog_util import SMALL_WIDTH, WIDTH, confirm_exit, \
     Reset, update_background_title
 
 
-def image_creator(d, media, out, tmp):
-
+def create_image(d, media, out, tmp):
+    """Create an image out of `media'"""
     d.setBackgroundTitle('snf-image-creator')
 
     gauge = GaugeOutput(d, "Initialization", "Initializing...")
@@ -71,19 +77,14 @@ def image_creator(d, media, out, tmp):
     signal.signal(signal.SIGTERM, signal_handler)
     try:
         snapshot = disk.snapshot()
-        dev = disk.get_device(snapshot)
+        image = disk.get_image(snapshot)
 
+        out.output("Collecting image metadata ...")
         metadata = {}
-        for (key, value) in dev.meta.items():
+        for (key, value) in image.meta.items():
             metadata[str(key)] = str(value)
 
-        dev.mount(readonly=True)
-        out.output("Collecting image metadata...")
-        cls = os_cls(dev.distro, dev.ostype)
-        image_os = cls(dev.root, dev.g, out)
-        dev.umount()
-
-        for (key, value) in image_os.meta.items():
+        for (key, value) in image.os.meta.items():
             metadata[str(key)] = str(value)
 
         out.success("done")
@@ -97,18 +98,36 @@ def image_creator(d, media, out, tmp):
 
         session = {"dialog": d,
                    "disk": disk,
-                   "snapshot": snapshot,
-                   "device": dev,
-                   "image_os": image_os,
+                   "image": image,
                    "metadata": metadata}
 
+        if hasattr(image, "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 not d.yesno(msg, width=WIDTH, defaultno=1, height=12):
+                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 the snf-image-creator in expert mode or " \
               "press ESC to quit the program." \
-              % (dev.ostype if dev.ostype == dev.distro else "%s (%s)" %
-                 (dev.ostype, dev.distro))
+              % (image.ostype if image.ostype == image.distro or
+                 image.distro == "unknown" else "%s (%s)" %
+                 (image.ostype, image.distro))
 
         update_background_title(session)
 
@@ -116,7 +135,7 @@ def image_creator(d, media, out, tmp):
             code = d.yesno(msg, width=WIDTH, height=12, yes_label="Wizard",
                            no_label="Expert")
             if code == d.DIALOG_OK:
-                if wizard(session):
+                if start_wizard(session):
                     break
             elif code == d.DIALOG_CANCEL:
                 main_menu(session)
@@ -133,6 +152,10 @@ def image_creator(d, media, out, tmp):
 
 
 def select_file(d, media):
+    """Select a media file"""
+    if media == '/':
+        return '/'
+
     default = os.getcwd() + os.sep
     while 1:
         if media is not None:
@@ -160,8 +183,45 @@ def select_file(d, media):
     return media
 
 
+def _dialog_form(self, text, height=20, width=60, form_height=15, fields=[],
+                 **kwargs):
+    """Display a form box.
+
+    fields is in the form: [(label1, item1, item_length1), ...]
+    """
+
+    cmd = ["--form", text, str(height), str(width), str(form_height)]
+
+    label_len = 0
+    for field in fields:
+        if len(field[0]) > label_len:
+            label_len = len(field[0])
+
+    input_len = width - label_len - 1
+
+    line = 1
+    for field in fields:
+        label = field[0]
+        item = field[1]
+        item_len = field[2]
+        cmd.extend((label, str(line), str(1), item, str(line),
+                   str(label_len + 1), str(input_len), str(item_len)))
+        line += 1
+
+    code, output = self._perform(*(cmd,), **kwargs)
+
+    if not output:
+        return (code, [])
+
+    return (code, output.splitlines())
+
+
 def main():
 
+    # 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
@@ -178,6 +238,10 @@ def main():
     dialog._common_args_syntax["no_label"] = \
         lambda string: ("--no-label", string)
 
+    # Monkey-patch pythondialog to include support for form dialog boxes
+    if not hasattr(dialog, 'form'):
+        d.form = types.MethodType(_dialog_form, d)
+
     usage = "Usage: %prog [options] [<input_media>]"
     parser = optparse.OptionParser(version=version, usage=usage)
     parser.add_option("-l", "--logfile", type="string", dest="logfile",
@@ -220,12 +284,12 @@ def main():
             while 1:
                 try:
                     out = CompositeOutput([log])
-                    out.output("Starting %s v%s..." %
+                    out.output("Starting %s v%s ..." %
                                (parser.get_prog_name(), version))
-                    ret = image_creator(d, media, out, options.tmp)
+                    ret = create_image(d, media, out, options.tmp)
                     sys.exit(ret)
                 except Reset:
-                    log.output("Resetting everything...")
+                    log.output("Resetting everything ...")
                     continue
         finally:
             if logfile is not None: