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
58 CONFIGURATION_TASKS = [
59 ("Partition table manipulation", ["FixPartitionTable"],
60 ["linux", "windows"]),
61 ("File system resize",
62 ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
63 ["linux", "windows"]),
64 ("Swap partition configuration", ["AddSwap"], ["linux"]),
65 ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
66 ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"], ["windows"]),
67 ("SELinux relabeling at next boot", ["SELinuxAutorelabel"],
69 ("Hostname/Computer Name assignment", ["AssignHostname"],
70 ["windows", "linux"]),
71 ("Password change", ["ChangePassword"], ["windows", "linux"]),
72 ("File injection", ["EnforcePersonality"], ["windows", "linux"])
76 class Reset(Exception):
80 def confirm_exit(d, msg=''):
81 return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
86 "Are you sure you want to reset everything?",
90 def update_background_title(session):
92 dev = session['device']
96 size = (dev.meta['SIZE'] + MB - 1) // MB
97 title = "OS: %s, Distro: %s, Size: %dMB" % (dev.ostype, dev.distro, size)
99 d.setBackgroundTitle(title)
102 def extract_image(session):
103 d = session['dialog']
106 if dir and dir[-1] != os.sep:
109 (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
110 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
113 if os.path.isdir(path):
117 if os.path.isdir("%s.meta" % path):
118 d.msgbox("Can't overwrite directory `%s.meta'" % path,
122 if os.path.isdir("%s.md5sum" % path):
123 d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
127 basedir = os.path.dirname(path)
128 name = os.path.basename(path)
129 if not os.path.exists(basedir):
130 d.msgbox("Directory `%s' does not exist" % basedir,
138 files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
139 overwrite = filter(os.path.exists, files)
141 if len(overwrite) > 0:
142 if d.yesno("The following file(s) exist:\n"
143 "%s\nDo you want to overwrite them?" %
144 "\n".join(overwrite), width=YESNO_WIDTH):
147 out = GaugeOutput(d, "Image Extraction", "Extracting image...")
149 dev = session['device']
150 if "checksum" not in session:
151 size = dev.meta['SIZE']
153 session['checksum'] = md5.compute(session['snapshot'], size)
159 # Extract metadata file
160 out.output("Extracting metadata file...")
161 metastring = '\n'.join(
162 ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
164 with open('%s.meta' % path, 'w') as f:
168 # Extract md5sum file
169 out.output("Extracting md5sum file...")
170 md5str = "%s %s\n" % (session['checksum'], name)
171 with open('%s.md5sum' % path, 'w') as f:
177 d.msgbox("Image file `%s' was successfully extracted!" % path,
184 def upload_image(session):
185 d = session["dialog"]
186 size = session['device'].meta['SIZE']
188 if "account" not in session:
189 d.msgbox("You need to provide your ~okeanos login username before you "
190 "can upload images to pithos+", width=MSGBOX_WIDTH)
193 if "token" not in session:
194 d.msgbox("You need to provide your ~okeanos account authentication "
195 "token before you can upload images to pithos+",
200 init = session["upload"] if "upload" in session else ''
201 (code, answer) = d.inputbox("Please provide a filename:", init=init,
202 width=INPUTBOX_WIDTH)
204 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
207 filename = answer.strip()
208 if len(filename) == 0:
209 d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
214 out = GaugeOutput(d, "Image Upload", "Uploading...")
215 if 'checksum' not in session:
217 session['checksum'] = md5.compute(session['snapshot'], size)
219 kamaki = Kamaki(session['account'], session['token'], out)
222 with open(session['snapshot'], 'rb') as f:
223 session["upload"] = kamaki.upload(f, size, filename,
224 "Calculating block hashes",
225 "Uploading missing blocks")
226 # Upload metadata file
227 out.output("Uploading metadata file...")
228 metastring = '\n'.join(
229 ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
231 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
232 remote_path="%s.meta" % filename)
236 out.output("Uploading md5sum file...")
237 md5str = "%s %s\n" % (session['checksum'], filename)
238 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
239 remote_path="%s.md5sum" % filename)
242 except ClientError as e:
243 d.msgbox("Error in pithos+ client: %s" % e.message,
244 title="Pithos+ Client Error", width=MSGBOX_WIDTH)
245 if 'upload' in session:
246 del session['upload']
251 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
257 def register_image(session):
258 d = session["dialog"]
260 if "account" not in session:
261 d.msgbox("You need to provide your ~okeanos login username before you "
262 "can register an images to cyclades",
266 if "token" not in session:
267 d.msgbox("You need to provide your ~okeanos account authentication "
268 "token before you can register an images to cyclades",
272 if "upload" not in session:
273 d.msgbox("You need to have an image uploaded to pithos+ before you "
274 "can register it to cyclades",
279 (code, answer) = d.inputbox("Please provide a registration name:"
280 " be registered:", width=INPUTBOX_WIDTH)
281 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
284 name = answer.strip()
286 d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
290 out = GaugeOutput(d, "Image Registration", "Registrating image...")
292 out.output("Registring image to cyclades...")
294 kamaki = Kamaki(session['account'], session['token'], out)
295 kamaki.register(name, session['upload'], session['metadata'])
297 except ClientError as e:
298 d.msgbox("Error in pithos+ client: %s" % e.message)
303 d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
304 (session['upload'], name), width=MSGBOX_WIDTH)
308 def kamaki_menu(session):
309 d = session['dialog']
310 default_item = "Account"
312 account = session["account"] if "account" in session else "<none>"
313 token = session["token"] if "token" in session else "<none>"
314 upload = session["upload"] if "upload" in session else "<none>"
316 choices = [("Account", "Change your ~okeanos username: %s" % account),
317 ("Token", "Change your ~okeanos token: %s" % token),
318 ("Upload", "Upload image to pithos+"),
319 ("Register", "Register image to cyclades: %s" % upload)]
321 (code, choice) = d.menu(
322 text="Choose one of the following or press <Back> to go back.",
323 width=MENU_WIDTH, choices=choices, cancel="Back", help_button=1,
324 default_item=default_item, title="Image Registration Menu")
326 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
329 if choice == "Account":
330 default_item = "Account"
331 (code, answer) = d.inputbox(
332 "Please provide your ~okeanos account e-mail address:",
333 init=session["account"] if "account" in session else '',
335 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
337 if len(answer) == 0 and "account" in session:
338 del session["account"]
340 session["account"] = answer.strip()
341 default_item = "Token"
342 elif choice == "Token":
343 default_item = "Token"
344 (code, answer) = d.inputbox(
345 "Please provide your ~okeanos account authetication token:",
346 init=session["token"] if "token" in session else '',
348 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
350 if len(answer) == 0 and "token" in session:
353 session["token"] = answer.strip()
354 default_item = "Upload"
355 elif choice == "Upload":
356 if upload_image(session):
357 default_item = "Register"
359 default_item = "Upload"
360 elif choice == "Register":
361 if register_image(session):
364 default_item = "Register"
367 def add_property(session):
368 d = session['dialog']
371 (code, answer) = d.inputbox("Please provide a name for a new image"
372 " property:", width=INPUTBOX_WIDTH)
373 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
376 name = answer.strip()
378 d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
384 (code, answer) = d.inputbox("Please provide a value for image "
385 "property %s" % name, width=INPUTBOX_WIDTH)
386 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
389 value = answer.strip()
391 d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
396 session['metadata'][name] = value
401 def modify_properties(session):
402 d = session['dialog']
406 for (key, val) in session['metadata'].items():
407 choices.append((str(key), str(val)))
409 (code, choice) = d.menu(
410 "In this menu you can edit existing image properties or add new "
411 "ones. Be carefull! Most properties have special meaning and "
412 "alter the image deployment behaviour. Press <HELP> to see more "
413 "information about image properties. Press <BACK> when done.",
414 height=18, width=MENU_WIDTH, choices=choices, menu_height=10,
415 ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
416 help_button=1, title="Image Metadata")
418 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
421 elif code == d.DIALOG_OK:
422 (code, answer) = d.inputbox("Please provide a new value for "
423 "the image property with name `%s':" % choice,
424 init=session['metadata'][choice], width=INPUTBOX_WIDTH)
425 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
426 value = answer.strip()
428 d.msgbox("Value cannot be empty!")
431 session['metadata'][choice] = value
433 elif code == d.DIALOG_EXTRA:
434 add_property(session)
437 def delete_properties(session):
438 d = session['dialog']
441 for (key, val) in session['metadata'].items():
442 choices.append((key, "%s" % val, 0))
444 (code, to_delete) = d.checklist("Choose which properties to delete:",
445 choices=choices, width=CHECKBOX_WIDTH)
447 # If the user exits with ESC or CANCEL, the returned tag list is empty.
449 del session['metadata'][i]
453 d.msgbox("%d image properties were deleted." % cnt, width=MSGBOX_WIDTH)
456 def exclude_tasks(session):
457 d = session['dialog']
463 if 'excluded_tasks' not in session:
464 session['excluded_tasks'] = []
466 if -1 in session['excluded_tasks']:
467 if not d.yesno("Image deployment configuration is disabled. "
468 "Do you wish to enable it?", width=YESNO_WIDTH):
469 session['excluded_tasks'].remove(-1)
473 for (msg, task, osfamily) in CONFIGURATION_TASKS:
474 if session['metadata']['OSFAMILY'] in osfamily:
475 checked = 1 if index in session['excluded_tasks'] else 0
476 choices.append((str(displayed_index), msg, checked))
477 mapping[displayed_index] = index
482 (code, tags) = d.checklist(
483 text="Please choose which configuration tasks you would like to "
484 "prevent from running during image deployment. "
485 "Press <No Config> to supress any configuration. "
486 "Press <Help> for more help on the image deployment "
487 "configuration tasks.",
488 choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
489 help_button=1, extra_button=1, extra_label="No Config",
490 title="Exclude Configuration Tasks")
492 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
494 elif code == d.DIALOG_HELP:
495 help_file = get_help_file("configuration_tasks")
496 assert os.path.exists(help_file)
497 d.textbox(help_file, title="Configuration Tasks",
500 elif code == d.DIALOG_EXTRA:
501 session['excluded_tasks'] = [-1]
502 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
504 elif code == d.DIALOG_OK:
505 session['excluded_tasks'] = []
507 session['excluded_tasks'].append(mapping[int(tag)])
509 exclude_metadata = []
510 for task in session['excluded_tasks']:
511 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
513 session['task_metadata'] = \
514 map(lambda x: "EXCLUDE_TASK_%s" % x, exclude_metadata)
518 def sysprep(session):
519 d = session['dialog']
520 image_os = session['image_os']
522 wrapper = textwrap.TextWrapper(width=65)
524 help_title = "System Preperation Tasks"
525 sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
527 if 'exec_syspreps' not in session:
528 session['exec_syspreps'] = []
530 all_syspreps = image_os.list_syspreps()
531 # Only give the user the choice between syspreps that have not ran yet
532 syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
537 for sysprep in syspreps:
538 name, descr = image_os.sysprep_info(sysprep)
539 display_name = name.replace('-', ' ').capitalize()
540 sysprep_help += "%s\n" % display_name
541 sysprep_help += "%s\n" % ('-' * len(display_name))
542 sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
543 enabled = 1 if sysprep.enabled else 0
544 choices.append((str(index + 1), display_name, enabled))
547 (code, tags) = d.checklist(
548 "Please choose which system preperation tasks you would like to "
549 "run on the image. Press <Help> to see details about the system "
550 "preperation tasks.", title="Run system preperation tasks",
551 choices=choices, width=70, ok_label="Run", help_button=1)
553 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
555 elif code == d.DIALOG_HELP:
556 d.scrollbox(sysprep_help, width=HELP_WIDTH)
557 elif code == d.DIALOG_OK:
558 # Enable selected syspreps and disable the rest
559 for i in range(len(syspreps)):
560 if str(i + 1) in tags:
561 image_os.enable_sysprep(syspreps[i])
562 session['exec_syspreps'].append(syspreps[i])
564 image_os.disable_sysprep(syspreps[i])
566 out = InfoBoxOutput(d, "Image Configuration")
568 dev = session['device']
570 dev.mount(readonly=False)
572 # The checksum is invalid. We have mounted the image rw
573 if 'checksum' in session:
574 del session['checksum']
577 image_os.do_sysprep()
579 # Disable syspreps that have ran
580 for sysprep in session['exec_syspreps']:
581 image_os.disable_sysprep(sysprep)
583 image_os.out.finalize()
591 def customize_menu(session):
592 d = session['dialog']
594 choices = [("Sysprep", "Run various image preperation tasks"),
595 ("Shrink", "Shrink image"),
596 ("View/Modify", "View/Modify image properties"),
597 ("Delete", "Delete image properties"),
598 ("Exclude", "Exclude various deployment tasks from running")]
600 default_item = "Sysprep"
602 actions = {"Sysprep": sysprep,
603 "View/Modify": modify_properties,
604 "Delete": delete_properties,
605 "Exclude": exclude_tasks}
607 (code, choice) = d.menu(
608 text="Choose one of the following or press <Back> to exit.",
609 width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
610 menu_height=len(choices), default_item=default_item,
611 title="Image Customization Menu")
613 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
615 elif choice in actions:
616 default_item = choice
617 actions[choice](session)
620 def main_menu(session):
621 d = session['dialog']
622 dev = session['device']
624 update_background_title(session)
626 choices = [("Customize", "Customize image & ~okeanos deployment options"),
627 ("Register", "Register image to ~okeanos"),
628 ("Extract", "Dump image to local file system"),
629 ("Reset", "Reset everything and start over again"),
630 ("Help", "Get help for using snf-image-creator")]
632 default_item = "Customize"
634 actions = {"Customize": customize_menu, "Register": kamaki_menu,
635 "Extract": extract_image}
637 (code, choice) = d.menu(
638 text="Choose one of the following or press <Exit> to exit.",
639 width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
640 default_item=default_item, menu_height=len(choices),
641 title="Image Creator for ~okeanos (snf-image-creator version %s)" %
644 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
647 elif choice == "Reset":
649 d.infobox("Resetting snf-image-creator. Please wait...")
651 elif choice in actions:
652 actions[choice](session)
655 def select_file(d, media):
658 if media is not None:
659 if not os.path.exists(media):
660 d.msgbox("The file you choose does not exist",
665 (code, media) = d.fselect(root, 10, 50,
666 title="Please select input media")
667 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
668 if confirm_exit(d, "You canceled the media selection dialog box."):
677 def image_creator(d):
678 basename = os.path.basename(sys.argv[0])
679 usage = "Usage: %s [input_media]" % basename
680 if len(sys.argv) > 2:
681 sys.stderr.write("%s\n" % usage)
684 if os.geteuid() != 0:
685 raise FatalError("You must run %s as root" % basename)
687 media = select_file(d, sys.argv[1] if len(sys.argv) == 2 else None)
689 d.setBackgroundTitle('snf-image-creator')
691 out = GaugeOutput(d, "Initialization", "Initializing...")
692 disk = Disk(media, out)
694 def signal_handler(signum, frame):
698 signal.signal(signal.SIGINT, signal_handler)
700 snapshot = disk.snapshot()
701 dev = disk.get_device(snapshot)
703 out.output("Collecting image metadata...")
705 dev.mount(readonly=True)
706 cls = os_cls(dev.distro, dev.ostype)
707 image_os = cls(dev.root, dev.g, out)
709 metadata.update(image_os.meta)
713 # Make sure the signal handler does not call out.cleanup again
716 out.cleanup = type(GaugeOutput.cleanup)(dummy, out, GaugeOutput)
718 session = {"dialog": d,
720 "snapshot": snapshot,
722 "image_os": image_os,
723 "metadata": metadata}
726 d.infobox("Thank you for using snf-image-creator. Bye", width=53)
735 d = dialog.Dialog(dialog="dialog")
737 # Add extra button in dialog library
738 dialog._common_args_syntax["extra_button"] = \
739 lambda enable: dialog._simple_option("--extra-button", enable)
741 dialog._common_args_syntax["extra_label"] = \
742 lambda string: ("--extra-label", string)
747 ret = image_creator(d)
749 except FatalError as e:
750 msg = textwrap.fill(str(e), width=70)
751 d.infobox(msg, width=70, title="Fatal Error")
756 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :