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.
44 from image_creator import __version__ as version
45 from image_creator.util import FatalError, MD5
46 from image_creator.output import Output, CombinedOutput
47 from image_creator.output.cli import SimpleOutput
48 from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
49 from image_creator.disk import Disk
50 from image_creator.os_type import os_cls
51 from image_creator.kamaki_wrapper import Kamaki, ClientError
52 from image_creator.help import get_help_file
53 from image_creator.dialog_wizard import wizard
63 CONFIGURATION_TASKS = [
64 ("Partition table manipulation", ["FixPartitionTable"],
65 ["linux", "windows"]),
66 ("File system resize",
67 ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
68 ["linux", "windows"]),
69 ("Swap partition configuration", ["AddSwap"], ["linux"]),
70 ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
71 ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
73 ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
74 ("Hostname/Computer Name assignment", ["AssignHostname"],
75 ["windows", "linux"]),
76 ("Password change", ["ChangePassword"], ["windows", "linux"]),
77 ("File injection", ["EnforcePersonality"], ["windows", "linux"])
81 class Reset(Exception):
85 class metadata_monitor(object):
86 def __init__(self, session, meta):
87 self.session = session
92 for (k, v) in self.meta.items():
95 def __exit__(self, type, value, traceback):
96 d = self.session['dialog']
101 for (k, v) in self.meta.items():
102 if k not in self.old:
104 elif self.old[k] != v:
107 if not (len(added) or len(altered)):
110 msg = "The last action has changed some image properties:\n\n"
112 msg += "New image properties:\n"
113 for (k, v) in added.items():
114 msg += ' %s: "%s"\n' % (k, v)
117 msg += "Updated image properties:\n"
118 for (k, v) in altered.items():
119 msg += ' %s: "%s" -> "%s"\n' % (k, self.old[k], v)
122 self.session['metadata'].update(added)
123 self.session['metadata'].update(altered)
124 d.msgbox(msg, title="Image Property Changes", width=MSGBOX_WIDTH)
127 def extract_metadata_string(session):
128 metadata = ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()]
130 if 'task_metadata' in session:
131 metadata.extend("%s=yes" % m for m in session['task_metadata'])
133 return '\n'.join(metadata) + '\n'
136 def confirm_exit(d, msg=''):
137 return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
140 def confirm_reset(d):
141 return not d.yesno("Are you sure you want to reset everything?",
142 width=YESNO_WIDTH, defaultno=1)
145 def update_background_title(session):
146 d = session['dialog']
147 dev = session['device']
151 size = (dev.size + MB - 1) // MB
152 shrinked = 'shrinked' in session and session['shrinked']
153 postfix = " (shrinked)" if shrinked else ''
155 title = "OS: %s, Distro: %s, Size: %dMB%s" % \
156 (dev.ostype, dev.distro, size, postfix)
158 d.setBackgroundTitle(title)
161 def extract_image(session):
162 d = session['dialog']
165 if dir and dir[-1] != os.sep:
168 (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
169 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
172 if os.path.isdir(path):
176 if os.path.isdir("%s.meta" % path):
177 d.msgbox("Can't overwrite directory `%s.meta'" % path,
181 if os.path.isdir("%s.md5sum" % path):
182 d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
186 basedir = os.path.dirname(path)
187 name = os.path.basename(path)
188 if not os.path.exists(basedir):
189 d.msgbox("Directory `%s' does not exist" % basedir,
197 files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
198 overwrite = filter(os.path.exists, files)
200 if len(overwrite) > 0:
201 if d.yesno("The following file(s) exist:\n"
202 "%s\nDo you want to overwrite them?" %
203 "\n".join(overwrite), width=YESNO_WIDTH):
206 gauge = GaugeOutput(d, "Image Extraction", "Extracting image...")
208 dev = session['device']
212 if "checksum" not in session:
215 session['checksum'] = md5.compute(session['snapshot'],
221 # Extract metadata file
222 out.output("Extracting metadata file...")
223 with open('%s.meta' % path, 'w') as f:
224 f.write(extract_metadata_string(session))
227 # Extract md5sum file
228 out.output("Extracting md5sum file...")
229 md5str = "%s %s\n" % (session['checksum'], name)
230 with open('%s.md5sum' % path, 'w') as f:
237 d.msgbox("Image file `%s' was successfully extracted!" % path,
244 def upload_image(session):
245 d = session["dialog"]
246 dev = session['device']
249 if "account" not in session:
250 d.msgbox("You need to provide your ~okeanos login username before you "
251 "can upload images to pithos+", width=MSGBOX_WIDTH)
254 if "token" not in session:
255 d.msgbox("You need to provide your ~okeanos account authentication "
256 "token before you can upload images to pithos+",
261 init = session["upload"] if "upload" in session else ''
262 (code, answer) = d.inputbox("Please provide a filename:", init=init,
263 width=INPUTBOX_WIDTH)
265 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
268 filename = answer.strip()
269 if len(filename) == 0:
270 d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
275 gauge = GaugeOutput(d, "Image Upload", "Uploading...")
280 if 'checksum' not in session:
282 session['checksum'] = md5.compute(session['snapshot'], size)
284 kamaki = Kamaki(session['account'], session['token'], out)
287 with open(session['snapshot'], 'rb') as f:
288 session["upload"] = kamaki.upload(f, size, filename,
289 "Calculating block hashes",
290 "Uploading missing blocks")
291 # Upload metadata file
292 out.output("Uploading metadata file...")
293 metastring = extract_metadata_string(session)
294 kamaki.upload(StringIO.StringIO(metastring),
295 size=len(metastring),
296 remote_path="%s.meta" % filename)
300 out.output("Uploading md5sum file...")
301 md5str = "%s %s\n" % (session['checksum'], filename)
302 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
303 remote_path="%s.md5sum" % filename)
306 except ClientError as e:
307 d.msgbox("Error in pithos+ client: %s" % e.message,
308 title="Pithos+ Client Error", width=MSGBOX_WIDTH)
309 if 'upload' in session:
310 del session['upload']
317 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
323 def register_image(session):
324 d = session["dialog"]
325 dev = session['device']
327 if "account" not in session:
328 d.msgbox("You need to provide your ~okeanos login username before you "
329 "can register an images to cyclades",
333 if "token" not in session:
334 d.msgbox("You need to provide your ~okeanos account authentication "
335 "token before you can register an images to cyclades",
339 if "upload" not in session:
340 d.msgbox("You need to upload the image to pithos+ before you can "
341 "register it to cyclades", width=MSGBOX_WIDTH)
345 (code, answer) = d.inputbox("Please provide a registration name:",
346 width=INPUTBOX_WIDTH)
347 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
350 name = answer.strip()
352 d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
357 metadata.update(session['metadata'])
358 if 'task_metadata' in session:
359 for key in session['task_metadata']:
360 metadata[key] = 'yes'
362 gauge = GaugeOutput(d, "Image Registration", "Registrating image...")
367 out.output("Registring image to cyclades...")
369 kamaki = Kamaki(session['account'], session['token'], out)
370 kamaki.register(name, session['upload'], metadata)
372 except ClientError as e:
373 d.msgbox("Error in pithos+ client: %s" % e.message)
380 d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
381 (session['upload'], name), width=MSGBOX_WIDTH)
385 def kamaki_menu(session):
386 d = session['dialog']
387 default_item = "Account"
389 account = Kamaki.get_account()
391 session['account'] = account
393 token = Kamaki.get_token()
395 session['token'] = token
398 account = session["account"] if "account" in session else "<none>"
399 token = session["token"] if "token" in session else "<none>"
400 upload = session["upload"] if "upload" in session else "<none>"
402 choices = [("Account", "Change your ~okeanos username: %s" % account),
403 ("Token", "Change your ~okeanos token: %s" % token),
404 ("Upload", "Upload image to pithos+"),
405 ("Register", "Register the image to cyclades: %s" % upload)]
407 (code, choice) = d.menu(
408 text="Choose one of the following or press <Back> to go back.",
409 width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
410 menu_height=5, default_item=default_item,
411 title="Image Registration Menu")
413 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
416 if choice == "Account":
417 default_item = "Account"
418 (code, answer) = d.inputbox(
419 "Please provide your ~okeanos account e-mail address:",
420 init=session["account"] if "account" in session else '',
422 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
424 if len(answer) == 0 and "account" in session:
425 del session["account"]
427 session["account"] = answer.strip()
428 Kamaki.save_account(session['account'])
429 default_item = "Token"
430 elif choice == "Token":
431 default_item = "Token"
432 (code, answer) = d.inputbox(
433 "Please provide your ~okeanos account authetication token:",
434 init=session["token"] if "token" in session else '',
436 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
438 if len(answer) == 0 and "token" in session:
441 session["token"] = answer.strip()
442 Kamaki.save_token(session['account'])
443 default_item = "Upload"
444 elif choice == "Upload":
445 if upload_image(session):
446 default_item = "Register"
448 default_item = "Upload"
449 elif choice == "Register":
450 if register_image(session):
453 default_item = "Register"
456 def add_property(session):
457 d = session['dialog']
460 (code, answer) = d.inputbox("Please provide a name for a new image"
461 " property:", width=INPUTBOX_WIDTH)
462 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
465 name = answer.strip()
467 d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
473 (code, answer) = d.inputbox("Please provide a value for image "
474 "property %s" % name, width=INPUTBOX_WIDTH)
475 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
478 value = answer.strip()
480 d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
485 session['metadata'][name] = value
490 def modify_properties(session):
491 d = session['dialog']
495 for (key, val) in session['metadata'].items():
496 choices.append((str(key), str(val)))
498 (code, choice) = d.menu(
499 "In this menu you can edit existing image properties or add new "
500 "ones. Be careful! Most properties have special meaning and "
501 "alter the image deployment behaviour. Press <HELP> to see more "
502 "information about image properties. Press <BACK> when done.",
503 height=18, width=MENU_WIDTH, choices=choices, menu_height=10,
504 ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
505 help_button=1, title="Image Properties")
507 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
510 elif code == d.DIALOG_OK:
511 (code, answer) = d.inputbox("Please provide a new value for the "
512 "image property with name `%s':" %
514 init=session['metadata'][choice],
515 width=INPUTBOX_WIDTH)
516 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
517 value = answer.strip()
519 d.msgbox("Value cannot be empty!")
522 session['metadata'][choice] = value
524 elif code == d.DIALOG_EXTRA:
525 add_property(session)
527 help_file = get_help_file("image_properties")
528 assert os.path.exists(help_file)
529 d.textbox(help_file, title="Image Properties", width=70, height=40)
532 def delete_properties(session):
533 d = session['dialog']
536 for (key, val) in session['metadata'].items():
537 choices.append((key, "%s" % val, 0))
539 (code, to_delete) = d.checklist("Choose which properties to delete:",
540 choices=choices, width=CHECKBOX_WIDTH)
542 # If the user exits with ESC or CANCEL, the returned tag list is empty.
544 del session['metadata'][i]
548 d.msgbox("%d image properties were deleted." % cnt, width=MSGBOX_WIDTH)
554 def exclude_tasks(session):
555 d = session['dialog']
561 if 'excluded_tasks' not in session:
562 session['excluded_tasks'] = []
564 if -1 in session['excluded_tasks']:
565 if not d.yesno("Image deployment configuration is disabled. "
566 "Do you wish to enable it?", width=YESNO_WIDTH):
567 session['excluded_tasks'].remove(-1)
571 for (msg, task, osfamily) in CONFIGURATION_TASKS:
572 if session['metadata']['OSFAMILY'] in osfamily:
573 checked = 1 if index in session['excluded_tasks'] else 0
574 choices.append((str(displayed_index), msg, checked))
575 mapping[displayed_index] = index
580 (code, tags) = d.checklist(
581 text="Please choose which configuration tasks you would like to "
582 "prevent from running during image deployment. "
583 "Press <No Config> to supress any configuration. "
584 "Press <Help> for more help on the image deployment "
585 "configuration tasks.",
586 choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
587 help_button=1, extra_button=1, extra_label="No Config",
588 title="Exclude Configuration Tasks")
590 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
592 elif code == d.DIALOG_HELP:
593 help_file = get_help_file("configuration_tasks")
594 assert os.path.exists(help_file)
595 d.textbox(help_file, title="Configuration Tasks",
598 elif code == d.DIALOG_EXTRA:
599 session['excluded_tasks'] = [-1]
600 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
602 elif code == d.DIALOG_OK:
603 session['excluded_tasks'] = []
605 session['excluded_tasks'].append(mapping[int(tag)])
607 exclude_metadata = []
608 for task in session['excluded_tasks']:
609 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
611 session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
618 def sysprep(session):
619 d = session['dialog']
620 image_os = session['image_os']
622 # Is the image already shrinked?
623 if 'shrinked' in session and session['shrinked']:
624 msg = "It seems you have shrinked the image. Running system " \
625 "preparation tasks on a shrinked image is dangerous."
627 if d.yesno("%s\n\nDo you really want to continue?" % msg,
628 width=YESNO_WIDTH, defaultno=1):
631 wrapper = textwrap.TextWrapper(width=65)
633 help_title = "System Preperation Tasks"
634 sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
636 if 'exec_syspreps' not in session:
637 session['exec_syspreps'] = []
639 all_syspreps = image_os.list_syspreps()
640 # Only give the user the choice between syspreps that have not ran yet
641 syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
643 if len(syspreps) == 0:
644 d.msgbox("No system preparation task available to run!",
645 title="System Preperation", width=MSGBOX_WIDTH)
651 for sysprep in syspreps:
652 name, descr = image_os.sysprep_info(sysprep)
653 display_name = name.replace('-', ' ').capitalize()
654 sysprep_help += "%s\n" % display_name
655 sysprep_help += "%s\n" % ('-' * len(display_name))
656 sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
657 enabled = 1 if sysprep.enabled else 0
658 choices.append((str(index + 1), display_name, enabled))
661 (code, tags) = d.checklist(
662 "Please choose which system preperation tasks you would like to "
663 "run on the image. Press <Help> to see details about the system "
664 "preperation tasks.", title="Run system preperation tasks",
665 choices=choices, width=70, ok_label="Run", help_button=1)
667 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
669 elif code == d.DIALOG_HELP:
670 d.scrollbox(sysprep_help, width=HELP_WIDTH)
671 elif code == d.DIALOG_OK:
672 # Enable selected syspreps and disable the rest
673 for i in range(len(syspreps)):
674 if str(i + 1) in tags:
675 image_os.enable_sysprep(syspreps[i])
676 session['exec_syspreps'].append(syspreps[i])
678 image_os.disable_sysprep(syspreps[i])
680 infobox = InfoBoxOutput(d, "Image Configuration")
682 dev = session['device']
685 dev.mount(readonly=False)
687 # The checksum is invalid. We have mounted the image rw
688 if 'checksum' in session:
689 del session['checksum']
691 # Monitor the metadata changes during syspreps
692 with metadata_monitor(session, image_os.meta):
693 image_os.do_sysprep()
696 # Disable syspreps that have ran
697 for sysprep in session['exec_syspreps']:
698 image_os.disable_sysprep(sysprep)
702 dev.out.remove(infobox)
710 d = session['dialog']
711 dev = session['device']
713 shrinked = 'shrinked' in session and session['shrinked']
716 d.msgbox("The image is already shrinked!", title="Image Shrinking",
720 msg = "This operation will shrink the last partition of the image to " \
721 "reduce the total image size. If the last partition is a swap " \
722 "partition, then this partition is removed and the partition " \
723 "before that is shrinked. The removed swap partition will be " \
724 "recreated during image deployment."
726 if not d.yesno("%s\n\nDo you want to continue?" % msg, width=70,
727 height=12, title="Image Shrinking"):
728 with metadata_monitor(session, dev.meta):
729 infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
735 dev.out.remove(infobox)
737 session['shrinked'] = True
738 update_background_title(session)
745 def customization_menu(session):
746 d = session['dialog']
748 choices = [("Sysprep", "Run various image preperation tasks"),
749 ("Shrink", "Shrink image"),
750 ("View/Modify", "View/Modify image properties"),
751 ("Delete", "Delete image properties"),
752 ("Exclude", "Exclude various deployment tasks from running")]
756 actions = {"Sysprep": sysprep,
758 "View/Modify": modify_properties,
759 "Delete": delete_properties,
760 "Exclude": exclude_tasks}
762 (code, choice) = d.menu(
763 text="Choose one of the following or press <Back> to exit.",
764 width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
765 menu_height=len(choices), default_item=choices[default_item][0],
766 title="Image Customization Menu")
768 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
770 elif choice in actions:
771 default_item = [entry[0] for entry in choices].index(choice)
772 if actions[choice](session):
773 default_item = (default_item + 1) % len(choices)
776 def main_menu(session):
777 d = session['dialog']
778 dev = session['device']
780 update_background_title(session)
782 choices = [("Customize", "Customize image & ~okeanos deployment options"),
783 ("Register", "Register image to ~okeanos"),
784 ("Extract", "Dump image to local file system"),
785 ("Reset", "Reset everything and start over again"),
786 ("Help", "Get help for using snf-image-creator")]
788 default_item = "Customize"
790 actions = {"Customize": customization_menu, "Register": kamaki_menu,
791 "Extract": extract_image}
793 (code, choice) = d.menu(
794 text="Choose one of the following or press <Exit> to exit.",
795 width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
796 default_item=default_item, menu_height=len(choices),
797 title="Image Creator for ~okeanos (snf-image-creator version %s)" %
800 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
803 elif choice == "Reset":
805 d.infobox("Resetting snf-image-creator. Please wait...",
808 elif choice in actions:
809 actions[choice](session)
812 def image_creator(d, media, out):
814 d.setBackgroundTitle('snf-image-creator')
816 gauge = GaugeOutput(d, "Initialization", "Initializing...")
818 disk = Disk(media, out)
820 def signal_handler(signum, frame):
824 signal.signal(signal.SIGINT, signal_handler)
826 snapshot = disk.snapshot()
827 dev = disk.get_device(snapshot)
830 for (key, value) in dev.meta.items():
831 metadata[str(key)] = str(value)
833 dev.mount(readonly=True)
834 out.output("Collecting image metadata...")
835 cls = os_cls(dev.distro, dev.ostype)
836 image_os = cls(dev.root, dev.g, out)
839 for (key, value) in image_os.meta.items():
840 metadata[str(key)] = str(value)
846 # Make sure the signal handler does not call gauge.cleanup again
849 gauge.cleanup = type(GaugeOutput.cleanup)(dummy, gauge, GaugeOutput)
851 session = {"dialog": d,
853 "snapshot": snapshot,
855 "image_os": image_os,
856 "metadata": metadata}
858 msg = "snf-image-creator detected a %s system on the input media. " \
859 "Would you like to run a wizards to assists you through the " \
860 "image creation process?\n\nChoose <Yes> to run the wizard, " \
861 "<No> to run the snf-image-creator in expert mode or press " \
862 "ESC to quit the program." \
863 % (dev.ostype if dev.ostype == dev.distro else "%s (%s)" %
864 (dev.ostype, dev.distro))
866 update_background_title(session)
869 code = d.yesno(msg, width=YESNO_WIDTH, height=12)
870 if code == d.DIALOG_OK:
873 elif code == d.DIALOG_CANCEL:
880 d.infobox("Thank you for using snf-image-creator. Bye", width=53)
887 def select_file(d, media):
890 if media is not None:
891 if not os.path.exists(media):
892 d.msgbox("The file `%s' you choose does not exist." % media,
897 (code, media) = d.fselect(root, 10, 50,
898 title="Please select input media")
899 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
900 if confirm_exit(d, "You canceled the media selection dialog box."):
911 d = dialog.Dialog(dialog="dialog")
913 # Add extra button in dialog library
914 dialog._common_args_syntax["extra_button"] = \
915 lambda enable: dialog._simple_option("--extra-button", enable)
917 dialog._common_args_syntax["extra_label"] = \
918 lambda string: ("--extra-label", string)
920 usage = "Usage: %prog [options] [<input_media>]"
921 parser = optparse.OptionParser(version=version, usage=usage)
922 parser.add_option("-l", "--logfile", type="string", dest="logfile",
923 default=None, help="log all messages to FILE",
926 options, args = parser.parse_args(sys.argv[1:])
929 parser.error("Wrong number of arguments")
931 d.setBackgroundTitle('snf-image-creator')
934 if os.geteuid() != 0:
935 raise FatalError("You must run %s as root" % \
936 parser.get_prog_name())
938 media = select_file(d, args[0] if len(args) == 1 else None)
941 if options.logfile is not None:
943 logfile = open(options.logfile, 'w')
946 "Unable to open logfile `%s' for writing. Reason: %s" % \
947 (options.logfile, e.strerror))
949 log = SimpleOutput(False, logfile) if logfile is not None \
953 out = CombinedOutput([log])
954 out.output("Starting %s version %s..." % \
955 (parser.get_prog_name(), version))
956 ret = image_creator(d, media, out)
959 log.output("Resetting everything...")
962 if logfile is not None:
964 except FatalError as e:
965 msg = textwrap.fill(str(e), width=70)
966 d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
969 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :