84d11c79d0a6ed33cda185e096dcd3145177afc4
[snf-image-creator] / image_creator / dialog_menu.py
1 #!/usr/bin/env python
2
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
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.
17 #
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.
30 #
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.
35
36 import sys
37 import os
38 import textwrap
39 import StringIO
40
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
49
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"],
59         ["windows"]),
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"])
65 ]
66
67
68 class metadata_monitor(object):
69     def __init__(self, session, meta):
70         self.session = session
71         self.meta = meta
72
73     def __enter__(self):
74         self.old = {}
75         for (k, v) in self.meta.items():
76             self.old[k] = v
77
78     def __exit__(self, type, value, traceback):
79         d = self.session['dialog']
80
81         altered = {}
82         added = {}
83
84         for (k, v) in self.meta.items():
85             if k not in self.old:
86                 added[k] = v
87             elif self.old[k] != v:
88                 altered[k] = v
89
90         if not (len(added) or len(altered)):
91             return
92
93         msg = "The last action has changed some image properties:\n\n"
94         if len(added):
95             msg += "New image properties:\n"
96             for (k, v) in added.items():
97                 msg += '    %s: "%s"\n' % (k, v)
98             msg += "\n"
99         if len(altered):
100             msg += "Updated image properties:\n"
101             for (k, v) in altered.items():
102                 msg += '    %s: "%s" -> "%s"\n' % (k, self.old[k], v)
103             msg += "\n"
104
105         self.session['metadata'].update(added)
106         self.session['metadata'].update(altered)
107         d.msgbox(msg, title="Image Property Changes", width=SMALL_WIDTH)
108
109
110 def upload_image(session):
111     d = session["dialog"]
112     dev = session['device']
113     meta = session['metadata']
114     size = dev.size
115
116     if "account" not in session:
117         d.msgbox("You need to provide your ~okeanos credentials before you "
118                  "can upload images to pithos+", width=SMALL_WIDTH)
119         return False
120
121     while 1:
122         if 'upload' in session:
123             init = session['upload']
124         elif 'OS' in meta:
125             init = "%s.diskdump" % meta['OS']
126         else:
127             init = ""
128         (code, answer) = d.inputbox("Please provide a filename:", init=init,
129                                     width=WIDTH)
130
131         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
132             return False
133
134         filename = answer.strip()
135         if len(filename) == 0:
136             d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
137             continue
138         session['upload'] = filename
139         break
140
141     gauge = GaugeOutput(d, "Image Upload", "Uploading...")
142     try:
143         out = dev.out
144         out.add(gauge)
145         try:
146             if 'checksum' not in session:
147                 md5 = MD5(out)
148                 session['checksum'] = md5.compute(session['snapshot'], size)
149
150             kamaki = Kamaki(session['account'], out)
151             try:
152                 # Upload image file
153                 with open(session['snapshot'], 'rb') as f:
154                     session["pithos_uri"] = \
155                         kamaki.upload(f, size, filename,
156                                       "Calculating block hashes",
157                                       "Uploading missing blocks")
158                 # Upload metadata file
159                 out.output("Uploading metadata file...")
160                 metastring = extract_metadata_string(session)
161                 kamaki.upload(StringIO.StringIO(metastring),
162                               size=len(metastring),
163                               remote_path="%s.meta" % filename)
164                 out.success("done")
165
166                 # Upload md5sum file
167                 out.output("Uploading md5sum file...")
168                 md5str = "%s %s\n" % (session['checksum'], filename)
169                 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
170                               remote_path="%s.md5sum" % filename)
171                 out.success("done")
172
173             except ClientError as e:
174                 d.msgbox("Error in pithos+ client: %s" % e.message,
175                          title="Pithos+ Client Error", width=SMALL_WIDTH)
176                 if 'pithos_uri' in session:
177                     del session['pithos_uri']
178                 return False
179         finally:
180             out.remove(gauge)
181     finally:
182         gauge.cleanup()
183
184     d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
185              width=SMALL_WIDTH)
186
187     return True
188
189
190 def register_image(session):
191     d = session["dialog"]
192     dev = session['device']
193
194     is_public = False
195
196     if "account" not in session:
197         d.msgbox("You need to provide your ~okeanos credentians before you "
198                  "can register an images to cyclades",
199                  width=SMALL_WIDTH)
200         return False
201
202     if "pithos_uri" not in session:
203         d.msgbox("You need to upload the image to pithos+ before you can "
204                  "register it to cyclades", width=SMALL_WIDTH)
205         return False
206
207     while 1:
208         (code, answer) = d.inputbox("Please provide a registration name:",
209                                     width=WIDTH)
210         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
211             return False
212
213         name = answer.strip()
214         if len(name) == 0:
215             d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
216             continue
217
218         ret = d.yesno("Make the image public?\\nA public image is accessible "
219                       "by every user of the service.", defaultno=1,
220                       width=WIDTH)
221         if ret not in (0, 1):
222             continue
223
224         is_public = True if ret == 0 else False
225
226         break
227
228     metadata = {}
229     metadata.update(session['metadata'])
230     if 'task_metadata' in session:
231         for key in session['task_metadata']:
232             metadata[key] = 'yes'
233
234     img_type = "public" if is_public else "private"
235     gauge = GaugeOutput(d, "Image Registration", "Registering image...")
236     try:
237         out = dev.out
238         out.add(gauge)
239         try:
240             out.output("Registering %s image with Cyclades..." % img_type)
241             try:
242                 kamaki = Kamaki(session['account'], out)
243                 kamaki.register(name, session['pithos_uri'], metadata,
244                                 is_public)
245                 out.success('done')
246             except ClientError as e:
247                 d.msgbox("Error in pithos+ client: %s" % e.message)
248                 return False
249         finally:
250             out.remove(gauge)
251     finally:
252         gauge.cleanup()
253
254     d.msgbox("%s image `%s' was successfully registered with Cyclades as `%s'"
255              % (img_type.title(), session['upload'], name), width=SMALL_WIDTH)
256     return True
257
258
259 def kamaki_menu(session):
260     d = session['dialog']
261     default_item = "Account"
262
263     if 'account' not in session:
264         token = Kamaki.get_token()
265         if token:
266             session['account'] = Kamaki.get_account(token)
267             if not session['account']:
268                 del session['account']
269                 Kamaki.save_token('')  # The token was not valid. Remove it
270
271     while 1:
272         account = session["account"]['username'] if "account" in session else \
273             "<none>"
274         upload = session["upload"] if "upload" in session else "<none>"
275
276         choices = [("Account", "Change your ~okeanos account: %s" % account),
277                    ("Upload", "Upload image to pithos+"),
278                    ("Register", "Register the image to cyclades: %s" % upload)]
279
280         (code, choice) = d.menu(
281             text="Choose one of the following or press <Back> to go back.",
282             width=WIDTH, choices=choices, cancel="Back", height=13,
283             menu_height=5, default_item=default_item,
284             title="Image Registration Menu")
285
286         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
287             return False
288
289         if choice == "Account":
290             default_item = "Account"
291             (code, answer) = d.inputbox(
292                 "Please provide your ~okeanos authentication token:",
293                 init=session["account"]['auth_token'] if "account" in session
294                 else '', width=WIDTH)
295             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
296                 continue
297             if len(answer) == 0 and "account" in session:
298                     del session["account"]
299             else:
300                 token = answer.strip()
301                 session['account'] = Kamaki.get_account(token)
302                 if session['account'] is not None:
303                     Kamaki.save_token(token)
304                     default_item = "Upload"
305                 else:
306                     del session['account']
307                     d.msgbox("The token you provided is not valid!",
308                              width=SMALL_WIDTH)
309         elif choice == "Upload":
310             if upload_image(session):
311                 default_item = "Register"
312             else:
313                 default_item = "Upload"
314         elif choice == "Register":
315             if register_image(session):
316                 return True
317             else:
318                 default_item = "Register"
319
320
321 def add_property(session):
322     d = session['dialog']
323
324     while 1:
325         (code, answer) = d.inputbox("Please provide a name for a new image"
326                                     " property:", width=WIDTH)
327         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
328             return False
329
330         name = answer.strip()
331         if len(name) == 0:
332             d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
333             continue
334
335         break
336
337     while 1:
338         (code, answer) = d.inputbox("Please provide a value for image "
339                                     "property %s" % name, width=WIDTH)
340         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
341             return False
342
343         value = answer.strip()
344         if len(value) == 0:
345             d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
346             continue
347
348         break
349
350     session['metadata'][name] = value
351
352     return True
353
354
355 def modify_properties(session):
356     d = session['dialog']
357
358     while 1:
359         choices = []
360         for (key, val) in session['metadata'].items():
361             choices.append((str(key), str(val)))
362
363         (code, choice) = d.menu(
364             "In this menu you can edit existing image properties or add new "
365             "ones. Be careful! Most properties have special meaning and "
366             "alter the image deployment behaviour. Press <HELP> to see more "
367             "information about image properties. Press <BACK> when done.",
368             height=18, width=WIDTH, choices=choices, menu_height=10,
369             ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
370             help_button=1, title="Image Properties")
371
372         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
373             return True
374         # Edit button
375         elif code == d.DIALOG_OK:
376             (code, answer) = d.inputbox("Please provide a new value for the "
377                                         "image property with name `%s':" %
378                                         choice,
379                                         init=session['metadata'][choice],
380                                         width=WIDTH)
381             if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
382                 value = answer.strip()
383                 if len(value) == 0:
384                     d.msgbox("Value cannot be empty!")
385                     continue
386                 else:
387                     session['metadata'][choice] = value
388         # ADD button
389         elif code == d.DIALOG_EXTRA:
390             add_property(session)
391         elif code == 'help':
392             help_file = get_help_file("image_properties")
393             assert os.path.exists(help_file)
394             d.textbox(help_file, title="Image Properties", width=70, height=40)
395
396
397 def delete_properties(session):
398     d = session['dialog']
399
400     choices = []
401     for (key, val) in session['metadata'].items():
402         choices.append((key, "%s" % val, 0))
403
404     (code, to_delete) = d.checklist("Choose which properties to delete:",
405                                     choices=choices, width=WIDTH)
406
407     # If the user exits with ESC or CANCEL, the returned tag list is empty.
408     for i in to_delete:
409         del session['metadata'][i]
410
411     cnt = len(to_delete)
412     if cnt > 0:
413         d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
414         return True
415     else:
416         return False
417
418
419 def exclude_tasks(session):
420     d = session['dialog']
421
422     index = 0
423     displayed_index = 1
424     choices = []
425     mapping = {}
426     if 'excluded_tasks' not in session:
427         session['excluded_tasks'] = []
428
429     if -1 in session['excluded_tasks']:
430         if not d.yesno("Image deployment configuration is disabled. "
431                        "Do you wish to enable it?", width=SMALL_WIDTH):
432             session['excluded_tasks'].remove(-1)
433         else:
434             return False
435
436     for (msg, task, osfamily) in CONFIGURATION_TASKS:
437         if session['metadata']['OSFAMILY'] in osfamily:
438             checked = 1 if index in session['excluded_tasks'] else 0
439             choices.append((str(displayed_index), msg, checked))
440             mapping[displayed_index] = index
441             displayed_index += 1
442         index += 1
443
444     while 1:
445         (code, tags) = d.checklist(
446             text="Please choose which configuration tasks you would like to "
447                  "prevent from running during image deployment. "
448                  "Press <No Config> to supress any configuration. "
449                  "Press <Help> for more help on the image deployment "
450                  "configuration tasks.",
451             choices=choices, height=19, list_height=8, width=WIDTH,
452             help_button=1, extra_button=1, extra_label="No Config",
453             title="Exclude Configuration Tasks")
454
455         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
456             return False
457         elif code == d.DIALOG_HELP:
458             help_file = get_help_file("configuration_tasks")
459             assert os.path.exists(help_file)
460             d.textbox(help_file, title="Configuration Tasks",
461                       width=70, height=40)
462         # No Config button
463         elif code == d.DIALOG_EXTRA:
464             session['excluded_tasks'] = [-1]
465             session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
466             break
467         elif code == d.DIALOG_OK:
468             session['excluded_tasks'] = []
469             for tag in tags:
470                 session['excluded_tasks'].append(mapping[int(tag)])
471
472             exclude_metadata = []
473             for task in session['excluded_tasks']:
474                 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
475
476             session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
477                                            exclude_metadata)
478             break
479
480     return True
481
482
483 def sysprep(session):
484     d = session['dialog']
485     image_os = session['image_os']
486
487     # Is the image already shrinked?
488     if 'shrinked' in session and session['shrinked']:
489         msg = "It seems you have shrinked the image. Running system " \
490               "preparation tasks on a shrinked image is dangerous."
491
492         if d.yesno("%s\n\nDo you really want to continue?" % msg,
493                    width=SMALL_WIDTH, defaultno=1):
494             return
495
496     wrapper = textwrap.TextWrapper(width=WIDTH - 5)
497
498     help_title = "System Preperation Tasks"
499     sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
500
501     if 'exec_syspreps' not in session:
502         session['exec_syspreps'] = []
503
504     all_syspreps = image_os.list_syspreps()
505     # Only give the user the choice between syspreps that have not ran yet
506     syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
507
508     if len(syspreps) == 0:
509         d.msgbox("No system preparation task available to run!",
510                  title="System Preperation", width=SMALL_WIDTH)
511         return
512
513     while 1:
514         choices = []
515         index = 0
516         for sysprep in syspreps:
517             name, descr = image_os.sysprep_info(sysprep)
518             display_name = name.replace('-', ' ').capitalize()
519             sysprep_help += "%s\n" % display_name
520             sysprep_help += "%s\n" % ('-' * len(display_name))
521             sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
522             enabled = 1 if sysprep.enabled else 0
523             choices.append((str(index + 1), display_name, enabled))
524             index += 1
525
526         (code, tags) = d.checklist(
527             "Please choose which system preparation tasks you would like to "
528             "run on the image. Press <Help> to see details about the system "
529             "preparation tasks.", title="Run system preparation tasks",
530             choices=choices, width=70, ok_label="Run", help_button=1)
531
532         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
533             return False
534         elif code == d.DIALOG_HELP:
535             d.scrollbox(sysprep_help, width=WIDTH)
536         elif code == d.DIALOG_OK:
537             # Enable selected syspreps and disable the rest
538             for i in range(len(syspreps)):
539                 if str(i + 1) in tags:
540                     image_os.enable_sysprep(syspreps[i])
541                     session['exec_syspreps'].append(syspreps[i])
542                 else:
543                     image_os.disable_sysprep(syspreps[i])
544
545             infobox = InfoBoxOutput(d, "Image Configuration")
546             try:
547                 dev = session['device']
548                 dev.out.add(infobox)
549                 try:
550                     dev.mount(readonly=False)
551                     try:
552                         # The checksum is invalid. We have mounted the image rw
553                         if 'checksum' in session:
554                             del session['checksum']
555
556                         # Monitor the metadata changes during syspreps
557                         with metadata_monitor(session, image_os.meta):
558                             image_os.do_sysprep()
559                             infobox.finalize()
560
561                         # Disable syspreps that have ran
562                         for sysprep in session['exec_syspreps']:
563                             image_os.disable_sysprep(sysprep)
564                     finally:
565                         dev.umount()
566                 finally:
567                     dev.out.remove(infobox)
568             finally:
569                 infobox.cleanup()
570             break
571     return True
572
573
574 def shrink(session):
575     d = session['dialog']
576     dev = session['device']
577
578     shrinked = 'shrinked' in session and session['shrinked']
579
580     if shrinked:
581         d.msgbox("The image is already shrinked!", title="Image Shrinking",
582                  width=SMALL_WIDTH)
583         return True
584
585     msg = "This operation will shrink the last partition of the image to " \
586           "reduce the total image size. If the last partition is a swap " \
587           "partition, then this partition is removed and the partition " \
588           "before that is shrinked. The removed swap partition will be " \
589           "recreated during image deployment."
590
591     if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH,
592                    height=12, title="Image Shrinking"):
593         with metadata_monitor(session, dev.meta):
594             infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
595             dev.out.add(infobox)
596             try:
597                 dev.shrink()
598                 infobox.finalize()
599             finally:
600                 dev.out.remove(infobox)
601
602         session['shrinked'] = True
603         update_background_title(session)
604     else:
605         return False
606
607     return True
608
609
610 def customization_menu(session):
611     d = session['dialog']
612
613     choices = [("Sysprep", "Run various image preparation tasks"),
614                ("Shrink", "Shrink image"),
615                ("View/Modify", "View/Modify image properties"),
616                ("Delete", "Delete image properties"),
617                ("Exclude", "Exclude various deployment tasks from running")]
618
619     default_item = 0
620
621     actions = {"Sysprep": sysprep,
622                "Shrink": shrink,
623                "View/Modify": modify_properties,
624                "Delete": delete_properties,
625                "Exclude": exclude_tasks}
626     while 1:
627         (code, choice) = d.menu(
628             text="Choose one of the following or press <Back> to exit.",
629             width=WIDTH, choices=choices, cancel="Back", height=13,
630             menu_height=len(choices), default_item=choices[default_item][0],
631             title="Image Customization Menu")
632
633         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
634             break
635         elif choice in actions:
636             default_item = [entry[0] for entry in choices].index(choice)
637             if actions[choice](session):
638                 default_item = (default_item + 1) % len(choices)
639
640
641 def main_menu(session):
642     d = session['dialog']
643     dev = session['device']
644
645     update_background_title(session)
646
647     choices = [("Customize", "Customize image & ~okeanos deployment options"),
648                ("Register", "Register image to ~okeanos"),
649                ("Extract", "Dump image to local file system"),
650                ("Reset", "Reset everything and start over again"),
651                ("Help", "Get help for using snf-image-creator")]
652
653     default_item = "Customize"
654
655     actions = {"Customize": customization_menu, "Register": kamaki_menu,
656                "Extract": extract_image}
657     while 1:
658         (code, choice) = d.menu(
659             text="Choose one of the following or press <Exit> to exit.",
660             width=WIDTH, choices=choices, cancel="Exit", height=13,
661             default_item=default_item, menu_height=len(choices),
662             title="Image Creator for ~okeanos (snf-image-creator version %s)" %
663                   version)
664
665         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
666             if confirm_exit(d):
667                 break
668         elif choice == "Reset":
669             if confirm_reset(d):
670                 d.infobox("Resetting snf-image-creator. Please wait...",
671                           width=SMALL_WIDTH)
672                 raise Reset
673         elif choice in actions:
674             actions[choice](session)
675
676 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :