Code cleanup and refactoring
[snf-image-creator] / image_creator / dialog_main.py
1 #!/usr/bin/env python
2
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
13 #   2. Redistributions in binary form must reproduce the above
14 #      copyright notice, this list of conditions and the following
15 #      disclaimer in the documentation and/or other materials
16 #      provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
30 #
31 # The views and conclusions contained in the software and
32 # documentation are those of the authors and should not be
33 # interpreted as representing official policies, either expressed
34 # or implied, of GRNET S.A.
35
36 import dialog
37 import sys
38 import os
39 import textwrap
40 import signal
41 import optparse
42
43 from image_creator import __version__ as version
44 from image_creator.util import FatalError
45 from image_creator.output import Output
46 from image_creator.output.cli import SimpleOutput
47 from image_creator.output.dialog import GaugeOutput
48 from image_creator.output.composite import CompositeOutput
49 from image_creator.disk import Disk
50 from image_creator.os_type import os_cls
51 from image_creator.dialog_wizard import wizard
52 from image_creator.dialog_menu import main_menu
53 from image_creator.dialog_util import SMALL_WIDTH, WIDTH, confirm_exit, \
54     Reset, update_background_title
55
56
57 def image_creator(d, media, out):
58
59     d.setBackgroundTitle('snf-image-creator')
60
61     gauge = GaugeOutput(d, "Initialization", "Initializing...")
62     out.add(gauge)
63     disk = Disk(media, out)
64
65     def signal_handler(signum, frame):
66         gauge.cleanup()
67         disk.cleanup()
68
69     signal.signal(signal.SIGINT, signal_handler)
70     try:
71         snapshot = disk.snapshot()
72         dev = disk.get_device(snapshot)
73
74         metadata = {}
75         for (key, value) in dev.meta.items():
76             metadata[str(key)] = str(value)
77
78         dev.mount(readonly=True)
79         out.output("Collecting image metadata...")
80         cls = os_cls(dev.distro, dev.ostype)
81         image_os = cls(dev.root, dev.g, out)
82         dev.umount()
83
84         for (key, value) in image_os.meta.items():
85             metadata[str(key)] = str(value)
86
87         out.success("done")
88         gauge.cleanup()
89         out.remove(gauge)
90
91         # Make sure the signal handler does not call gauge.cleanup again
92         def dummy(self):
93             pass
94         gauge.cleanup = type(GaugeOutput.cleanup)(dummy, gauge, GaugeOutput)
95
96         session = {"dialog": d,
97                    "disk": disk,
98                    "snapshot": snapshot,
99                    "device": dev,
100                    "image_os": image_os,
101                    "metadata": metadata}
102
103         msg = "snf-image-creator detected a %s system on the input media. " \
104               "Would you like to run a wizard to assist you through the " \
105               "image creation process?\n\nChoose <Wizard> to run the wizard," \
106               " <Expert> to run the snf-image-creator in expert mode or " \
107               "press ESC to quit the program." \
108               % (dev.ostype if dev.ostype == dev.distro else "%s (%s)" %
109                  (dev.ostype, dev.distro))
110
111         update_background_title(session)
112
113         while True:
114             code = d.yesno(msg, width=WIDTH, height=12, yes_label="Wizard",
115                            no_label="Expert")
116             if code == d.DIALOG_OK:
117                 if wizard(session):
118                     break
119             elif code == d.DIALOG_CANCEL:
120                 main_menu(session)
121                 break
122
123             if confirm_exit(d):
124                 break
125
126         d.infobox("Thank you for using snf-image-creator. Bye", width=53)
127     finally:
128         disk.cleanup()
129
130     return 0
131
132
133 def select_file(d, media):
134     root = os.sep
135     while 1:
136         if media is not None:
137             if not os.path.exists(media):
138                 d.msgbox("The file `%s' you choose does not exist." % media,
139                          width=SMALL_WIDTH)
140             else:
141                 break
142
143         (code, media) = d.fselect(root, 10, 50,
144                                   title="Please select input media")
145         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
146             if confirm_exit(d, "You canceled the media selection dialog box."):
147                 sys.exit(0)
148             else:
149                 media = None
150                 continue
151
152     return media
153
154
155 def main():
156
157     d = dialog.Dialog(dialog="dialog")
158
159     # Add extra button in dialog library
160     dialog._common_args_syntax["extra_button"] = \
161         lambda enable: dialog._simple_option("--extra-button", enable)
162
163     dialog._common_args_syntax["extra_label"] = \
164         lambda string: ("--extra-label", string)
165
166     # Allow yes-no label overwriting
167     dialog._common_args_syntax["yes_label"] = \
168         lambda string: ("--yes-label", string)
169
170     dialog._common_args_syntax["no_label"] = \
171         lambda string: ("--no-label", string)
172
173     usage = "Usage: %prog [options] [<input_media>]"
174     parser = optparse.OptionParser(version=version, usage=usage)
175     parser.add_option("-l", "--logfile", type="string", dest="logfile",
176                       default=None, help="log all messages to FILE",
177                       metavar="FILE")
178
179     options, args = parser.parse_args(sys.argv[1:])
180
181     if len(args) > 1:
182         parser.error("Wrong number of arguments")
183
184     d.setBackgroundTitle('snf-image-creator')
185
186     try:
187         if os.geteuid() != 0:
188             raise FatalError("You must run %s as root" %
189                              parser.get_prog_name())
190
191         media = select_file(d, args[0] if len(args) == 1 else None)
192
193         logfile = None
194         if options.logfile is not None:
195             try:
196                 logfile = open(options.logfile, 'w')
197             except IOError as e:
198                 raise FatalError(
199                     "Unable to open logfile `%s' for writing. Reason: %s" %
200                     (options.logfile, e.strerror))
201         try:
202             log = SimpleOutput(False, logfile) if logfile is not None \
203                 else Output()
204             while 1:
205                 try:
206                     out = CompositeOutput([log])
207                     out.output("Starting %s v%s..." %
208                                (parser.get_prog_name(), version))
209                     ret = image_creator(d, media, out)
210                     sys.exit(ret)
211                 except Reset:
212                     log.output("Resetting everything...")
213                     continue
214         finally:
215             if logfile is not None:
216                 logfile.close()
217     except FatalError as e:
218         msg = textwrap.fill(str(e), width=WIDTH)
219         d.infobox(msg, width=WIDTH, title="Fatal Error")
220         sys.exit(1)
221
222 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :