Move wizard code out of dialog_main.py
[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 StringIO
42 import optparse
43
44 from image_creator import __version__ as version
45 from image_creator.util import FatalError, MD5
46 from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
47 from image_creator.disk import Disk
48 from image_creator.os_type import os_cls
49 from image_creator.kamaki_wrapper import Kamaki, ClientError
50 from image_creator.help import get_help_file
51 from image_creator.dialog_wizard import wizard
52
53 MSGBOX_WIDTH = 60
54 YESNO_WIDTH = 50
55 MENU_WIDTH = 70
56 INPUTBOX_WIDTH = 70
57 CHECKBOX_WIDTH = 70
58 HELP_WIDTH = 70
59 INFOBOX_WIDTH = 70
60
61 CONFIGURATION_TASKS = [
62     ("Partition table manipulation", ["FixPartitionTable"],
63         ["linux", "windows"]),
64     ("File system resize",
65         ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
66         ["linux", "windows"]),
67     ("Swap partition configuration", ["AddSwap"], ["linux"]),
68     ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
69     ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
70         ["windows"]),
71     ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
72     ("Hostname/Computer Name assignment", ["AssignHostname"],
73         ["windows", "linux"]),
74     ("Password change", ["ChangePassword"], ["windows", "linux"]),
75     ("File injection", ["EnforcePersonality"], ["windows", "linux"])
76 ]
77
78
79 class Reset(Exception):
80     pass
81
82
83 class metadata_monitor(object):
84     def __init__(self, session, meta):
85         self.session = session
86         self.meta = meta
87
88     def __enter__(self):
89         self.old = {}
90         for (k, v) in self.meta.items():
91             self.old[k] = v
92
93     def __exit__(self, type, value, traceback):
94         d = self.session['dialog']
95
96         altered = {}
97         added = {}
98
99         for (k, v) in self.meta.items():
100             if k not in self.old:
101                 added[k] = v
102             elif self.old[k] != v:
103                 altered[k] = v
104
105         if not (len(added) or len(altered)):
106             return
107
108         msg = "The last action has changed some image properties:\n\n"
109         if len(added):
110             msg += "New image properties:\n"
111             for (k, v) in added.items():
112                 msg += '    %s: "%s"\n' % (k, v)
113             msg += "\n"
114         if len(altered):
115             msg += "Updated image properties:\n"
116             for (k, v) in altered.items():
117                 msg += '    %s: "%s" -> "%s"\n' % (k, self.old[k], v)
118             msg += "\n"
119
120         self.session['metadata'].update(added)
121         self.session['metadata'].update(altered)
122         d.msgbox(msg, title="Image Property Changes", width=MSGBOX_WIDTH)
123
124
125 def extract_metadata_string(session):
126     metadata = ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()]
127
128     if 'task_metadata' in session:
129         metadata.extend("%s=yes" % m for m in session['task_metadata'])
130
131     return '\n'.join(metadata) + '\n'
132
133
134 def confirm_exit(d, msg=''):
135     return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
136
137
138 def confirm_reset(d):
139     return not d.yesno("Are you sure you want to reset everything?",
140                        width=YESNO_WIDTH, defaultno=1)
141
142
143 def update_background_title(session):
144     d = session['dialog']
145     dev = session['device']
146
147     MB = 2 ** 20
148
149     size = (dev.meta['SIZE'] + MB - 1) // MB
150     shrinked = 'shrinked' in session and session['shrinked']
151     postfix = " (shrinked)" if shrinked else ''
152
153     title = "OS: %s, Distro: %s, Size: %dMB%s" % \
154             (dev.ostype, dev.distro, size, postfix)
155
156     d.setBackgroundTitle(title)
157
158
159 def extract_image(session):
160     d = session['dialog']
161     dir = os.getcwd()
162     while 1:
163         if dir and dir[-1] != os.sep:
164             dir = dir + os.sep
165
166         (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
167         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
168             return False
169
170         if os.path.isdir(path):
171             dir = path
172             continue
173
174         if os.path.isdir("%s.meta" % path):
175             d.msgbox("Can't overwrite directory `%s.meta'" % path,
176                      width=MSGBOX_WIDTH)
177             continue
178
179         if os.path.isdir("%s.md5sum" % path):
180             d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
181                      width=MSGBOX_WIDTH)
182             continue
183
184         basedir = os.path.dirname(path)
185         name = os.path.basename(path)
186         if not os.path.exists(basedir):
187             d.msgbox("Directory `%s' does not exist" % basedir,
188                      width=MSGBOX_WIDTH)
189             continue
190
191         dir = basedir
192         if len(name) == 0:
193             continue
194
195         files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
196         overwrite = filter(os.path.exists, files)
197
198         if len(overwrite) > 0:
199             if d.yesno("The following file(s) exist:\n"
200                        "%s\nDo you want to overwrite them?" %
201                        "\n".join(overwrite), width=YESNO_WIDTH):
202                 continue
203
204         out = GaugeOutput(d, "Image Extraction", "Extracting image...")
205         try:
206             dev = session['device']
207             if "checksum" not in session:
208                 size = dev.meta['SIZE']
209                 md5 = MD5(out)
210                 session['checksum'] = md5.compute(session['snapshot'], size)
211
212             # Extract image file
213             dev.out = out
214             dev.dump(path)
215
216             # Extract metadata file
217             out.output("Extracting metadata file...")
218             with open('%s.meta' % path, 'w') as f:
219                 f.write(extract_metadata_string(session))
220             out.success('done')
221
222             # Extract md5sum file
223             out.output("Extracting md5sum file...")
224             md5str = "%s %s\n" % (session['checksum'], name)
225             with open('%s.md5sum' % path, 'w') as f:
226                 f.write(md5str)
227             out.success("done")
228
229         finally:
230             out.cleanup()
231         d.msgbox("Image file `%s' was successfully extracted!" % path,
232                  width=MSGBOX_WIDTH)
233         break
234
235     return True
236
237
238 def upload_image(session):
239     d = session["dialog"]
240     size = session['device'].meta['SIZE']
241
242     if "account" not in session:
243         d.msgbox("You need to provide your ~okeanos login username before you "
244                  "can upload images to pithos+", width=MSGBOX_WIDTH)
245         return False
246
247     if "token" not in session:
248         d.msgbox("You need to provide your ~okeanos account authentication "
249                  "token before you can upload images to pithos+",
250                  width=MSGBOX_WIDTH)
251         return False
252
253     while 1:
254         init = session["upload"] if "upload" in session else ''
255         (code, answer) = d.inputbox("Please provide a filename:", init=init,
256                                     width=INPUTBOX_WIDTH)
257
258         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
259             return False
260
261         filename = answer.strip()
262         if len(filename) == 0:
263             d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
264             continue
265
266         break
267
268     out = GaugeOutput(d, "Image Upload", "Uploading...")
269     try:
270         if 'checksum' not in session:
271             md5 = MD5(out)
272             session['checksum'] = md5.compute(session['snapshot'], size)
273         kamaki = Kamaki(session['account'], session['token'], out)
274         try:
275             # Upload image file
276             with open(session['snapshot'], 'rb') as f:
277                 session["upload"] = kamaki.upload(f, size, filename,
278                                                   "Calculating block hashes",
279                                                   "Uploading missing blocks")
280             # Upload metadata file
281             out.output("Uploading metadata file...")
282             metastring = extract_metadata_string(session)
283             kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
284                           remote_path="%s.meta" % filename)
285             out.success("done")
286
287             # Upload md5sum file
288             out.output("Uploading md5sum file...")
289             md5str = "%s %s\n" % (session['checksum'], filename)
290             kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
291                           remote_path="%s.md5sum" % filename)
292             out.success("done")
293
294         except ClientError as e:
295             d.msgbox("Error in pithos+ client: %s" % e.message,
296                      title="Pithos+ Client Error", width=MSGBOX_WIDTH)
297             if 'upload' in session:
298                 del session['upload']
299             return False
300     finally:
301         out.cleanup()
302
303     d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
304              width=MSGBOX_WIDTH)
305
306     return True
307
308
309 def register_image(session):
310     d = session["dialog"]
311
312     if "account" not in session:
313         d.msgbox("You need to provide your ~okeanos login username before you "
314                  "can register an images to cyclades",
315                  width=MSGBOX_WIDTH)
316         return False
317
318     if "token" not in session:
319         d.msgbox("You need to provide your ~okeanos account authentication "
320                  "token before you can register an images to cyclades",
321                  width=MSGBOX_WIDTH)
322         return False
323
324     if "upload" not in session:
325         d.msgbox("You need to upload the image to pithos+ before you can "
326                  "register it to cyclades", width=MSGBOX_WIDTH)
327         return False
328
329     while 1:
330         (code, answer) = d.inputbox("Please provide a registration name:",
331                                     width=INPUTBOX_WIDTH)
332         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
333             return False
334
335         name = answer.strip()
336         if len(name) == 0:
337             d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
338             continue
339         break
340
341     metadata = {}
342     metadata.update(session['metadata'])
343     if 'task_metadata' in session:
344         for key in session['task_metadata']:
345             metadata[key] = 'yes'
346
347     out = GaugeOutput(d, "Image Registration", "Registrating image...")
348     try:
349         out.output("Registring image to cyclades...")
350         try:
351             kamaki = Kamaki(session['account'], session['token'], out)
352             kamaki.register(name, session['upload'], metadata)
353             out.success('done')
354         except ClientError as e:
355             d.msgbox("Error in pithos+ client: %s" % e.message)
356             return False
357     finally:
358         out.cleanup()
359
360     d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
361              (session['upload'], name), width=MSGBOX_WIDTH)
362     return True
363
364
365 def kamaki_menu(session):
366     d = session['dialog']
367     default_item = "Account"
368
369     (session['account'], session['token']) = Kamaki.saved_credentials()
370     while 1:
371         account = session["account"] if "account" in session else "<none>"
372         token = session["token"] if "token" in session else "<none>"
373         upload = session["upload"] if "upload" in session else "<none>"
374
375         choices = [("Account", "Change your ~okeanos username: %s" % account),
376                    ("Token", "Change your ~okeanos token: %s" % token),
377                    ("Upload", "Upload image to pithos+"),
378                    ("Register", "Register the image to cyclades: %s" % upload)]
379
380         (code, choice) = d.menu(
381             text="Choose one of the following or press <Back> to go back.",
382             width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
383             menu_height=5, default_item=default_item,
384             title="Image Registration Menu")
385
386         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
387             return False
388
389         if choice == "Account":
390             default_item = "Account"
391             (code, answer) = d.inputbox(
392                 "Please provide your ~okeanos account e-mail address:",
393                 init=session["account"] if "account" in session else '',
394                 width=70)
395             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
396                 continue
397             if len(answer) == 0 and "account" in session:
398                     del session["account"]
399             else:
400                 session["account"] = answer.strip()
401                 Kamaki.save_account(session['account'])
402                 default_item = "Token"
403         elif choice == "Token":
404             default_item = "Token"
405             (code, answer) = d.inputbox(
406                 "Please provide your ~okeanos account authetication token:",
407                 init=session["token"] if "token" in session else '',
408                 width=70)
409             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
410                 continue
411             if len(answer) == 0 and "token" in session:
412                 del session["token"]
413             else:
414                 session["token"] = answer.strip()
415                 Kamaki.save_token(session['account'])
416                 default_item = "Upload"
417         elif choice == "Upload":
418             if upload_image(session):
419                 default_item = "Register"
420             else:
421                 default_item = "Upload"
422         elif choice == "Register":
423             if register_image(session):
424                 return True
425             else:
426                 default_item = "Register"
427
428
429 def add_property(session):
430     d = session['dialog']
431
432     while 1:
433         (code, answer) = d.inputbox("Please provide a name for a new image"
434                                     " property:", width=INPUTBOX_WIDTH)
435         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
436             return False
437
438         name = answer.strip()
439         if len(name) == 0:
440             d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
441             continue
442
443         break
444
445     while 1:
446         (code, answer) = d.inputbox("Please provide a value for image "
447                                     "property %s" % name, width=INPUTBOX_WIDTH)
448         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
449             return False
450
451         value = answer.strip()
452         if len(value) == 0:
453             d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
454             continue
455
456         break
457
458     session['metadata'][name] = value
459
460     return True
461
462
463 def modify_properties(session):
464     d = session['dialog']
465
466     while 1:
467         choices = []
468         for (key, val) in session['metadata'].items():
469             choices.append((str(key), str(val)))
470
471         (code, choice) = d.menu(
472             "In this menu you can edit existing image properties or add new "
473             "ones. Be careful! Most properties have special meaning and "
474             "alter the image deployment behaviour. Press <HELP> to see more "
475             "information about image properties. Press <BACK> when done.",
476             height=18, width=MENU_WIDTH, choices=choices, menu_height=10,
477             ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
478             help_button=1, title="Image Properties")
479
480         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
481             return True
482         # Edit button
483         elif code == d.DIALOG_OK:
484             (code, answer) = d.inputbox("Please provide a new value for the "
485                                         "image property with name `%s':" %
486                                         choice,
487                                         init=session['metadata'][choice],
488                                         width=INPUTBOX_WIDTH)
489             if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
490                 value = answer.strip()
491                 if len(value) == 0:
492                     d.msgbox("Value cannot be empty!")
493                     continue
494                 else:
495                     session['metadata'][choice] = value
496         # ADD button
497         elif code == d.DIALOG_EXTRA:
498             add_property(session)
499         elif code == 'help':
500             help_file = get_help_file("image_properties")
501             assert os.path.exists(help_file)
502             d.textbox(help_file, title="Image Properties", width=70, height=40)
503
504
505 def delete_properties(session):
506     d = session['dialog']
507
508     choices = []
509     for (key, val) in session['metadata'].items():
510         choices.append((key, "%s" % val, 0))
511
512     (code, to_delete) = d.checklist("Choose which properties to delete:",
513                                     choices=choices, width=CHECKBOX_WIDTH)
514
515     # If the user exits with ESC or CANCEL, the returned tag list is empty.
516     for i in to_delete:
517         del session['metadata'][i]
518
519     cnt = len(to_delete)
520     if cnt > 0:
521         d.msgbox("%d image properties were deleted." % cnt, width=MSGBOX_WIDTH)
522         return True
523     else:
524         return False
525
526
527 def exclude_tasks(session):
528     d = session['dialog']
529
530     index = 0
531     displayed_index = 1
532     choices = []
533     mapping = {}
534     if 'excluded_tasks' not in session:
535         session['excluded_tasks'] = []
536
537     if -1 in session['excluded_tasks']:
538         if not d.yesno("Image deployment configuration is disabled. "
539                        "Do you wish to enable it?", width=YESNO_WIDTH):
540             session['excluded_tasks'].remove(-1)
541         else:
542             return False
543
544     for (msg, task, osfamily) in CONFIGURATION_TASKS:
545         if session['metadata']['OSFAMILY'] in osfamily:
546             checked = 1 if index in session['excluded_tasks'] else 0
547             choices.append((str(displayed_index), msg, checked))
548             mapping[displayed_index] = index
549             displayed_index += 1
550         index += 1
551
552     while 1:
553         (code, tags) = d.checklist(
554             text="Please choose which configuration tasks you would like to "
555                  "prevent from running during image deployment. "
556                  "Press <No Config> to supress any configuration. "
557                  "Press <Help> for more help on the image deployment "
558                  "configuration tasks.",
559             choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
560             help_button=1, extra_button=1, extra_label="No Config",
561             title="Exclude Configuration Tasks")
562
563         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
564             return False
565         elif code == d.DIALOG_HELP:
566             help_file = get_help_file("configuration_tasks")
567             assert os.path.exists(help_file)
568             d.textbox(help_file, title="Configuration Tasks",
569                       width=70, height=40)
570         # No Config button
571         elif code == d.DIALOG_EXTRA:
572             session['excluded_tasks'] = [-1]
573             session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
574             break
575         elif code == d.DIALOG_OK:
576             session['excluded_tasks'] = []
577             for tag in tags:
578                 session['excluded_tasks'].append(mapping[int(tag)])
579
580             exclude_metadata = []
581             for task in session['excluded_tasks']:
582                 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
583
584             session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
585                                            exclude_metadata)
586             break
587
588     return True
589
590
591 def sysprep(session):
592     d = session['dialog']
593     image_os = session['image_os']
594
595     # Is the image already shrinked?
596     if 'shrinked' in session and session['shrinked']:
597         msg = "It seems you have shrinked the image. Running system " \
598               "preparation tasks on a shrinked image is dangerous."
599
600         if d.yesno("%s\n\nDo you really want to continue?" % msg,
601                    width=YESNO_WIDTH, defaultno=1):
602             return
603
604     wrapper = textwrap.TextWrapper(width=65)
605
606     help_title = "System Preperation Tasks"
607     sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
608
609     if 'exec_syspreps' not in session:
610         session['exec_syspreps'] = []
611
612     all_syspreps = image_os.list_syspreps()
613     # Only give the user the choice between syspreps that have not ran yet
614     syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
615
616     if len(syspreps) == 0:
617         d.msgbox("No system preparation task available to run!",
618                  title="System Preperation", width=MSGBOX_WIDTH)
619         return
620
621     while 1:
622         choices = []
623         index = 0
624         for sysprep in syspreps:
625             name, descr = image_os.sysprep_info(sysprep)
626             display_name = name.replace('-', ' ').capitalize()
627             sysprep_help += "%s\n" % display_name
628             sysprep_help += "%s\n" % ('-' * len(display_name))
629             sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
630             enabled = 1 if sysprep.enabled else 0
631             choices.append((str(index + 1), display_name, enabled))
632             index += 1
633
634         (code, tags) = d.checklist(
635             "Please choose which system preperation tasks you would like to "
636             "run on the image. Press <Help> to see details about the system "
637             "preperation tasks.", title="Run system preperation tasks",
638             choices=choices, width=70, ok_label="Run", help_button=1)
639
640         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
641             return False
642         elif code == d.DIALOG_HELP:
643             d.scrollbox(sysprep_help, width=HELP_WIDTH)
644         elif code == d.DIALOG_OK:
645             # Enable selected syspreps and disable the rest
646             for i in range(len(syspreps)):
647                 if str(i + 1) in tags:
648                     image_os.enable_sysprep(syspreps[i])
649                     session['exec_syspreps'].append(syspreps[i])
650                 else:
651                     image_os.disable_sysprep(syspreps[i])
652
653             out = InfoBoxOutput(d, "Image Configuration")
654             try:
655                 dev = session['device']
656                 dev.out = out
657                 dev.mount(readonly=False)
658                 try:
659                     # The checksum is invalid. We have mounted the image rw
660                     if 'checksum' in session:
661                         del session['checksum']
662
663                     # Monitor the metadata changes during syspreps
664                     with metadata_monitor(session, image_os.meta):
665                         image_os.out = out
666                         image_os.do_sysprep()
667                         image_os.out.finalize()
668
669                     # Disable syspreps that have ran
670                     for sysprep in session['exec_syspreps']:
671                         image_os.disable_sysprep(sysprep)
672
673                 finally:
674                     dev.umount()
675             finally:
676                 out.cleanup()
677             break
678     return True
679
680
681 def shrink(session):
682     d = session['dialog']
683     dev = session['device']
684
685     shrinked = 'shrinked' in session and session['shrinked']
686
687     if shrinked:
688         d.msgbox("The image is already shrinked!", title="Image Shrinking",
689                  width=MSGBOX_WIDTH)
690         return True
691
692     msg = "This operation will shrink the last partition of the image to " \
693           "reduce the total image size. If the last partition is a swap " \
694           "partition, then this partition is removed and the partition " \
695           "before that is shrinked. The removed swap partition will be " \
696           "recreated during image deployment."
697
698     if not d.yesno("%s\n\nDo you want to continue?" % msg, width=70,
699                    height=12, title="Image Shrinking"):
700         with metadata_monitor(session, dev.meta):
701             dev.out = InfoBoxOutput(d, "Image Shrinking", height=4)
702             dev.shrink()
703             dev.out.finalize()
704
705         session['shrinked'] = True
706         update_background_title(session)
707     else:
708         return False
709
710     return True
711
712
713 def customization_menu(session):
714     d = session['dialog']
715
716     choices = [("Sysprep", "Run various image preperation tasks"),
717                ("Shrink", "Shrink image"),
718                ("View/Modify", "View/Modify image properties"),
719                ("Delete", "Delete image properties"),
720                ("Exclude", "Exclude various deployment tasks from running")]
721
722     default_item = 0
723
724     actions = {"Sysprep": sysprep,
725                "Shrink": shrink,
726                "View/Modify": modify_properties,
727                "Delete": delete_properties,
728                "Exclude": exclude_tasks}
729     while 1:
730         (code, choice) = d.menu(
731             text="Choose one of the following or press <Back> to exit.",
732             width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
733             menu_height=len(choices), default_item=choices[default_item][0],
734             title="Image Customization Menu")
735
736         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
737             break
738         elif choice in actions:
739             default_item = [entry[0] for entry in choices].index(choice)
740             if actions[choice](session):
741                 default_item = (default_item + 1) % len(choices)
742
743
744 def main_menu(session):
745     d = session['dialog']
746     dev = session['device']
747
748     update_background_title(session)
749
750     choices = [("Customize", "Customize image & ~okeanos deployment options"),
751                ("Register", "Register image to ~okeanos"),
752                ("Extract", "Dump image to local file system"),
753                ("Reset", "Reset everything and start over again"),
754                ("Help", "Get help for using snf-image-creator")]
755
756     default_item = "Customize"
757
758     actions = {"Customize": customization_menu, "Register": kamaki_menu,
759                "Extract": extract_image}
760     while 1:
761         (code, choice) = d.menu(
762             text="Choose one of the following or press <Exit> to exit.",
763             width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
764             default_item=default_item, menu_height=len(choices),
765             title="Image Creator for ~okeanos (snf-image-creator version %s)" %
766                   version)
767
768         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
769             if confirm_exit(d):
770                 break
771         elif choice == "Reset":
772             if confirm_reset(d):
773                 d.infobox("Resetting snf-image-creator. Please wait...",
774                           width=INFOBOX_WIDTH)
775                 raise Reset
776         elif choice in actions:
777             actions[choice](session)
778
779
780 def select_file(d, media):
781     root = os.sep
782     while 1:
783         if media is not None:
784             if not os.path.exists(media):
785                 d.msgbox("The file you choose does not exist",
786                          width=MSGBOX_WIDTH)
787             else:
788                 break
789
790         (code, media) = d.fselect(root, 10, 50,
791                                   title="Please select input media")
792         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
793             if confirm_exit(d, "You canceled the media selection dialog box."):
794                 sys.exit(0)
795             else:
796                 media = None
797                 continue
798
799     return media
800
801
802 def image_creator(d):
803
804     usage = "Usage: %prog [options] [<input_media>]"
805     parser = optparse.OptionParser(version=version, usage=usage)
806
807     options, args = parser.parse_args(sys.argv[1:])
808
809     if len(args) > 1:
810         parser.error("Wrong numver of arguments")
811
812     d.setBackgroundTitle('snf-image-creator')
813
814     if os.geteuid() != 0:
815         raise FatalError("You must run %s as root" % basename)
816
817     media = select_file(d, args[0] if len(args) == 1 else None)
818
819     out = GaugeOutput(d, "Initialization", "Initializing...")
820     disk = Disk(media, out)
821
822     def signal_handler(signum, frame):
823         out.cleanup()
824         disk.cleanup()
825
826     signal.signal(signal.SIGINT, signal_handler)
827     try:
828         snapshot = disk.snapshot()
829         dev = disk.get_device(snapshot)
830
831         metadata = {}
832         for (key, value) in dev.meta.items():
833             metadata[str(key)] = str(value)
834
835         dev.mount(readonly=True)
836         out.output("Collecting image metadata...")
837         cls = os_cls(dev.distro, dev.ostype)
838         image_os = cls(dev.root, dev.g, out)
839         dev.umount()
840
841         for (key, value) in image_os.meta.items():
842             metadata[str(key)] = str(value)
843
844         out.success("done")
845         out.cleanup()
846
847         # Make sure the signal handler does not call out.cleanup again
848         def dummy(self):
849             pass
850         out.cleanup = type(GaugeOutput.cleanup)(dummy, out, GaugeOutput)
851
852         session = {"dialog": d,
853                    "disk": disk,
854                    "snapshot": snapshot,
855                    "device": dev,
856                    "image_os": image_os,
857                    "metadata": metadata}
858
859         msg = "snf-image-creator detected a %s system on the input media. " \
860               "Would you like to run a wizards to assists you through the " \
861               "image creation process?\n\nChoose <Yes> to run the wizard, " \
862               "<No> to run the snf-image-creator in expert mode or press " \
863               "ESC to quit the program." \
864               % (dev.ostype if dev.ostype == dev.distro else "%s/%s" %
865                  (dev.distro, dev.ostype))
866
867         while True:
868             code = d.yesno(msg, width=YESNO_WIDTH, height=12)
869             if code == d.DIALOG_OK:
870                 if wizard(session):
871                     break
872             elif code == d.DIALOG_CANCEL:
873                 main_menu(session)
874                 break
875
876             exit_msg = "You have not selected if you want to run " \
877                        "snf-image-creator in wizard or expert mode."
878             if confirm_exit(d, exit_msg):
879                 break
880
881         d.infobox("Thank you for using snf-image-creator. Bye", width=53)
882     finally:
883         disk.cleanup()
884
885     return 0
886
887
888 def main():
889
890     d = dialog.Dialog(dialog="dialog")
891
892     # Add extra button in dialog library
893     dialog._common_args_syntax["extra_button"] = \
894         lambda enable: dialog._simple_option("--extra-button", enable)
895
896     dialog._common_args_syntax["extra_label"] = \
897         lambda string: ("--extra-label", string)
898
899     while 1:
900         try:
901             try:
902                 ret = image_creator(d)
903                 sys.exit(ret)
904             except FatalError as e:
905                 msg = textwrap.fill(str(e), width=70)
906                 d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
907                 sys.exit(1)
908         except Reset:
909             continue
910
911 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :