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.
43 from image_creator import __version__ as version
44 from image_creator.util import FatalError, MD5
45 from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
46 from image_creator.disk import Disk
47 from image_creator.os_type import os_cls
48 from image_creator.kamaki_wrapper import Kamaki, ClientError
49 from image_creator.help import get_help_file
59 CONFIGURATION_TASKS = [
60 ("Partition table manipulation", ["FixPartitionTable"],
61 ["linux", "windows"]),
62 ("File system resize",
63 ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
64 ["linux", "windows"]),
65 ("Swap partition configuration", ["AddSwap"], ["linux"]),
66 ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
67 ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
69 ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
70 ("Hostname/Computer Name assignment", ["AssignHostname"],
71 ["windows", "linux"]),
72 ("Password change", ["ChangePassword"], ["windows", "linux"]),
73 ("File injection", ["EnforcePersonality"], ["windows", "linux"])
77 class Reset(Exception):
81 class metadata_monitor(object):
82 def __init__(self, session, meta):
83 self.session = session
88 for (k, v) in self.meta.items():
91 def __exit__(self, type, value, traceback):
92 d = self.session['dialog']
97 for (k, v) in self.meta.items():
100 elif self.old[k] != v:
103 if not (len(added) or len(altered)):
106 msg = "The last action has changed some image properties:\n\n"
108 msg += "New image properties:\n"
109 for (k, v) in added.items():
110 msg += ' %s: "%s"\n' % (k, v)
113 msg += "Updated image properties:\n"
114 for (k, v) in altered.items():
115 msg += ' %s: "%s" -> "%s"\n' % (k, self.old[k], v)
118 self.session['metadata'].update(added)
119 self.session['metadata'].update(altered)
120 d.msgbox(msg, title="Image Property Changes", width=MSGBOX_WIDTH)
123 def extract_metadata_string(session):
124 metadata = ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()]
126 if 'task_metadata' in session:
127 metadata.extend("%s=yes" % m for m in session['task_metadata'])
129 return '\n'.join(metadata) + '\n'
132 def confirm_exit(d, msg=''):
133 return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
136 def confirm_reset(d):
137 return not d.yesno("Are you sure you want to reset everything?",
138 width=YESNO_WIDTH, defaultno=1)
141 def update_background_title(session):
142 d = session['dialog']
143 dev = session['device']
147 size = (dev.meta['SIZE'] + MB - 1) // MB
148 shrinked = 'shrinked' in session and session['shrinked']
149 postfix = " (shrinked)" if shrinked else ''
151 title = "OS: %s, Distro: %s, Size: %dMB%s" % \
152 (dev.ostype, dev.distro, size, postfix)
154 d.setBackgroundTitle(title)
157 def extract_image(session):
158 d = session['dialog']
161 if dir and dir[-1] != os.sep:
164 (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
165 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
168 if os.path.isdir(path):
172 if os.path.isdir("%s.meta" % path):
173 d.msgbox("Can't overwrite directory `%s.meta'" % path,
177 if os.path.isdir("%s.md5sum" % path):
178 d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
182 basedir = os.path.dirname(path)
183 name = os.path.basename(path)
184 if not os.path.exists(basedir):
185 d.msgbox("Directory `%s' does not exist" % basedir,
193 files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
194 overwrite = filter(os.path.exists, files)
196 if len(overwrite) > 0:
197 if d.yesno("The following file(s) exist:\n"
198 "%s\nDo you want to overwrite them?" %
199 "\n".join(overwrite), width=YESNO_WIDTH):
202 out = GaugeOutput(d, "Image Extraction", "Extracting image...")
204 dev = session['device']
205 if "checksum" not in session:
206 size = dev.meta['SIZE']
208 session['checksum'] = md5.compute(session['snapshot'], size)
214 # Extract metadata file
215 out.output("Extracting metadata file...")
216 with open('%s.meta' % path, 'w') as f:
217 f.write(extract_metadata_string(session))
220 # Extract md5sum file
221 out.output("Extracting md5sum file...")
222 md5str = "%s %s\n" % (session['checksum'], name)
223 with open('%s.md5sum' % path, 'w') as f:
229 d.msgbox("Image file `%s' was successfully extracted!" % path,
236 def upload_image(session):
237 d = session["dialog"]
238 size = session['device'].meta['SIZE']
240 if "account" not in session:
241 d.msgbox("You need to provide your ~okeanos login username before you "
242 "can upload images to pithos+", width=MSGBOX_WIDTH)
245 if "token" not in session:
246 d.msgbox("You need to provide your ~okeanos account authentication "
247 "token before you can upload images to pithos+",
252 init = session["upload"] if "upload" in session else ''
253 (code, answer) = d.inputbox("Please provide a filename:", init=init,
254 width=INPUTBOX_WIDTH)
256 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
259 filename = answer.strip()
260 if len(filename) == 0:
261 d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
266 out = GaugeOutput(d, "Image Upload", "Uploading...")
267 if 'checksum' not in session:
269 session['checksum'] = md5.compute(session['snapshot'], size)
271 kamaki = Kamaki(session['account'], session['token'], out)
274 with open(session['snapshot'], 'rb') as f:
275 session["upload"] = kamaki.upload(f, size, filename,
276 "Calculating block hashes",
277 "Uploading missing blocks")
278 # Upload metadata file
279 out.output("Uploading metadata file...")
280 metastring = extract_metadata_string(session)
281 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
282 remote_path="%s.meta" % filename)
286 out.output("Uploading md5sum file...")
287 md5str = "%s %s\n" % (session['checksum'], filename)
288 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
289 remote_path="%s.md5sum" % filename)
292 except ClientError as e:
293 d.msgbox("Error in pithos+ client: %s" % e.message,
294 title="Pithos+ Client Error", width=MSGBOX_WIDTH)
295 if 'upload' in session:
296 del session['upload']
301 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
307 def register_image(session):
308 d = session["dialog"]
310 if "account" not in session:
311 d.msgbox("You need to provide your ~okeanos login username before you "
312 "can register an images to cyclades",
316 if "token" not in session:
317 d.msgbox("You need to provide your ~okeanos account authentication "
318 "token before you can register an images to cyclades",
322 if "upload" not in session:
323 d.msgbox("You need to upload the image to pithos+ before you can "
324 "register it to cyclades", width=MSGBOX_WIDTH)
328 (code, answer) = d.inputbox("Please provide a registration name:",
329 width=INPUTBOX_WIDTH)
330 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
333 name = answer.strip()
335 d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
340 metadata.update(session['metadata'])
341 if 'task_metadata' in session:
342 for key in session['task_metadata']:
343 metadata[key] = 'yes'
345 out = GaugeOutput(d, "Image Registration", "Registrating image...")
347 out.output("Registring image to cyclades...")
349 kamaki = Kamaki(session['account'], session['token'], out)
350 kamaki.register(name, session['upload'], metadata)
352 except ClientError as e:
353 d.msgbox("Error in pithos+ client: %s" % e.message)
358 d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
359 (session['upload'], name), width=MSGBOX_WIDTH)
363 def kamaki_menu(session):
364 d = session['dialog']
365 default_item = "Account"
367 account = session["account"] if "account" in session else "<none>"
368 token = session["token"] if "token" in session else "<none>"
369 upload = session["upload"] if "upload" in session else "<none>"
371 choices = [("Account", "Change your ~okeanos username: %s" % account),
372 ("Token", "Change your ~okeanos token: %s" % token),
373 ("Upload", "Upload image to pithos+"),
374 ("Register", "Register the image to cyclades: %s" % upload)]
376 (code, choice) = d.menu(
377 text="Choose one of the following or press <Back> to go back.",
378 width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
379 menu_height=5, default_item=default_item,
380 title="Image Registration Menu")
382 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
385 if choice == "Account":
386 default_item = "Account"
387 (code, answer) = d.inputbox(
388 "Please provide your ~okeanos account e-mail address:",
389 init=session["account"] if "account" in session else '',
391 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
393 if len(answer) == 0 and "account" in session:
394 del session["account"]
396 session["account"] = answer.strip()
397 default_item = "Token"
398 elif choice == "Token":
399 default_item = "Token"
400 (code, answer) = d.inputbox(
401 "Please provide your ~okeanos account authetication token:",
402 init=session["token"] if "token" in session else '',
404 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
406 if len(answer) == 0 and "token" in session:
409 session["token"] = answer.strip()
410 default_item = "Upload"
411 elif choice == "Upload":
412 if upload_image(session):
413 default_item = "Register"
415 default_item = "Upload"
416 elif choice == "Register":
417 if register_image(session):
420 default_item = "Register"
423 def add_property(session):
424 d = session['dialog']
427 (code, answer) = d.inputbox("Please provide a name for a new image"
428 " property:", width=INPUTBOX_WIDTH)
429 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
432 name = answer.strip()
434 d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
440 (code, answer) = d.inputbox("Please provide a value for image "
441 "property %s" % name, width=INPUTBOX_WIDTH)
442 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
445 value = answer.strip()
447 d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
452 session['metadata'][name] = value
457 def modify_properties(session):
458 d = session['dialog']
462 for (key, val) in session['metadata'].items():
463 choices.append((str(key), str(val)))
465 (code, choice) = d.menu(
466 "In this menu you can edit existing image properties or add new "
467 "ones. Be careful! Most properties have special meaning and "
468 "alter the image deployment behaviour. Press <HELP> to see more "
469 "information about image properties. Press <BACK> when done.",
470 height=18, width=MENU_WIDTH, choices=choices, menu_height=10,
471 ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
472 help_button=1, title="Image Properties")
474 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
477 elif code == d.DIALOG_OK:
478 (code, answer) = d.inputbox("Please provide a new value for the "
479 "image property with name `%s':" %
481 init=session['metadata'][choice],
482 width=INPUTBOX_WIDTH)
483 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
484 value = answer.strip()
486 d.msgbox("Value cannot be empty!")
489 session['metadata'][choice] = value
491 elif code == d.DIALOG_EXTRA:
492 add_property(session)
494 help_file = get_help_file("image_properties")
495 assert os.path.exists(help_file)
496 d.textbox(help_file, title="Image Properties", width=70, height=40)
499 def delete_properties(session):
500 d = session['dialog']
503 for (key, val) in session['metadata'].items():
504 choices.append((key, "%s" % val, 0))
506 (code, to_delete) = d.checklist("Choose which properties to delete:",
507 choices=choices, width=CHECKBOX_WIDTH)
509 # If the user exits with ESC or CANCEL, the returned tag list is empty.
511 del session['metadata'][i]
515 d.msgbox("%d image properties were deleted." % cnt, width=MSGBOX_WIDTH)
521 def exclude_tasks(session):
522 d = session['dialog']
528 if 'excluded_tasks' not in session:
529 session['excluded_tasks'] = []
531 if -1 in session['excluded_tasks']:
532 if not d.yesno("Image deployment configuration is disabled. "
533 "Do you wish to enable it?", width=YESNO_WIDTH):
534 session['excluded_tasks'].remove(-1)
538 for (msg, task, osfamily) in CONFIGURATION_TASKS:
539 if session['metadata']['OSFAMILY'] in osfamily:
540 checked = 1 if index in session['excluded_tasks'] else 0
541 choices.append((str(displayed_index), msg, checked))
542 mapping[displayed_index] = index
547 (code, tags) = d.checklist(
548 text="Please choose which configuration tasks you would like to "
549 "prevent from running during image deployment. "
550 "Press <No Config> to supress any configuration. "
551 "Press <Help> for more help on the image deployment "
552 "configuration tasks.",
553 choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
554 help_button=1, extra_button=1, extra_label="No Config",
555 title="Exclude Configuration Tasks")
557 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
559 elif code == d.DIALOG_HELP:
560 help_file = get_help_file("configuration_tasks")
561 assert os.path.exists(help_file)
562 d.textbox(help_file, title="Configuration Tasks",
565 elif code == d.DIALOG_EXTRA:
566 session['excluded_tasks'] = [-1]
567 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
569 elif code == d.DIALOG_OK:
570 session['excluded_tasks'] = []
572 session['excluded_tasks'].append(mapping[int(tag)])
574 exclude_metadata = []
575 for task in session['excluded_tasks']:
576 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
578 session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
585 def sysprep(session):
586 d = session['dialog']
587 image_os = session['image_os']
589 # Is the image already shrinked?
590 if 'shrinked' in session and session['shrinked']:
591 msg = "It seems you have shrinked the image. Running system " \
592 "preparation tasks on a shrinked image is dangerous."
594 if d.yesno("%s\n\nDo you really want to continue?" % msg,
595 width=YESNO_WIDTH, defaultno=1):
598 wrapper = textwrap.TextWrapper(width=65)
600 help_title = "System Preperation Tasks"
601 sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
603 if 'exec_syspreps' not in session:
604 session['exec_syspreps'] = []
606 all_syspreps = image_os.list_syspreps()
607 # Only give the user the choice between syspreps that have not ran yet
608 syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
610 if len(syspreps) == 0:
611 d.msgbox("No system preparation task available to run!", title="System Preperation", width=MSGBOX_WIDTH)
617 for sysprep in syspreps:
618 name, descr = image_os.sysprep_info(sysprep)
619 display_name = name.replace('-', ' ').capitalize()
620 sysprep_help += "%s\n" % display_name
621 sysprep_help += "%s\n" % ('-' * len(display_name))
622 sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
623 enabled = 1 if sysprep.enabled else 0
624 choices.append((str(index + 1), display_name, enabled))
627 (code, tags) = d.checklist(
628 "Please choose which system preperation tasks you would like to "
629 "run on the image. Press <Help> to see details about the system "
630 "preperation tasks.", title="Run system preperation tasks",
631 choices=choices, width=70, ok_label="Run", help_button=1)
633 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
635 elif code == d.DIALOG_HELP:
636 d.scrollbox(sysprep_help, width=HELP_WIDTH)
637 elif code == d.DIALOG_OK:
638 # Enable selected syspreps and disable the rest
639 for i in range(len(syspreps)):
640 if str(i + 1) in tags:
641 image_os.enable_sysprep(syspreps[i])
642 session['exec_syspreps'].append(syspreps[i])
644 image_os.disable_sysprep(syspreps[i])
646 out = InfoBoxOutput(d, "Image Configuration")
648 dev = session['device']
650 dev.mount(readonly=False)
652 # The checksum is invalid. We have mounted the image rw
653 if 'checksum' in session:
654 del session['checksum']
656 # Monitor the metadata changes during syspreps
657 with metadata_monitor(session, image_os.meta):
659 image_os.do_sysprep()
660 image_os.out.finalize()
662 # Disable syspreps that have ran
663 for sysprep in session['exec_syspreps']:
664 image_os.disable_sysprep(sysprep)
675 d = session['dialog']
676 dev = session['device']
678 shrinked = 'shrinked' in session and session['shrinked']
681 d.msgbox("The image is already shrinked!", title="Image Shrinking",
685 msg = "This operation will shrink the last partition of the image to " \
686 "reduce the total image size. If the last partition is a swap " \
687 "partition, then this partition is removed and the partition " \
688 "before that is shrinked. The removed swap partition will be " \
689 "recreated during image deployment."
691 if not d.yesno("%s\n\nDo you want to continue?" % msg, width=70,
692 height=12, title="Image Shrinking"):
693 with metadata_monitor(session, dev.meta):
694 dev.out = InfoBoxOutput(d, "Image Shrinking", height=4)
698 session['shrinked'] = True
699 update_background_title(session)
706 def customization_menu(session):
707 d = session['dialog']
709 choices = [("Sysprep", "Run various image preperation tasks"),
710 ("Shrink", "Shrink image"),
711 ("View/Modify", "View/Modify image properties"),
712 ("Delete", "Delete image properties"),
713 ("Exclude", "Exclude various deployment tasks from running")]
717 actions = {"Sysprep": sysprep,
719 "View/Modify": modify_properties,
720 "Delete": delete_properties,
721 "Exclude": exclude_tasks}
723 (code, choice) = d.menu(
724 text="Choose one of the following or press <Back> to exit.",
725 width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
726 menu_height=len(choices), default_item=choices[default_item][0],
727 title="Image Customization Menu")
729 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
731 elif choice in actions:
732 default_item = [entry[0] for entry in choices].index(choice)
733 if actions[choice](session):
734 default_item = (default_item + 1) % len(choices)
737 def main_menu(session):
738 d = session['dialog']
739 dev = session['device']
741 update_background_title(session)
743 choices = [("Customize", "Customize image & ~okeanos deployment options"),
744 ("Register", "Register image to ~okeanos"),
745 ("Extract", "Dump image to local file system"),
746 ("Reset", "Reset everything and start over again"),
747 ("Help", "Get help for using snf-image-creator")]
749 default_item = "Customize"
751 actions = {"Customize": customization_menu, "Register": kamaki_menu,
752 "Extract": extract_image}
754 (code, choice) = d.menu(
755 text="Choose one of the following or press <Exit> to exit.",
756 width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
757 default_item=default_item, menu_height=len(choices),
758 title="Image Creator for ~okeanos (snf-image-creator version %s)" %
761 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
764 elif choice == "Reset":
766 d.infobox("Resetting snf-image-creator. Please wait...",
769 elif choice in actions:
770 actions[choice](session)
773 def select_file(d, media):
776 if media is not None:
777 if not os.path.exists(media):
778 d.msgbox("The file you choose does not exist",
783 (code, media) = d.fselect(root, 10, 50,
784 title="Please select input media")
785 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
786 if confirm_exit(d, "You canceled the media selection dialog box."):
795 def image_creator(d):
796 basename = os.path.basename(sys.argv[0])
797 usage = "Usage: %s [input_media]" % basename
798 if len(sys.argv) > 2:
799 sys.stderr.write("%s\n" % usage)
802 d.setBackgroundTitle('snf-image-creator')
804 if os.geteuid() != 0:
805 raise FatalError("You must run %s as root" % basename)
807 media = select_file(d, sys.argv[1] if len(sys.argv) == 2 else None)
809 out = GaugeOutput(d, "Initialization", "Initializing...")
810 disk = Disk(media, out)
812 def signal_handler(signum, frame):
816 signal.signal(signal.SIGINT, signal_handler)
818 snapshot = disk.snapshot()
819 dev = disk.get_device(snapshot)
822 for (key, value) in dev.meta.items():
823 metadata[str(key)] = str(value)
825 dev.mount(readonly=True)
826 out.output("Collecting image metadata...")
827 cls = os_cls(dev.distro, dev.ostype)
828 image_os = cls(dev.root, dev.g, out)
831 for (key, value) in image_os.meta.items():
832 metadata[str(key)] = str(value)
837 # Make sure the signal handler does not call out.cleanup again
840 out.cleanup = type(GaugeOutput.cleanup)(dummy, out, GaugeOutput)
842 session = {"dialog": d,
844 "snapshot": snapshot,
846 "image_os": image_os,
847 "metadata": metadata}
850 d.infobox("Thank you for using snf-image-creator. Bye", width=53)
859 d = dialog.Dialog(dialog="dialog")
861 # Add extra button in dialog library
862 dialog._common_args_syntax["extra_button"] = \
863 lambda enable: dialog._simple_option("--extra-button", enable)
865 dialog._common_args_syntax["extra_label"] = \
866 lambda string: ("--extra-label", string)
871 ret = image_creator(d)
873 except FatalError as e:
874 msg = textwrap.fill(str(e), width=70)
875 d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
880 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :