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