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