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