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, \
48 extract_image, extract_metadata_string
50 CONFIGURATION_TASKS = [
51 ("Partition table manipulation", ["FixPartitionTable"],
52 ["linux", "windows"]),
53 ("File system resize",
54 ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
55 ["linux", "windows"]),
56 ("Swap partition configuration", ["AddSwap"], ["linux"]),
57 ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
58 ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
60 ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
61 ("Hostname/Computer Name assignment", ["AssignHostname"],
62 ["windows", "linux"]),
63 ("Password change", ["ChangePassword"], ["windows", "linux"]),
64 ("File injection", ["EnforcePersonality"], ["windows", "linux"])
68 class metadata_monitor(object):
69 def __init__(self, session, meta):
70 self.session = session
75 for (k, v) in self.meta.items():
78 def __exit__(self, type, value, traceback):
79 d = self.session['dialog']
84 for (k, v) in self.meta.items():
87 elif self.old[k] != v:
90 if not (len(added) or len(altered)):
93 msg = "The last action has changed some image properties:\n\n"
95 msg += "New image properties:\n"
96 for (k, v) in added.items():
97 msg += ' %s: "%s"\n' % (k, v)
100 msg += "Updated image properties:\n"
101 for (k, v) in altered.items():
102 msg += ' %s: "%s" -> "%s"\n' % (k, self.old[k], v)
105 self.session['metadata'].update(added)
106 self.session['metadata'].update(altered)
107 d.msgbox(msg, title="Image Property Changes", width=SMALL_WIDTH)
110 def upload_image(session):
111 d = session["dialog"]
112 dev = session['device']
115 if "account" not in session:
116 d.msgbox("You need to provide your ~okeanos account before you "
117 "can upload images to pithos+", width=SMALL_WIDTH)
121 init = session["upload"] if "upload" in session else ''
122 (code, answer) = d.inputbox("Please provide a filename:", init=init,
125 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
128 filename = answer.strip()
129 if len(filename) == 0:
130 d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
132 session['upload'] = filename
135 gauge = GaugeOutput(d, "Image Upload", "Uploading...")
140 if 'checksum' not in session:
142 session['checksum'] = md5.compute(session['snapshot'], size)
144 kamaki = Kamaki(session['account'], out)
147 with open(session['snapshot'], 'rb') as f:
148 session["pithos_uri"] = \
149 kamaki.upload(f, size, filename,
150 "Calculating block hashes",
151 "Uploading missing blocks")
152 # Upload metadata file
153 out.output("Uploading metadata file...")
154 metastring = extract_metadata_string(session)
155 kamaki.upload(StringIO.StringIO(metastring),
156 size=len(metastring),
157 remote_path="%s.meta" % filename)
161 out.output("Uploading md5sum file...")
162 md5str = "%s %s\n" % (session['checksum'], filename)
163 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
164 remote_path="%s.md5sum" % filename)
167 except ClientError as e:
168 d.msgbox("Error in pithos+ client: %s" % e.message,
169 title="Pithos+ Client Error", width=SMALL_WIDTH)
170 if 'pithos_uri' in session:
171 del session['pithos_uri']
178 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
184 def register_image(session):
185 d = session["dialog"]
186 dev = session['device']
188 if "account" not in session:
189 d.msgbox("You need to provide your ~okeanos login username before you "
190 "can register an images to cyclades",
194 if "pithos_uri" not in session:
195 d.msgbox("You need to upload the image to pithos+ before you can "
196 "register it to cyclades", width=SMALL_WIDTH)
200 (code, answer) = d.inputbox("Please provide a registration name:",
202 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
205 name = answer.strip()
207 d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
212 metadata.update(session['metadata'])
213 if 'task_metadata' in session:
214 for key in session['task_metadata']:
215 metadata[key] = 'yes'
217 gauge = GaugeOutput(d, "Image Registration", "Registering image...")
222 out.output("Registering image with Cyclades...")
224 kamaki = Kamaki(session['account'], out)
225 kamaki.register(name, session['pithos_uri'], metadata)
227 except ClientError as e:
228 d.msgbox("Error in pithos+ client: %s" % e.message)
235 d.msgbox("Image `%s' was successfully registered with Cyclades as `%s'" %
236 (session['upload'], name), width=SMALL_WIDTH)
240 def kamaki_menu(session):
241 d = session['dialog']
242 default_item = "Account"
244 if 'account' not in session:
245 token = Kamaki.get_token()
247 session['account'] = Kamaki.get_account(token)
248 if not session['account']:
249 del session['account']
250 Kamaki.save_token('') # The token was not valid. Remove it
253 account = session["account"]['username'] if "account" in session else \
255 upload = session["upload"] if "upload" in session else "<none>"
257 choices = [("Account", "Change your ~okeanos account: %s" % account),
258 ("Upload", "Upload image to pithos+"),
259 ("Register", "Register the image to cyclades: %s" % upload)]
261 (code, choice) = d.menu(
262 text="Choose one of the following or press <Back> to go back.",
263 width=WIDTH, choices=choices, cancel="Back", height=13,
264 menu_height=5, default_item=default_item,
265 title="Image Registration Menu")
267 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
270 if choice == "Account":
271 default_item = "Account"
272 (code, answer) = d.inputbox(
273 "Please provide your ~okeanos token:",
274 init=session["account"]['auth_token'] if "account" in session
275 else '', width=WIDTH)
276 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
278 if len(answer) == 0 and "account" in session:
279 del session["account"]
281 token = answer.strip()
282 session['account'] = Kamaki.get_account(token)
283 if session['account'] is not None:
284 Kamaki.save_token(token)
285 default_item = "Upload"
287 del session['account']
288 d.msgbox("The token you provided is not valid!",
290 elif choice == "Upload":
291 if upload_image(session):
292 default_item = "Register"
294 default_item = "Upload"
295 elif choice == "Register":
296 if register_image(session):
299 default_item = "Register"
302 def add_property(session):
303 d = session['dialog']
306 (code, answer) = d.inputbox("Please provide a name for a new image"
307 " property:", width=WIDTH)
308 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
311 name = answer.strip()
313 d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
319 (code, answer) = d.inputbox("Please provide a value for image "
320 "property %s" % name, width=WIDTH)
321 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
324 value = answer.strip()
326 d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
331 session['metadata'][name] = value
336 def modify_properties(session):
337 d = session['dialog']
341 for (key, val) in session['metadata'].items():
342 choices.append((str(key), str(val)))
344 (code, choice) = d.menu(
345 "In this menu you can edit existing image properties or add new "
346 "ones. Be careful! Most properties have special meaning and "
347 "alter the image deployment behaviour. Press <HELP> to see more "
348 "information about image properties. Press <BACK> when done.",
349 height=18, width=WIDTH, choices=choices, menu_height=10,
350 ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
351 help_button=1, title="Image Properties")
353 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
356 elif code == d.DIALOG_OK:
357 (code, answer) = d.inputbox("Please provide a new value for the "
358 "image property with name `%s':" %
360 init=session['metadata'][choice],
362 if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
363 value = answer.strip()
365 d.msgbox("Value cannot be empty!")
368 session['metadata'][choice] = value
370 elif code == d.DIALOG_EXTRA:
371 add_property(session)
373 help_file = get_help_file("image_properties")
374 assert os.path.exists(help_file)
375 d.textbox(help_file, title="Image Properties", width=70, height=40)
378 def delete_properties(session):
379 d = session['dialog']
382 for (key, val) in session['metadata'].items():
383 choices.append((key, "%s" % val, 0))
385 (code, to_delete) = d.checklist("Choose which properties to delete:",
386 choices=choices, width=WIDTH)
388 # If the user exits with ESC or CANCEL, the returned tag list is empty.
390 del session['metadata'][i]
394 d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
400 def exclude_tasks(session):
401 d = session['dialog']
407 if 'excluded_tasks' not in session:
408 session['excluded_tasks'] = []
410 if -1 in session['excluded_tasks']:
411 if not d.yesno("Image deployment configuration is disabled. "
412 "Do you wish to enable it?", width=SMALL_WIDTH):
413 session['excluded_tasks'].remove(-1)
417 for (msg, task, osfamily) in CONFIGURATION_TASKS:
418 if session['metadata']['OSFAMILY'] in osfamily:
419 checked = 1 if index in session['excluded_tasks'] else 0
420 choices.append((str(displayed_index), msg, checked))
421 mapping[displayed_index] = index
426 (code, tags) = d.checklist(
427 text="Please choose which configuration tasks you would like to "
428 "prevent from running during image deployment. "
429 "Press <No Config> to supress any configuration. "
430 "Press <Help> for more help on the image deployment "
431 "configuration tasks.",
432 choices=choices, height=19, list_height=8, width=WIDTH,
433 help_button=1, extra_button=1, extra_label="No Config",
434 title="Exclude Configuration Tasks")
436 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
438 elif code == d.DIALOG_HELP:
439 help_file = get_help_file("configuration_tasks")
440 assert os.path.exists(help_file)
441 d.textbox(help_file, title="Configuration Tasks",
444 elif code == d.DIALOG_EXTRA:
445 session['excluded_tasks'] = [-1]
446 session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
448 elif code == d.DIALOG_OK:
449 session['excluded_tasks'] = []
451 session['excluded_tasks'].append(mapping[int(tag)])
453 exclude_metadata = []
454 for task in session['excluded_tasks']:
455 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
457 session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
464 def sysprep(session):
465 d = session['dialog']
466 image_os = session['image_os']
468 # Is the image already shrinked?
469 if 'shrinked' in session and session['shrinked']:
470 msg = "It seems you have shrinked the image. Running system " \
471 "preparation tasks on a shrinked image is dangerous."
473 if d.yesno("%s\n\nDo you really want to continue?" % msg,
474 width=SMALL_WIDTH, defaultno=1):
477 wrapper = textwrap.TextWrapper(width=WIDTH - 5)
479 help_title = "System Preperation Tasks"
480 sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
482 if 'exec_syspreps' not in session:
483 session['exec_syspreps'] = []
485 all_syspreps = image_os.list_syspreps()
486 # Only give the user the choice between syspreps that have not ran yet
487 syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
489 if len(syspreps) == 0:
490 d.msgbox("No system preparation task available to run!",
491 title="System Preperation", width=SMALL_WIDTH)
497 for sysprep in syspreps:
498 name, descr = image_os.sysprep_info(sysprep)
499 display_name = name.replace('-', ' ').capitalize()
500 sysprep_help += "%s\n" % display_name
501 sysprep_help += "%s\n" % ('-' * len(display_name))
502 sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
503 enabled = 1 if sysprep.enabled else 0
504 choices.append((str(index + 1), display_name, enabled))
507 (code, tags) = d.checklist(
508 "Please choose which system preparation tasks you would like to "
509 "run on the image. Press <Help> to see details about the system "
510 "preparation tasks.", title="Run system preparation tasks",
511 choices=choices, width=70, ok_label="Run", help_button=1)
513 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
515 elif code == d.DIALOG_HELP:
516 d.scrollbox(sysprep_help, width=WIDTH)
517 elif code == d.DIALOG_OK:
518 # Enable selected syspreps and disable the rest
519 for i in range(len(syspreps)):
520 if str(i + 1) in tags:
521 image_os.enable_sysprep(syspreps[i])
522 session['exec_syspreps'].append(syspreps[i])
524 image_os.disable_sysprep(syspreps[i])
526 infobox = InfoBoxOutput(d, "Image Configuration")
528 dev = session['device']
531 dev.mount(readonly=False)
533 # The checksum is invalid. We have mounted the image rw
534 if 'checksum' in session:
535 del session['checksum']
537 # Monitor the metadata changes during syspreps
538 with metadata_monitor(session, image_os.meta):
539 image_os.do_sysprep()
542 # Disable syspreps that have ran
543 for sysprep in session['exec_syspreps']:
544 image_os.disable_sysprep(sysprep)
548 dev.out.remove(infobox)
556 d = session['dialog']
557 dev = session['device']
559 shrinked = 'shrinked' in session and session['shrinked']
562 d.msgbox("The image is already shrinked!", title="Image Shrinking",
566 msg = "This operation will shrink the last partition of the image to " \
567 "reduce the total image size. If the last partition is a swap " \
568 "partition, then this partition is removed and the partition " \
569 "before that is shrinked. The removed swap partition will be " \
570 "recreated during image deployment."
572 if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH,
573 height=12, title="Image Shrinking"):
574 with metadata_monitor(session, dev.meta):
575 infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
581 dev.out.remove(infobox)
583 session['shrinked'] = True
584 update_background_title(session)
591 def customization_menu(session):
592 d = session['dialog']
594 choices = [("Sysprep", "Run various image preparation 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")]
602 actions = {"Sysprep": sysprep,
604 "View/Modify": modify_properties,
605 "Delete": delete_properties,
606 "Exclude": exclude_tasks}
608 (code, choice) = d.menu(
609 text="Choose one of the following or press <Back> to exit.",
610 width=WIDTH, choices=choices, cancel="Back", height=13,
611 menu_height=len(choices), default_item=choices[default_item][0],
612 title="Image Customization Menu")
614 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
616 elif choice in actions:
617 default_item = [entry[0] for entry in choices].index(choice)
618 if actions[choice](session):
619 default_item = (default_item + 1) % len(choices)
622 def main_menu(session):
623 d = session['dialog']
624 dev = session['device']
626 update_background_title(session)
628 choices = [("Customize", "Customize image & ~okeanos deployment options"),
629 ("Register", "Register image to ~okeanos"),
630 ("Extract", "Dump image to local file system"),
631 ("Reset", "Reset everything and start over again"),
632 ("Help", "Get help for using snf-image-creator")]
634 default_item = "Customize"
636 actions = {"Customize": customization_menu, "Register": kamaki_menu,
637 "Extract": extract_image}
639 (code, choice) = d.menu(
640 text="Choose one of the following or press <Exit> to exit.",
641 width=WIDTH, choices=choices, cancel="Exit", height=13,
642 default_item=default_item, menu_height=len(choices),
643 title="Image Creator for ~okeanos (snf-image-creator version %s)" %
646 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
649 elif choice == "Reset":
651 d.infobox("Resetting snf-image-creator. Please wait...",
654 elif choice in actions:
655 actions[choice](session)
657 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :