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