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