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 InitializationOutput, GaugeOutput
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
57 CONFIGURATION_TASKS = [
58 ("Partition table manipulation", ["FixPartitionTable"],
59 ["linux", "windows"]),
60 ("File system resize",
61 ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
62 ["linux", "windows"]),
63 ("Swap partition configuration", ["AddSwap"], ["linux"]),
64 ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
65 ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"], ["windows"]),
66 ("SELinux relabeling at next boot", ["SELinuxAutorelabel"],
68 ("Hostname/Computer Name assignment", ["AssignHostname"],
69 ["windows", "linux"]),
70 ("Password change", ["ChangePassword"], ["windows", "linux"]),
71 ("File injection", ["EnforcePersonality"], ["windows", "linux"])
75 class Reset(Exception):
79 def confirm_exit(d, msg=''):
80 return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
85 "Are you sure you want to reset everything?",
89 def extract_image(session):
93 if dir and dir[-1] != os.sep:
96 (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
97 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
100 if os.path.isdir(path):
104 if os.path.isdir("%s.meta" % path):
105 d.msgbox("Can't overwrite directory `%s.meta'" % path,
109 if os.path.isdir("%s.md5sum" % path):
110 d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
114 basedir = os.path.dirname(path)
115 name = os.path.basename(path)
116 if not os.path.exists(basedir):
117 d.msgbox("Directory `%s' does not exist" % basedir,
125 files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
126 overwrite = filter(os.path.exists, files)
128 if len(overwrite) > 0:
129 if d.yesno("The following file(s) exist:\n"
130 "%s\nDo you want to overwrite them?" %
131 "\n".join(overwrite), width=YESNO_WIDTH):
134 out = GaugeOutput(d, "Image Extraction", "Extracting image...")
136 dev = session['device']
137 if "checksum" not in session:
138 size = dev.meta['SIZE']
140 session['checksum'] = md5.compute(session['snapshot'], size)
146 # Extract metadata file
147 out.output("Extracting metadata file...")
148 metastring = '\n'.join(
149 ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
151 with open('%s.meta' % path, 'w') as f:
155 # Extract md5sum file
156 out.output("Extracting md5sum file...")
157 md5str = "%s %s\n" % (session['checksum'], name)
158 with open('%s.md5sum' % path, 'w') as f:
164 d.msgbox("Image file `%s' was successfully extracted!" % path,
171 def upload_image(session):
172 d = session["dialog"]
173 size = session['device'].meta['SIZE']
175 if "account" not in session:
176 d.msgbox("You need to provide your ~okeanos login username before you "
177 "can upload images to pithos+", width=MSGBOX_WIDTH)
180 if "token" not in session:
181 d.msgbox("You need to provide your ~okeanos account authentication "
182 "token before you can upload images to pithos+",
187 init = session["upload"] if "upload" in session else ''
188 (code, answer) = d.inputbox("Please provide a filename:", init=init,
189 width=INPUTBOX_WIDTH)
191 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
194 filename = answer.strip()
195 if len(filename) == 0:
196 d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
201 out = GaugeOutput(d, "Image Upload", "Uploading...")
202 if 'checksum' not in session:
204 session['checksum'] = md5.compute(session['snapshot'], size)
206 kamaki = Kamaki(session['account'], session['token'], out)
209 with open(session['snapshot'], 'rb') as f:
210 session["upload"] = kamaki.upload(f, size, filename,
211 "Calculating block hashes",
212 "Uploading missing blocks")
213 # Upload metadata file
214 out.output("Uploading metadata file...")
215 metastring = '\n'.join(
216 ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
218 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
219 remote_path="%s.meta" % filename)
223 out.output("Uploading md5sum file...")
224 md5str = "%s %s\n" % (session['checksum'], filename)
225 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
226 remote_path="%s.md5sum" % filename)
229 except ClientError as e:
230 d.msgbox("Error in pithos+ client: %s" % e.message,
231 title="Pithos+ Client Error", width=MSGBOX_WIDTH)
232 if 'upload' in session:
233 del session['upload']
238 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
244 def register_image(session):
245 d = session["dialog"]
247 if "account" not in session:
248 d.msgbox("You need to provide your ~okeanos login username before you "
249 "can register an images to cyclades",
253 if "token" not in session:
254 d.msgbox("You need to provide your ~okeanos account authentication "
255 "token before you can register an images to cyclades",
259 if "upload" not in session:
260 d.msgbox("You need to have an image uploaded to pithos+ before you "
261 "can register it to cyclades",
266 (code, answer) = d.inputbox("Please provide a registration name:"
267 " be registered:", width=INPUTBOX_WIDTH)
268 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
271 name = answer.strip()
273 d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
277 out = GaugeOutput(d, "Image Registration", "Registrating image...")
279 out.output("Registring image to cyclades...")
281 kamaki = Kamaki(session['account'], session['token'], out)
282 kamaki.register(name, session['upload'], session['metadata'])
284 except ClientError as e:
285 d.msgbox("Error in pithos+ client: %s" % e.message)
290 d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
291 (session['upload'], name), width=MSGBOX_WIDTH)
295 def kamaki_menu(session):
296 d = session['dialog']
297 default_item = "Account"
299 account = session["account"] if "account" in session else "<none>"
300 token = session["token"] if "token" in session else "<none>"
301 upload = session["upload"] if "upload" in session else "<none>"
302 (code, choice) = d.menu(
303 "Choose one of the following or press <Back> to go back.",
305 choices=[("Account", "Change your ~okeanos username: %s" %
307 ("Token", "Change your ~okeanos token: %s" % token),
308 ("Upload", "Upload image to pithos+"),
309 ("Register", "Register image to cyclades: %s" % upload)],
311 default_item=default_item,
313 title="Image Registration Menu")
315 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
318 if choice == "Account":
319 default_item = "Account"
320 (code, answer) = d.inputbox(
321 "Please provide your ~okeanos account e-mail address:",
322 init=session["account"] if "account" in session else '',
324 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
326 if len(answer) == 0 and "account" in session:
327 del session["account"]
329 session["account"] = answer.strip()
330 default_item = "Token"
331 elif choice == "Token":
332 default_item = "Token"
333 (code, answer) = d.inputbox(
334 "Please provide your ~okeanos account authetication token:",
335 init=session["token"] if "token" in session else '',
337 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
339 if len(answer) == 0 and "token" in session:
342 session["token"] = answer.strip()
343 default_item = "Upload"
344 elif choice == "Upload":
345 if upload_image(session):
346 default_item = "Register"
348 default_item = "Upload"
349 elif choice == "Register":
350 if register_image(session):
353 default_item = "Register"
356 def add_property(session):
357 d = session['dialog']
360 (code, answer) = d.inputbox("Please provide a name for a new image"
361 " property:", width=INPUTBOX_WIDTH)
362 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
365 name = answer.strip()
367 d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
373 (code, answer) = d.inputbox("Please provide a value for image "
374 "property %s" % name, width=INPUTBOX_WIDTH)
375 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
378 value = answer.strip()
380 d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
385 session['metadata'][name] = value
390 def modify_properties(session):
391 d = session['dialog']
395 for (key, val) in session['metadata'].items():
396 choices.append((str(key), str(val)))
398 (code, choice) = d.menu(
399 "In this menu you can edit existing image properties or add new "
400 "ones. Be carefull! Most properties have special meaning and "
401 "alter the image deployment behaviour. Press <HELP> to see more "
402 "information about image properties. Press <BACK> when done.",
405 choices=choices, menu_height=10,
406 ok_label="EDIT", extra_button=1, extra_label="ADD", cancel="BACK",
407 help_button=1, help_label="HELP", title="Image Metadata")
409 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
412 elif code == d.DIALOG_OK:
413 (code, answer) = d.inputbox("Please provide a new value for "
414 "the image property with name `%s':" % choice,
415 init=session['metadata'][choice], width=INPUTBOX_WIDTH)
416 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
417 value = answer.strip()
419 d.msgbox("Value cannot be empty!")
422 session['metadata'][choice] = value
424 elif code == d.DIALOG_EXTRA:
425 add_property(session)
428 def delete_properties(session):
429 d = session['dialog']
432 for (key, val) in session['metadata'].items():
433 choices.append((key, "%s" % val, 0))
435 (code, to_delete) = d.checklist("Choose which properties to delete:",
436 choices=choices, width=CHECKBOX_WIDTH)
437 count = len(to_delete)
438 # If the user exits with ESC or CANCEL, the returned tag list is empty.
440 del session['metadata'][i]
443 d.msgbox("%d image properties were deleted.", width=MSGBOX_WIDTH)
446 def exclude_tasks(session):
447 d = session['dialog']
453 if 'excluded_tasks' not in session:
454 session['excluded_tasks'] = []
456 if -1 in session['excluded_tasks']:
457 if not d.yesno("Image deployment configuration is disabled. "
458 "Do you wish to enable it?", width=YESNO_WIDTH):
459 session['excluded_tasks'].remove(-1)
463 for (msg, task, osfamily) in CONFIGURATION_TASKS:
464 if session['metadata']['OSFAMILY'] in osfamily:
465 checked = 1 if index in session['excluded_tasks'] else 0
466 choices.append((str(displayed_index), msg, checked))
467 mapping[displayed_index] = index
472 (code, tags) = d.checklist(
473 "Please choose which configuration tasks you would like to "
474 "prevent from running during image deployment. "
475 "Press <No Config> to supress any configuration. "
476 "Press <Help> for more help on the image deployment configuration "
477 "tasks.", height=19, list_height=8,
478 title="Exclude Configuration Tasks", choices=choices,
479 width=CHECKBOX_WIDTH, help_button=1, extra_button=1,
480 extra_label="No Config")
482 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
484 elif code == d.DIALOG_HELP:
485 help_file = get_help_file("configuration_tasks")
486 assert os.path.exists(help_file)
487 d.textbox(help_file, title="Configuration Tasks",
490 elif code == d.DIALOG_EXTRA:
491 session['excluded_tasks'] = [-1]
492 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
494 elif code == d.DIALOG_OK:
495 session['excluded_tasks'] = []
497 session['excluded_tasks'].append(mapping[int(tag)])
499 exclude_metadata = []
500 for task in session['excluded_tasks']:
501 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
503 session['task_metadata'] = \
504 map(lambda x: "EXCLUDE_TASK_%s" % x, exclude_metadata)
508 def sysprep(session):
509 d = session['dialog']
510 image_os = session['image_os']
512 syspreps = image_os.list_syspreps()
514 wrapper = textwrap.TextWrapper()
516 sysprep_help = "System Preperation Tasks"
517 sysprep_help += "\n%s\n\n" % ('=' * len(sysprep_help))
522 for sysprep in syspreps:
523 name, descr = image_os.sysprep_info(sysprep)
524 display_name = name.replace('-', ' ').capitalize()
525 sysprep_help += "%s\n%s\n%s\n\n" % \
526 (display_name, '-' * len(display_name),
527 wrapper.fill(" ".join(descr.split())))
528 enabled = 1 if sysprep.enabled else 0
529 choices.append((str(index + 1), display_name, enabled))
532 (code, tags) = d.checklist(
533 "Please choose which system preperation tasks you would like to "
534 "run on the image. Press <Help> to see details about the system "
535 "preperation tasks.",
536 title="Run system preperation tasks", choices=choices,
537 width=70, ok_label="Run", help_button=1)
539 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
541 if code == d.DIALOG_HELP:
542 d.scrollbox(sysprep_help, width=70)
546 def customize_menu(session):
547 d = session['dialog']
549 default_item = "Sysprep"
550 actions = {"Sysprep": sysprep,
551 "View/Modify": modify_properties,
552 "Delete": delete_properties,
553 "Exclude": exclude_tasks}
555 (code, choice) = d.menu(
556 "Choose one of the following or press <Back> to exit.",
558 choices=[("Sysprep", "Run various image preperation tasks"),
559 ("Shrink", "Shrink image"),
560 ("View/Modify", "View/Modify image properties"),
561 ("Delete", "Delete image properties"),
563 "Exclude various deployment tasks from running")],
565 default_item=default_item,
566 title="Image Customization Menu")
568 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
570 elif choice in actions:
571 default_item = choice
572 actions[choice](session)
575 def main_menu(session):
576 d = session['dialog']
577 dev = session['device']
578 d.setBackgroundTitle("OS: %s, Distro: %s" % (dev.ostype, dev.distro))
579 actions = {"Customize": customize_menu,
580 "Register": kamaki_menu,
581 "Extract": extract_image}
582 default_item = "Customize"
585 (code, choice) = d.menu(
586 "Choose one of the following or press <Exit> to exit.",
588 choices=[("Customize",
589 "Customize image and ~okeanos deployment options"),
590 ("Register", "Register image to ~okeanos"),
591 ("Extract", "Dump image to local file system"),
592 ("Reset", "Reset everything and start over again"),
593 ("Help", "Get help for using snf-image-creator")],
594 cancel="Exit", menu_height=5, height=13, default_item=default_item,
595 title="Image Creator for ~okeanos (snf-image-creator version %s)" %
598 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
601 elif choice == "Reset":
603 d.infobox("Resetting snf-image-creator. Please wait...")
605 elif choice in actions:
606 actions[choice](session)
609 def select_file(d, media):
612 if media is not None:
613 if not os.path.exists(media):
614 d.msgbox("The file you choose does not exist",
619 (code, media) = d.fselect(root, 10, 50,
620 title="Please select input media")
621 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
622 if confirm_exit(d, "You canceled the media selection dialog box."):
631 def image_creator(d):
632 basename = os.path.basename(sys.argv[0])
633 usage = "Usage: %s [input_media]" % basename
634 if len(sys.argv) > 2:
635 sys.stderr.write("%s\n" % usage)
638 if os.geteuid() != 0:
639 raise FatalError("You must run %s as root" % basename)
641 media = select_file(d, sys.argv[1] if len(sys.argv) == 2 else None)
643 out = InitializationOutput(d)
644 disk = Disk(media, out)
646 def signal_handler(signum, fram):
650 signal.signal(signal.SIGINT, signal_handler)
652 snapshot = disk.snapshot()
653 dev = disk.get_device(snapshot)
655 out.output("Collecting image metadata...")
657 dev.mount(readonly=True)
658 cls = os_cls(dev.distro, dev.ostype)
659 image_os = cls(dev.root, dev.g, out)
661 metadata.update(image_os.meta)
665 # Make sure the signal handler does not call out.cleanup again
668 instancemethod = type(InitializationOutput.cleanup)
669 out.cleanup = instancemethod(dummy, out, InitializationOutput)
671 session = {"dialog": d,
673 "snapshot": snapshot,
675 "image_os": image_os,
676 "metadata": metadata}
679 d.infobox("Thank you for using snf-image-creator. Bye", width=53)
688 d = dialog.Dialog(dialog="dialog")
690 # Add extra button in dialog library
691 dialog._common_args_syntax["extra_button"] = \
692 lambda enable: dialog._simple_option("--extra-button", enable)
694 dialog._common_args_syntax["extra_label"] = \
695 lambda string: ("--extra-label", string)
700 ret = image_creator(d)
702 except FatalError as e:
703 msg = textwrap.fill(str(e), width=70)
704 d.infobox(msg, width=70, title="Fatal Error")
709 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :