1 # -*- coding: utf-8 -*-
3 # Copyright 2012 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
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.
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.
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.
36 """This module implements the "expert" mode of the dialog-based version of
45 from image_creator import __version__ as version
46 from image_creator.util import MD5, FatalError
47 from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
48 from image_creator.kamaki_wrapper import Kamaki, ClientError
49 from image_creator.help import get_help_file
50 from image_creator.dialog_util import SMALL_WIDTH, WIDTH, \
51 update_background_title, confirm_reset, confirm_exit, Reset, \
52 extract_image, extract_metadata_string, add_cloud, edit_cloud
54 CONFIGURATION_TASKS = [
55 ("Partition table manipulation", ["FixPartitionTable"],
56 ["linux", "windows"]),
57 ("File system resize",
58 ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
59 ["linux", "windows"]),
60 ("Swap partition configuration", ["AddSwap"], ["linux"]),
61 ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
62 ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
64 ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
65 ("Hostname/Computer Name assignment", ["AssignHostname"],
66 ["windows", "linux"]),
67 ("Password change", ["ChangePassword"], ["windows", "linux"]),
68 ("File injection", ["EnforcePersonality"], ["windows", "linux"])
71 SYSPREP_PARAM_MAXLEN = 20
74 class MetadataMonitor(object):
75 """Monitors image metadata chages"""
76 def __init__(self, session, meta):
77 self.session = session
82 for (k, v) in self.meta.items():
85 def __exit__(self, type, value, traceback):
86 d = self.session['dialog']
91 for (k, v) in self.meta.items():
94 elif self.old[k] != v:
97 if not (len(added) or len(altered)):
100 msg = "The last action has changed some image properties:\n\n"
102 msg += "New image properties:\n"
103 for (k, v) in added.items():
104 msg += ' %s: "%s"\n' % (k, v)
107 msg += "Updated image properties:\n"
108 for (k, v) in altered.items():
109 msg += ' %s: "%s" -> "%s"\n' % (k, self.old[k], v)
112 self.session['metadata'].update(added)
113 self.session['metadata'].update(altered)
114 d.msgbox(msg, title="Image Property Changes", width=SMALL_WIDTH)
117 def upload_image(session):
118 """Upload the image to the storage service"""
119 d = session["dialog"]
120 image = session['image']
121 meta = session['metadata']
124 if "account" not in session:
125 d.msgbox("You need to select a valid cloud before you can upload "
126 "images to it", width=SMALL_WIDTH)
130 if 'upload' in session:
131 init = session['upload']
133 init = "%s.diskdump" % meta['OS']
136 (code, answer) = d.inputbox("Please provide a filename:", init=init,
139 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
142 filename = answer.strip()
143 if len(filename) == 0:
144 d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
147 kamaki = Kamaki(session['account'], None)
149 for f in (filename, "%s.md5sum" % filename, "%s.meta" % filename):
150 if kamaki.object_exists(f):
153 if len(overwrite) > 0:
154 if d.yesno("The following storage service object(s) already "
155 "exist(s):\n%s\nDo you want to overwrite them?" %
156 "\n".join(overwrite), width=WIDTH, defaultno=1):
159 session['upload'] = filename
162 gauge = GaugeOutput(d, "Image Upload", "Uploading ...")
168 if 'checksum' not in session:
170 session['checksum'] = md5.compute(image.device, size)
174 with open(image.device, 'rb') as f:
175 session["pithos_uri"] = \
176 kamaki.upload(f, size, filename,
177 "Calculating block hashes",
178 "Uploading missing blocks")
180 out.output("Uploading md5sum file ...")
181 md5str = "%s %s\n" % (session['checksum'], filename)
182 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
183 remote_path="%s.md5sum" % filename)
186 except ClientError as e:
188 "Error in storage service client: %s" % e.message,
189 title="Storage Service Client Error", width=SMALL_WIDTH)
190 if 'pithos_uri' in session:
191 del session['pithos_uri']
198 d.msgbox("Image file `%s' was successfully uploaded" % filename,
204 def register_image(session):
205 """Register image with the compute service"""
206 d = session["dialog"]
210 if "account" not in session:
211 d.msgbox("You need to select a valid cloud before you "
212 "can register an images with it", width=SMALL_WIDTH)
215 if "pithos_uri" not in session:
216 d.msgbox("You need to upload the image to the cloud before you can "
217 "register it", width=SMALL_WIDTH)
221 (code, answer) = d.inputbox("Please provide a registration name:",
223 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
226 name = answer.strip()
228 d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
231 ret = d.yesno("Make the image public?\\nA public image is accessible "
232 "by every user of the service.", defaultno=1,
234 if ret not in (0, 1):
237 is_public = True if ret == 0 else False
242 metadata.update(session['metadata'])
243 if 'task_metadata' in session:
244 for key in session['task_metadata']:
245 metadata[key] = 'yes'
247 img_type = "public" if is_public else "private"
248 gauge = GaugeOutput(d, "Image Registration", "Registering image ...")
250 out = session['image'].out
254 out.output("Registering %s image with the cloud ..." %
256 kamaki = Kamaki(session['account'], out)
257 result = kamaki.register(name, session['pithos_uri'], metadata,
260 # Upload metadata file
261 out.output("Uploading metadata file ...")
262 metastring = unicode(json.dumps(result, ensure_ascii=False))
263 kamaki.upload(StringIO.StringIO(metastring),
264 size=len(metastring),
265 remote_path="%s.meta" % session['upload'])
268 out.output("Sharing metadata and md5sum files ...")
269 kamaki.share("%s.meta" % session['upload'])
270 kamaki.share("%s.md5sum" % session['upload'])
272 except ClientError as e:
273 d.msgbox("Error in storage service client: %s" % e.message)
280 d.msgbox("%s image `%s' was successfully registered with the cloud as `%s'"
281 % (img_type.title(), session['upload'], name), width=SMALL_WIDTH)
285 def modify_clouds(session):
286 """Modify existing cloud accounts"""
287 d = session['dialog']
290 clouds = Kamaki.get_clouds()
292 if not add_cloud(session):
297 for (name, cloud) in clouds.items():
298 descr = cloud['description'] if 'description' in cloud else ''
299 choices.append((name, descr))
301 (code, choice) = d.menu(
302 "In this menu you can edit existing cloud accounts or add new "
303 " ones. Press <Edit> to edit an existing account or <Add> to add "
304 " a new one. Press <Back> or hit <ESC> when done.", height=18,
305 width=WIDTH, choices=choices, menu_height=10, ok_label="Edit",
306 extra_button=1, extra_label="Add", cancel="Back", help_button=1,
309 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
311 elif code == d.DIALOG_OK: # Edit button
312 edit_cloud(session, choice)
313 elif code == d.DIALOG_EXTRA: # Add button
317 def delete_clouds(session):
318 """Delete existing cloud accounts"""
319 d = session['dialog']
322 for (name, cloud) in Kamaki.get_clouds().items():
323 descr = cloud['description'] if 'description' in cloud else ''
324 choices.append((name, descr, 0))
326 if len(choices) == 0:
327 d.msgbox("No available clouds to delete!", width=SMALL_WIDTH)
330 (code, to_delete) = d.checklist("Choose which cloud accounts to delete:",
331 choices=choices, width=WIDTH)
332 to_delete = map(lambda x: x.strip('"'), to_delete) # Needed for OpenSUSE
334 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
337 if not len(to_delete):
338 d.msgbox("Nothing selected!", width=SMALL_WIDTH)
341 if not d.yesno("Are you sure you want to remove the selected cloud "
342 "accounts?", width=WIDTH, defaultno=1):
344 Kamaki.remove_cloud(i)
345 if 'cloud' in session and session['cloud'] == i:
347 if 'account' in session:
348 del session['account']
352 d.msgbox("%d cloud accounts were deleted." % len(to_delete),
357 def kamaki_menu(session):
358 """Show kamaki related actions"""
359 d = session['dialog']
360 default_item = "Cloud"
362 if 'cloud' not in session:
363 cloud = Kamaki.get_default_cloud_name()
365 session['cloud'] = cloud
366 session['account'] = Kamaki.get_account(cloud)
367 if not session['account']:
368 del session['account']
370 default_item = "Add/Edit"
373 cloud = session["cloud"] if "cloud" in session else "<none>"
374 if 'account' not in session and 'cloud' in session:
375 cloud += " <invalid>"
377 upload = session["upload"] if "upload" in session else "<none>"
379 choices = [("Add/Edit", "Add/Edit cloud accounts"),
380 ("Delete", "Delete existing cloud accounts"),
381 ("Cloud", "Select cloud account to use: %s" % cloud),
382 ("Upload", "Upload image to the cloud"),
383 ("Register", "Register image with the cloud: %s" % upload)]
385 (code, choice) = d.menu(
386 text="Choose one of the following or press <Back> to go back.",
387 width=WIDTH, choices=choices, cancel="Back", height=13,
388 menu_height=5, default_item=default_item,
389 title="Image Registration Menu")
391 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
394 if choice == "Add/Edit":
395 if modify_clouds(session):
396 default_item = "Cloud"
397 elif choice == "Delete":
398 if delete_clouds(session):
399 if len(Kamaki.get_clouds()):
400 default_item = "Cloud"
402 default_item = "Add/Edit"
404 default_item = "Delete"
405 elif choice == "Cloud":
406 default_item = "Cloud"
407 clouds = Kamaki.get_clouds()
409 d.msgbox("No clouds available. Please add a new cloud!",
411 default_item = "Add/Edit"
414 if 'cloud' not in session:
415 session['cloud'] = clouds.keys()[0]
418 for name, info in clouds.items():
419 default = 1 if session['cloud'] == name else 0
420 descr = info['description'] if 'description' in info else ""
421 choices.append((name, descr, default))
423 (code, answer) = d.radiolist("Please select a cloud:",
424 width=WIDTH, choices=choices)
425 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
428 session['account'] = Kamaki.get_account(answer)
430 if session['account'] is None: # invalid account
431 if not d.yesno("The cloud %s' is not valid! Would you "
432 "like to edit it?" % answer, width=WIDTH):
433 if edit_cloud(session, answer):
434 session['account'] = Kamaki.get_account(answer)
435 Kamaki.set_default_cloud(answer)
437 if session['account'] is not None:
438 session['cloud'] = answer
439 Kamaki.set_default_cloud(answer)
440 default_item = "Upload"
442 del session['account']
444 elif choice == "Upload":
445 if upload_image(session):
446 default_item = "Register"
448 default_item = "Upload"
449 elif choice == "Register":
450 if register_image(session):
453 default_item = "Register"
456 def add_property(session):
457 """Add a new property to the image"""
458 d = session['dialog']
461 (code, answer) = d.inputbox("Please provide a name for a new image"
462 " property:", width=WIDTH)
463 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
466 name = answer.strip()
468 d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
474 (code, answer) = d.inputbox("Please provide a value for image "
475 "property %s" % name, width=WIDTH)
476 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
479 value = answer.strip()
481 d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
486 session['metadata'][name] = value
491 def show_properties_help(session):
492 """Show help for image properties"""
493 d = session['dialog']
495 help_file = get_help_file("image_properties")
496 assert os.path.exists(help_file)
497 d.textbox(help_file, title="Image Properties", width=70, height=40)
500 def modify_properties(session):
501 """Modify an existing image property"""
502 d = session['dialog']
506 for (key, val) in session['metadata'].items():
507 choices.append((str(key), str(val)))
509 if len(choices) == 0:
511 "No image properties are available. "
512 "Would you like to add a new one?", width=WIDTH, help_button=1)
513 if code == d.DIALOG_OK:
514 if not add_property(session):
516 elif code == d.DIALOG_CANCEL:
518 elif code == d.DIALOG_HELP:
519 show_properties_help(session)
522 (code, choice) = d.menu(
523 "In this menu you can edit existing image properties or add new "
524 "ones. Be careful! Most properties have special meaning and "
525 "alter the image deployment behaviour. Press <HELP> to see more "
526 "information about image properties. Press <BACK> when done.",
527 height=18, width=WIDTH, choices=choices, menu_height=10,
528 ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
529 help_button=1, title="Image Properties")
531 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
534 elif code == d.DIALOG_OK:
535 (code, answer) = d.inputbox("Please provide a new value for the "
536 "image property with name `%s':" %
538 init=session['metadata'][choice],
540 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
541 value = answer.strip()
543 d.msgbox("Value cannot be empty!")
546 session['metadata'][choice] = value
548 elif code == d.DIALOG_EXTRA:
549 add_property(session)
551 show_properties_help(session)
554 def delete_properties(session):
555 """Delete an image property"""
556 d = session['dialog']
559 for (key, val) in session['metadata'].items():
560 choices.append((key, "%s" % val, 0))
562 if len(choices) == 0:
563 d.msgbox("No available images properties to delete!",
567 (code, to_delete) = d.checklist("Choose which properties to delete:",
568 choices=choices, width=WIDTH)
569 to_delete = map(lambda x: x.strip('"'), to_delete) # needed for OpenSUSE
571 # If the user exits with ESC or CANCEL, the returned tag list is empty.
573 del session['metadata'][i]
577 d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
583 def exclude_tasks(session):
584 """Exclude specific tasks from running during image deployment"""
585 d = session['dialog']
586 image = session['image']
588 if hasattr(image, "unsupported"):
589 d.msgbox("You cannot configure the deployment tasks for an unsupported"
590 " image.", width=SMALL_WIDTH)
597 if 'excluded_tasks' not in session:
598 session['excluded_tasks'] = []
600 if -1 in session['excluded_tasks']:
601 if not d.yesno("Image deployment configuration is disabled. "
602 "Do you wish to enable it?", width=SMALL_WIDTH):
603 session['excluded_tasks'].remove(-1)
607 for (msg, task, osfamily) in CONFIGURATION_TASKS:
608 if session['metadata']['OSFAMILY'] in osfamily:
609 checked = 1 if index in session['excluded_tasks'] else 0
610 choices.append((str(displayed_index), msg, checked))
611 mapping[displayed_index] = index
616 (code, tags) = d.checklist(
617 text="Please choose which configuration tasks you would like to "
618 "prevent from running during image deployment. "
619 "Press <No Config> to supress any configuration. "
620 "Press <Help> for more help on the image deployment "
621 "configuration tasks.",
622 choices=choices, height=19, list_height=8, width=WIDTH,
623 help_button=1, extra_button=1, extra_label="No Config",
624 title="Exclude Configuration Tasks")
625 tags = map(lambda x: x.strip('"'), tags) # Needed for OpenSUSE
627 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
629 elif code == d.DIALOG_HELP:
630 help_file = get_help_file("configuration_tasks")
631 assert os.path.exists(help_file)
632 d.textbox(help_file, title="Configuration Tasks",
635 elif code == d.DIALOG_EXTRA:
636 session['excluded_tasks'] = [-1]
637 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
639 elif code == d.DIALOG_OK:
640 session['excluded_tasks'] = []
642 session['excluded_tasks'].append(mapping[int(tag)])
644 exclude_metadata = []
645 for task in session['excluded_tasks']:
646 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
648 session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
655 def sysprep_params(session):
656 """Collect the needed sysprep parameters"""
657 d = session['dialog']
658 image = session['image']
660 available = image.os.sysprep_params
661 needed = image.os.needed_sysprep_params
666 def print_form(names, extra_button=False):
667 """print the dialog form providing sysprep_params"""
671 default = str(available[name]) if name in available else ""
672 fields.append(("%s: " % param.description, default,
673 SYSPREP_PARAM_MAXLEN))
677 kwargs['extra_button'] = 1
678 kwargs['extra_label'] = "Advanced"
680 txt = "Please provide the following system preparation parameters:"
681 return d.form(txt, height=13, width=WIDTH, form_height=len(fields),
682 fields=fields, **kwargs)
684 def check_params(names, values):
685 """check if the provided sysprep parameters have leagal values"""
686 for i in range(len(names)):
687 param = needed[names[i]]
689 normalized = param.type(values[i])
690 if param.validate(normalized):
691 image.os.sysprep_params[names[i]] = normalized
696 d.msgbox("Invalid value for parameter: `%s'" % names[i],
701 simple_names = [k for k, v in needed.items() if v.default is None]
702 advanced_names = [k for k, v in needed.items() if v.default is not None]
705 code, output = print_form(simple_names, extra_button=True)
707 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
709 if code == d.DIALOG_EXTRA:
711 code, output = print_form(advanced_names)
712 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
714 if check_params(advanced_names, output):
718 if check_params(simple_names, output):
724 def sysprep(session):
725 """Perform various system preperation tasks on the image"""
726 d = session['dialog']
727 image = session['image']
729 # Is the image already shrinked?
730 if 'shrinked' in session and session['shrinked']:
731 msg = "It seems you have shrinked the image. Running system " \
732 "preparation tasks on a shrinked image is dangerous."
734 if d.yesno("%s\n\nDo you really want to continue?" % msg,
735 width=SMALL_WIDTH, defaultno=1):
738 wrapper = textwrap.TextWrapper(width=WIDTH - 5)
740 syspreps = image.os.list_syspreps()
742 if len(syspreps) == 0:
743 d.msgbox("No system preparation task available to run!",
744 title="System Preperation", width=SMALL_WIDTH)
751 help_title = "System Preperation Tasks"
752 sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
754 for sysprep in syspreps:
755 name, descr = image.os.sysprep_info(sysprep)
756 display_name = name.replace('-', ' ').capitalize()
757 sysprep_help += "%s\n" % display_name
758 sysprep_help += "%s\n" % ('-' * len(display_name))
759 sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
760 enabled = 1 if sysprep.enabled else 0
761 choices.append((str(index + 1), display_name, enabled))
764 (code, tags) = d.checklist(
765 "Please choose which system preparation tasks you would like to "
766 "run on the image. Press <Help> to see details about the system "
767 "preparation tasks.", title="Run system preparation tasks",
768 choices=choices, width=70, ok_label="Run", help_button=1)
769 tags = map(lambda x: x.strip('"'), tags) # Needed for OpenSUSE
771 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
773 elif code == d.DIALOG_HELP:
774 d.scrollbox(sysprep_help, width=WIDTH)
775 elif code == d.DIALOG_OK:
776 # Enable selected syspreps and disable the rest
777 for i in range(len(syspreps)):
778 if str(i + 1) in tags:
779 image.os.enable_sysprep(syspreps[i])
781 image.os.disable_sysprep(syspreps[i])
783 if len([s for s in image.os.list_syspreps() if s.enabled]) == 0:
784 d.msgbox("No system preperation task is selected!",
785 title="System Preperation", width=SMALL_WIDTH)
788 if not sysprep_params(session):
791 infobox = InfoBoxOutput(d, "Image Configuration")
793 image.out.add(infobox)
795 # The checksum is invalid. We have mounted the image rw
796 if 'checksum' in session:
797 del session['checksum']
799 # Monitor the metadata changes during syspreps
800 with MetadataMonitor(session, image.os.meta):
802 image.os.do_sysprep()
804 except FatalError as e:
805 title = "System Preparation"
806 d.msgbox("System Preparation failed: %s" % e,
807 title=title, width=SMALL_WIDTH)
809 image.out.remove(infobox)
817 """Shrink the image"""
818 d = session['dialog']
819 image = session['image']
821 shrinked = 'shrinked' in session and session['shrinked']
824 d.msgbox("The image is already shrinked!", title="Image Shrinking",
828 msg = "This operation will shrink the last partition of the image to " \
829 "reduce the total image size. If the last partition is a swap " \
830 "partition, then this partition is removed and the partition " \
831 "before that is shrinked. The removed swap partition will be " \
832 "recreated during image deployment."
834 if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH,
835 height=12, title="Image Shrinking"):
836 with MetadataMonitor(session, image.meta):
837 infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
838 image.out.add(infobox)
843 image.out.remove(infobox)
845 session['shrinked'] = True
846 update_background_title(session)
853 def customization_menu(session):
854 """Show image customization menu"""
855 d = session['dialog']
857 choices = [("Sysprep", "Run various image preparation tasks"),
858 ("Shrink", "Shrink image"),
859 ("View/Modify", "View/Modify image properties"),
860 ("Delete", "Delete image properties"),
861 ("Exclude", "Exclude various deployment tasks from running")]
865 actions = {"Sysprep": sysprep,
867 "View/Modify": modify_properties,
868 "Delete": delete_properties,
869 "Exclude": exclude_tasks}
871 (code, choice) = d.menu(
872 text="Choose one of the following or press <Back> to exit.",
873 width=WIDTH, choices=choices, cancel="Back", height=13,
874 menu_height=len(choices), default_item=choices[default_item][0],
875 title="Image Customization Menu")
877 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
879 elif choice in actions:
880 default_item = [entry[0] for entry in choices].index(choice)
881 if actions[choice](session):
882 default_item = (default_item + 1) % len(choices)
885 def main_menu(session):
886 """Show the main menu of the program"""
887 d = session['dialog']
889 update_background_title(session)
891 choices = [("Customize", "Customize image & cloud deployment options"),
892 ("Register", "Register image to a cloud"),
893 ("Extract", "Dump image to local file system"),
894 ("Reset", "Reset everything and start over again"),
895 ("Help", "Get help for using snf-image-creator")]
897 default_item = "Customize"
899 actions = {"Customize": customization_menu, "Register": kamaki_menu,
900 "Extract": extract_image}
902 (code, choice) = d.menu(
903 text="Choose one of the following or press <Exit> to exit.",
904 width=WIDTH, choices=choices, cancel="Exit", height=13,
905 default_item=default_item, menu_height=len(choices),
906 title="Image Creator for synnefo (snf-image-creator version %s)" %
909 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
912 elif choice == "Reset":
914 d.infobox("Resetting snf-image-creator. Please wait ...",
917 elif choice == "Help":
918 d.msgbox("For help, check the online documentation:\n\nhttp://www"
919 ".synnefo.org/docs/snf-image-creator/latest/",
920 width=WIDTH, title="Help")
921 elif choice in actions:
922 actions[choice](session)
924 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :