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
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
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"],
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"])
71 class MetadataMonitor(object):
72 """Monitors image metadata chages"""
73 def __init__(self, session, meta):
74 self.session = session
79 for (k, v) in self.meta.items():
82 def __exit__(self, type, value, traceback):
83 d = self.session['dialog']
88 for (k, v) in self.meta.items():
91 elif self.old[k] != v:
94 if not (len(added) or len(altered)):
97 msg = "The last action has changed some image properties:\n\n"
99 msg += "New image properties:\n"
100 for (k, v) in added.items():
101 msg += ' %s: "%s"\n' % (k, v)
104 msg += "Updated image properties:\n"
105 for (k, v) in altered.items():
106 msg += ' %s: "%s" -> "%s"\n' % (k, self.old[k], v)
109 self.session['metadata'].update(added)
110 self.session['metadata'].update(altered)
111 d.msgbox(msg, title="Image Property Changes", width=SMALL_WIDTH)
114 def upload_image(session):
115 """Upload the image to pithos+"""
116 d = session["dialog"]
117 image = session['image']
118 meta = session['metadata']
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)
127 if 'upload' in session:
128 init = session['upload']
130 init = "%s.diskdump" % meta['OS']
133 (code, answer) = d.inputbox("Please provide a filename:", init=init,
136 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
139 filename = answer.strip()
140 if len(filename) == 0:
141 d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
144 kamaki = Kamaki(session['account'], None)
146 for f in (filename, "%s.md5sum" % filename, "%s.meta" % filename):
147 if kamaki.object_exists(f):
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):
156 session['upload'] = filename
159 gauge = GaugeOutput(d, "Image Upload", "Uploading...")
165 if 'checksum' not in session:
167 session['checksum'] = md5.compute(image.device, size)
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")
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)
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']
194 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
200 def register_image(session):
201 """Register image with cyclades"""
202 d = session["dialog"]
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)
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)
217 (code, answer) = d.inputbox("Please provide a registration name:",
219 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
222 name = answer.strip()
224 d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
227 ret = d.yesno("Make the image public?\\nA public image is accessible "
228 "by every user of the service.", defaultno=1,
230 if ret not in (0, 1):
233 is_public = True if ret == 0 else False
238 metadata.update(session['metadata'])
239 if 'task_metadata' in session:
240 for key in session['task_metadata']:
241 metadata[key] = 'yes'
243 img_type = "public" if is_public else "private"
244 gauge = GaugeOutput(d, "Image Registration", "Registering image...")
246 out = session['image'].out
250 out.output("Registering %s image with Cyclades..." % img_type)
251 kamaki = Kamaki(session['account'], out)
252 kamaki.register(name, session['pithos_uri'], metadata,
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'])
263 out.output("Sharing metadata and md5sum files...")
264 kamaki.share("%s.meta" % session['upload'])
265 kamaki.share("%s.md5sum" % session['upload'])
267 except ClientError as e:
268 d.msgbox("Error in pithos+ client: %s" % e.message)
275 d.msgbox("%s image `%s' was successfully registered with Cyclades as `%s'"
276 % (img_type.title(), session['upload'], name), width=SMALL_WIDTH)
280 def modify_clouds(session):
281 """Modify existing cloud accounts"""
282 d = session['dialog']
285 clouds = Kamaki.get_clouds()
287 if not add_cloud(session):
292 for (name, cloud) in clouds.items():
293 descr = cloud['description'] if 'description' in cloud else ''
294 choices.append((name, descr))
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,
304 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
306 elif code == d.DIALOG_OK: # Edit button
307 edit_cloud(session, choice)
308 elif code == d.DIALOG_EXTRA: # Add button
312 def delete_clouds(session):
313 """Delete existing cloud accounts"""
314 d = session['dialog']
317 for (name, cloud) in Kamaki.get_clouds().items():
318 descr = cloud['description'] if 'description' in cloud else ''
319 choices.append((name, descr, 0))
321 if len(choices) == 0:
322 d.msgbox("No available clouds to delete!", width=SMALL_WIDTH)
325 (code, to_delete) = d.checklist("Choose which cloud accounts to delete:",
326 choices=choices, width=WIDTH)
328 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
331 if not len(to_delete):
332 d.msgbox("Nothing selected!", width=SMALL_WIDTH)
335 if not d.yesno("Are you sure you want to remove the selected cloud "
336 "accounts?", width=WIDTH, defaultno=1):
338 Kamaki.remove_cloud(i)
339 if 'cloud' in session and session['cloud'] == i:
341 if 'account' in session:
342 del session['account']
346 d.msgbox("%d cloud accounts were deleted." % len(to_delete),
351 def kamaki_menu(session):
352 """Show kamaki related actions"""
353 d = session['dialog']
354 default_item = "Cloud"
356 if 'cloud' not in session:
357 cloud = Kamaki.get_default_cloud_name()
359 session['cloud'] = cloud
360 session['account'] = Kamaki.get_account(cloud)
361 if not session['account']:
362 del session['account']
364 default_item = "Add/Edit"
367 cloud = session["cloud"] if "cloud" in session else "<none>"
368 if 'account' not in session and 'cloud' in session:
369 cloud += " <invalid>"
371 upload = session["upload"] if "upload" in session else "<none>"
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)]
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")
385 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
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"
396 default_time = "Add/Edit"
398 default_time = "Delete"
399 elif choice == "Cloud":
400 default_item = "Cloud"
401 clouds = Kamaki.get_clouds()
403 d.msgbox("No clouds available. Please add a new cloud!",
405 default_item = "Add/Edit"
408 if 'cloud' not in session:
409 session['cloud'] = clouds.keys()[0]
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))
417 (code, answer) = d.radiolist("Please select a cloud:",
418 width=WIDTH, choices=choices)
419 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
422 session['account'] = Kamaki.get_account(answer)
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)
431 if session['account'] is not None:
432 session['cloud'] = answer
433 Kamaki.set_default_cloud(answer)
434 default_item = "Upload"
436 del session['account']
438 elif choice == "Upload":
439 if upload_image(session):
440 default_item = "Register"
442 default_item = "Upload"
443 elif choice == "Register":
444 if register_image(session):
447 default_item = "Register"
450 def add_property(session):
451 """Add a new property to the image"""
452 d = session['dialog']
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):
460 name = answer.strip()
462 d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
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):
473 value = answer.strip()
475 d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
480 session['metadata'][name] = value
485 def modify_properties(session):
486 """Modify an existing image property"""
487 d = session['dialog']
491 for (key, val) in session['metadata'].items():
492 choices.append((str(key), str(val)))
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")
503 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
506 elif code == d.DIALOG_OK:
507 (code, answer) = d.inputbox("Please provide a new value for the "
508 "image property with name `%s':" %
510 init=session['metadata'][choice],
512 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
513 value = answer.strip()
515 d.msgbox("Value cannot be empty!")
518 session['metadata'][choice] = value
520 elif code == d.DIALOG_EXTRA:
521 add_property(session)
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)
528 def delete_properties(session):
529 """Delete an image property"""
530 d = session['dialog']
533 for (key, val) in session['metadata'].items():
534 choices.append((key, "%s" % val, 0))
536 (code, to_delete) = d.checklist("Choose which properties to delete:",
537 choices=choices, width=WIDTH)
539 # If the user exits with ESC or CANCEL, the returned tag list is empty.
541 del session['metadata'][i]
545 d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
551 def exclude_tasks(session):
552 """Exclude specific tasks from running during image deployment"""
553 d = session['dialog']
559 if 'excluded_tasks' not in session:
560 session['excluded_tasks'] = []
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)
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
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")
588 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
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",
596 elif code == d.DIALOG_EXTRA:
597 session['excluded_tasks'] = [-1]
598 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
600 elif code == d.DIALOG_OK:
601 session['excluded_tasks'] = []
603 session['excluded_tasks'].append(mapping[int(tag)])
605 exclude_metadata = []
606 for task in session['excluded_tasks']:
607 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
609 session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
616 def sysprep(session):
617 """Perform various system preperation tasks on the image"""
618 d = session['dialog']
619 image = session['image']
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."
626 if d.yesno("%s\n\nDo you really want to continue?" % msg,
627 width=SMALL_WIDTH, defaultno=1):
630 wrapper = textwrap.TextWrapper(width=WIDTH - 5)
632 help_title = "System Preperation Tasks"
633 sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
635 syspreps = image.os.list_syspreps()
637 if len(syspreps) == 0:
638 d.msgbox("No system preparation task available to run!",
639 title="System Preperation", width=SMALL_WIDTH)
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))
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)
661 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
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])
671 image.os.disable_sysprep(syspreps[i])
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)
678 infobox = InfoBoxOutput(d, "Image Configuration")
680 image.out.add(infobox)
682 # The checksum is invalid. We have mounted the image rw
683 if 'checksum' in session:
684 del session['checksum']
686 # Monitor the metadata changes during syspreps
687 with MetadataMonitor(session, image.os.meta):
689 image.os.do_sysprep()
691 except FatalError as e:
692 title = "System Preparation"
693 d.msgbox("System Preparation failed: %s" % e,
694 title=title, width=SMALL_WIDTH)
696 image.out.remove(infobox)
704 """Shrink the image"""
705 d = session['dialog']
706 image = session['image']
708 shrinked = 'shrinked' in session and session['shrinked']
711 d.msgbox("The image is already shrinked!", title="Image Shrinking",
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."
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)
730 image.out.remove(infobox)
732 session['shrinked'] = True
733 update_background_title(session)
740 def customization_menu(session):
741 """Show image customization menu"""
742 d = session['dialog']
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")]
752 actions = {"Sysprep": sysprep,
754 "View/Modify": modify_properties,
755 "Delete": delete_properties,
756 "Exclude": exclude_tasks}
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")
764 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
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)
772 def main_menu(session):
773 """Show the main menu of the program"""
774 d = session['dialog']
776 update_background_title(session)
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")]
784 default_item = "Customize"
786 actions = {"Customize": customization_menu, "Register": kamaki_menu,
787 "Extract": extract_image}
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)" %
796 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
799 elif choice == "Reset":
801 d.infobox("Resetting snf-image-creator. Please wait...",
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)
811 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :