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.
41 from image_creator import __version__ as version
42 from image_creator.util import MD5
43 from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
44 from image_creator.kamaki_wrapper import Kamaki, ClientError
45 from image_creator.help import get_help_file
46 from image_creator.dialog_util import SMALL_WIDTH, WIDTH, \
47 update_background_title, confirm_reset, confirm_exit, Reset, extract_image
49 CONFIGURATION_TASKS = [
50 ("Partition table manipulation", ["FixPartitionTable"],
51 ["linux", "windows"]),
52 ("File system resize",
53 ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
54 ["linux", "windows"]),
55 ("Swap partition configuration", ["AddSwap"], ["linux"]),
56 ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
57 ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
59 ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
60 ("Hostname/Computer Name assignment", ["AssignHostname"],
61 ["windows", "linux"]),
62 ("Password change", ["ChangePassword"], ["windows", "linux"]),
63 ("File injection", ["EnforcePersonality"], ["windows", "linux"])
67 class metadata_monitor(object):
68 def __init__(self, session, meta):
69 self.session = session
74 for (k, v) in self.meta.items():
77 def __exit__(self, type, value, traceback):
78 d = self.session['dialog']
83 for (k, v) in self.meta.items():
86 elif self.old[k] != v:
89 if not (len(added) or len(altered)):
92 msg = "The last action has changed some image properties:\n\n"
94 msg += "New image properties:\n"
95 for (k, v) in added.items():
96 msg += ' %s: "%s"\n' % (k, v)
99 msg += "Updated image properties:\n"
100 for (k, v) in altered.items():
101 msg += ' %s: "%s" -> "%s"\n' % (k, self.old[k], v)
104 self.session['metadata'].update(added)
105 self.session['metadata'].update(altered)
106 d.msgbox(msg, title="Image Property Changes", width=SMALL_WIDTH)
109 def extract_metadata_string(session):
110 metadata = ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()]
112 if 'task_metadata' in session:
113 metadata.extend("%s=yes" % m for m in session['task_metadata'])
115 return '\n'.join(metadata) + '\n'
118 def upload_image(session):
119 d = session["dialog"]
120 dev = session['device']
123 if "account" not in session:
124 d.msgbox("You need to provide your ~okeanos login username before you "
125 "can upload images to pithos+", width=SMALL_WIDTH)
128 if "token" not in session:
129 d.msgbox("You need to provide your ~okeanos account authentication "
130 "token before you can upload images to pithos+",
135 init = session["upload"] if "upload" in session else ''
136 (code, answer) = d.inputbox("Please provide a filename:", init=init,
139 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
142 filename = answer.strip()
143 if len(filename) == 0:
144 d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
146 session['upload'] = filename
149 gauge = GaugeOutput(d, "Image Upload", "Uploading...")
154 if 'checksum' not in session:
156 session['checksum'] = md5.compute(session['snapshot'], size)
158 kamaki = Kamaki(session['account'], session['token'], out)
161 with open(session['snapshot'], 'rb') as f:
162 session["pithos_uri"] = \
163 kamaki.upload(f, size, filename,
164 "Calculating block hashes",
165 "Uploading missing blocks")
166 # Upload metadata file
167 out.output("Uploading metadata file...")
168 metastring = extract_metadata_string(session)
169 kamaki.upload(StringIO.StringIO(metastring),
170 size=len(metastring),
171 remote_path="%s.meta" % filename)
175 out.output("Uploading md5sum file...")
176 md5str = "%s %s\n" % (session['checksum'], filename)
177 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
178 remote_path="%s.md5sum" % filename)
181 except ClientError as e:
182 d.msgbox("Error in pithos+ client: %s" % e.message,
183 title="Pithos+ Client Error", width=SMALL_WIDTH)
184 if 'pithos_uri' in session:
185 del session['pithos_uri']
192 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
198 def register_image(session):
199 d = session["dialog"]
200 dev = session['device']
202 if "account" not in session:
203 d.msgbox("You need to provide your ~okeanos login username before you "
204 "can register an images to cyclades",
208 if "token" not in session:
209 d.msgbox("You need to provide your ~okeanos account authentication "
210 "token before you can register an images to cyclades",
214 if "pithos_uri" not in session:
215 d.msgbox("You need to upload the image to pithos+ before you can "
216 "register it to cyclades", width=SMALL_WIDTH)
220 (code, answer) = d.inputbox("Please provide a registration name:",
222 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
225 name = answer.strip()
227 d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
232 metadata.update(session['metadata'])
233 if 'task_metadata' in session:
234 for key in session['task_metadata']:
235 metadata[key] = 'yes'
237 gauge = GaugeOutput(d, "Image Registration", "Registering image...")
242 out.output("Registering image with Cyclades...")
244 kamaki = Kamaki(session['account'], session['token'], out)
245 kamaki.register(name, session['pithos_uri'], metadata)
247 except ClientError as e:
248 d.msgbox("Error in pithos+ client: %s" % e.message)
255 d.msgbox("Image `%s' was successfully registered with Cyclades as `%s'" %
256 (session['upload'], name), width=SMALL_WIDTH)
260 def kamaki_menu(session):
261 d = session['dialog']
262 default_item = "Account"
264 account = Kamaki.get_account()
266 session['account'] = account
268 token = Kamaki.get_token()
270 session['token'] = token
273 account = session["account"] if "account" in session else "<none>"
274 token = session["token"] if "token" in session else "<none>"
275 upload = session["upload"] if "upload" in session else "<none>"
277 choices = [("Account", "Change your ~okeanos username: %s" % account),
278 ("Token", "Change your ~okeanos token: %s" % token),
279 ("Upload", "Upload image to pithos+"),
280 ("Register", "Register the image to cyclades: %s" % upload)]
282 (code, choice) = d.menu(
283 text="Choose one of the following or press <Back> to go back.",
284 width=WIDTH, choices=choices, cancel="Back", height=13,
285 menu_height=5, default_item=default_item,
286 title="Image Registration Menu")
288 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
291 if choice == "Account":
292 default_item = "Account"
293 (code, answer) = d.inputbox(
294 "Please provide your ~okeanos account e-mail address:",
295 init=session["account"] if "account" in session else '',
297 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
299 if len(answer) == 0 and "account" in session:
300 del session["account"]
302 session["account"] = answer.strip()
303 Kamaki.save_account(session['account'])
304 default_item = "Token"
305 elif choice == "Token":
306 default_item = "Token"
307 (code, answer) = d.inputbox(
308 "Please provide your ~okeanos account authetication token:",
309 init=session["token"] if "token" in session else '',
311 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
313 if len(answer) == 0 and "token" in session:
316 session["token"] = answer.strip()
317 Kamaki.save_token(session['token'])
318 default_item = "Upload"
319 elif choice == "Upload":
320 if upload_image(session):
321 default_item = "Register"
323 default_item = "Upload"
324 elif choice == "Register":
325 if register_image(session):
328 default_item = "Register"
331 def add_property(session):
332 d = session['dialog']
335 (code, answer) = d.inputbox("Please provide a name for a new image"
336 " property:", width=WIDTH)
337 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
340 name = answer.strip()
342 d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
348 (code, answer) = d.inputbox("Please provide a value for image "
349 "property %s" % name, width=WIDTH)
350 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
353 value = answer.strip()
355 d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
360 session['metadata'][name] = value
365 def modify_properties(session):
366 d = session['dialog']
370 for (key, val) in session['metadata'].items():
371 choices.append((str(key), str(val)))
373 (code, choice) = d.menu(
374 "In this menu you can edit existing image properties or add new "
375 "ones. Be careful! Most properties have special meaning and "
376 "alter the image deployment behaviour. Press <HELP> to see more "
377 "information about image properties. Press <BACK> when done.",
378 height=18, width=WIDTH, choices=choices, menu_height=10,
379 ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
380 help_button=1, title="Image Properties")
382 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
385 elif code == d.DIALOG_OK:
386 (code, answer) = d.inputbox("Please provide a new value for the "
387 "image property with name `%s':" %
389 init=session['metadata'][choice],
391 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
392 value = answer.strip()
394 d.msgbox("Value cannot be empty!")
397 session['metadata'][choice] = value
399 elif code == d.DIALOG_EXTRA:
400 add_property(session)
402 help_file = get_help_file("image_properties")
403 assert os.path.exists(help_file)
404 d.textbox(help_file, title="Image Properties", width=70, height=40)
407 def delete_properties(session):
408 d = session['dialog']
411 for (key, val) in session['metadata'].items():
412 choices.append((key, "%s" % val, 0))
414 (code, to_delete) = d.checklist("Choose which properties to delete:",
415 choices=choices, width=WIDTH)
417 # If the user exits with ESC or CANCEL, the returned tag list is empty.
419 del session['metadata'][i]
423 d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
429 def exclude_tasks(session):
430 d = session['dialog']
436 if 'excluded_tasks' not in session:
437 session['excluded_tasks'] = []
439 if -1 in session['excluded_tasks']:
440 if not d.yesno("Image deployment configuration is disabled. "
441 "Do you wish to enable it?", width=SMALL_WIDTH):
442 session['excluded_tasks'].remove(-1)
446 for (msg, task, osfamily) in CONFIGURATION_TASKS:
447 if session['metadata']['OSFAMILY'] in osfamily:
448 checked = 1 if index in session['excluded_tasks'] else 0
449 choices.append((str(displayed_index), msg, checked))
450 mapping[displayed_index] = index
455 (code, tags) = d.checklist(
456 text="Please choose which configuration tasks you would like to "
457 "prevent from running during image deployment. "
458 "Press <No Config> to supress any configuration. "
459 "Press <Help> for more help on the image deployment "
460 "configuration tasks.",
461 choices=choices, height=19, list_height=8, width=WIDTH,
462 help_button=1, extra_button=1, extra_label="No Config",
463 title="Exclude Configuration Tasks")
465 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
467 elif code == d.DIALOG_HELP:
468 help_file = get_help_file("configuration_tasks")
469 assert os.path.exists(help_file)
470 d.textbox(help_file, title="Configuration Tasks",
473 elif code == d.DIALOG_EXTRA:
474 session['excluded_tasks'] = [-1]
475 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
477 elif code == d.DIALOG_OK:
478 session['excluded_tasks'] = []
480 session['excluded_tasks'].append(mapping[int(tag)])
482 exclude_metadata = []
483 for task in session['excluded_tasks']:
484 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
486 session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
493 def sysprep(session):
494 d = session['dialog']
495 image_os = session['image_os']
497 # Is the image already shrinked?
498 if 'shrinked' in session and session['shrinked']:
499 msg = "It seems you have shrinked the image. Running system " \
500 "preparation tasks on a shrinked image is dangerous."
502 if d.yesno("%s\n\nDo you really want to continue?" % msg,
503 width=SMALL_WIDTH, defaultno=1):
506 wrapper = textwrap.TextWrapper(width=WIDTH - 5)
508 help_title = "System Preperation Tasks"
509 sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
511 if 'exec_syspreps' not in session:
512 session['exec_syspreps'] = []
514 all_syspreps = image_os.list_syspreps()
515 # Only give the user the choice between syspreps that have not ran yet
516 syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
518 if len(syspreps) == 0:
519 d.msgbox("No system preparation task available to run!",
520 title="System Preperation", width=SMALL_WIDTH)
526 for sysprep in syspreps:
527 name, descr = image_os.sysprep_info(sysprep)
528 display_name = name.replace('-', ' ').capitalize()
529 sysprep_help += "%s\n" % display_name
530 sysprep_help += "%s\n" % ('-' * len(display_name))
531 sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
532 enabled = 1 if sysprep.enabled else 0
533 choices.append((str(index + 1), display_name, enabled))
536 (code, tags) = d.checklist(
537 "Please choose which system preparation tasks you would like to "
538 "run on the image. Press <Help> to see details about the system "
539 "preparation tasks.", title="Run system preparation tasks",
540 choices=choices, width=70, ok_label="Run", help_button=1)
542 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
544 elif code == d.DIALOG_HELP:
545 d.scrollbox(sysprep_help, width=WIDTH)
546 elif code == d.DIALOG_OK:
547 # Enable selected syspreps and disable the rest
548 for i in range(len(syspreps)):
549 if str(i + 1) in tags:
550 image_os.enable_sysprep(syspreps[i])
551 session['exec_syspreps'].append(syspreps[i])
553 image_os.disable_sysprep(syspreps[i])
555 infobox = InfoBoxOutput(d, "Image Configuration")
557 dev = session['device']
560 dev.mount(readonly=False)
562 # The checksum is invalid. We have mounted the image rw
563 if 'checksum' in session:
564 del session['checksum']
566 # Monitor the metadata changes during syspreps
567 with metadata_monitor(session, image_os.meta):
568 image_os.do_sysprep()
571 # Disable syspreps that have ran
572 for sysprep in session['exec_syspreps']:
573 image_os.disable_sysprep(sysprep)
577 dev.out.remove(infobox)
585 d = session['dialog']
586 dev = session['device']
588 shrinked = 'shrinked' in session and session['shrinked']
591 d.msgbox("The image is already shrinked!", title="Image Shrinking",
595 msg = "This operation will shrink the last partition of the image to " \
596 "reduce the total image size. If the last partition is a swap " \
597 "partition, then this partition is removed and the partition " \
598 "before that is shrinked. The removed swap partition will be " \
599 "recreated during image deployment."
601 if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH,
602 height=12, title="Image Shrinking"):
603 with metadata_monitor(session, dev.meta):
604 infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
610 dev.out.remove(infobox)
612 session['shrinked'] = True
613 update_background_title(session)
620 def customization_menu(session):
621 d = session['dialog']
623 choices = [("Sysprep", "Run various image preparation tasks"),
624 ("Shrink", "Shrink image"),
625 ("View/Modify", "View/Modify image properties"),
626 ("Delete", "Delete image properties"),
627 ("Exclude", "Exclude various deployment tasks from running")]
631 actions = {"Sysprep": sysprep,
633 "View/Modify": modify_properties,
634 "Delete": delete_properties,
635 "Exclude": exclude_tasks}
637 (code, choice) = d.menu(
638 text="Choose one of the following or press <Back> to exit.",
639 width=WIDTH, choices=choices, cancel="Back", height=13,
640 menu_height=len(choices), default_item=choices[default_item][0],
641 title="Image Customization Menu")
643 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
645 elif choice in actions:
646 default_item = [entry[0] for entry in choices].index(choice)
647 if actions[choice](session):
648 default_item = (default_item + 1) % len(choices)
651 def main_menu(session):
652 d = session['dialog']
653 dev = session['device']
655 update_background_title(session)
657 choices = [("Customize", "Customize image & ~okeanos deployment options"),
658 ("Register", "Register image to ~okeanos"),
659 ("Extract", "Dump image to local file system"),
660 ("Reset", "Reset everything and start over again"),
661 ("Help", "Get help for using snf-image-creator")]
663 default_item = "Customize"
665 actions = {"Customize": customization_menu, "Register": kamaki_menu,
666 "Extract": extract_image}
668 (code, choice) = d.menu(
669 text="Choose one of the following or press <Exit> to exit.",
670 width=WIDTH, choices=choices, cancel="Exit", height=13,
671 default_item=default_item, menu_height=len(choices),
672 title="Image Creator for ~okeanos (snf-image-creator version %s)" %
675 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
678 elif choice == "Reset":
680 d.infobox("Resetting snf-image-creator. Please wait...",
683 elif choice in actions:
684 actions[choice](session)
686 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :