Fix minor typos
[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     size = dev.size
114
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)
118         return False
119
120     while 1:
121         init = session["upload"] if "upload" in session else ''
122         (code, answer) = d.inputbox("Please provide a filename:", init=init,
123                                     width=WIDTH)
124
125         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
126             return False
127
128         filename = answer.strip()
129         if len(filename) == 0:
130             d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
131             continue
132         session['upload'] = filename
133         break
134
135     gauge = GaugeOutput(d, "Image Upload", "Uploading...")
136     try:
137         out = dev.out
138         out.add(gauge)
139         try:
140             if 'checksum' not in session:
141                 md5 = MD5(out)
142                 session['checksum'] = md5.compute(session['snapshot'], size)
143
144             kamaki = Kamaki(session['account'], out)
145             try:
146                 # Upload image file
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)
158                 out.success("done")
159
160                 # Upload md5sum file
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)
165                 out.success("done")
166
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']
172                 return False
173         finally:
174             out.remove(gauge)
175     finally:
176         gauge.cleanup()
177
178     d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
179              width=SMALL_WIDTH)
180
181     return True
182
183
184 def register_image(session):
185     d = session["dialog"]
186     dev = session['device']
187
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",
191                  width=SMALL_WIDTH)
192         return False
193
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)
197         return False
198
199     while 1:
200         (code, answer) = d.inputbox("Please provide a registration name:",
201                                     width=WIDTH)
202         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
203             return False
204
205         name = answer.strip()
206         if len(name) == 0:
207             d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
208             continue
209         break
210
211     metadata = {}
212     metadata.update(session['metadata'])
213     if 'task_metadata' in session:
214         for key in session['task_metadata']:
215             metadata[key] = 'yes'
216
217     gauge = GaugeOutput(d, "Image Registration", "Registering image...")
218     try:
219         out = dev.out
220         out.add(gauge)
221         try:
222             out.output("Registering image with Cyclades...")
223             try:
224                 kamaki = Kamaki(session['account'], out)
225                 kamaki.register(name, session['pithos_uri'], metadata)
226                 out.success('done')
227             except ClientError as e:
228                 d.msgbox("Error in pithos+ client: %s" % e.message)
229                 return False
230         finally:
231             out.remove(gauge)
232     finally:
233         gauge.cleanup()
234
235     d.msgbox("Image `%s' was successfully registered with Cyclades as `%s'" %
236              (session['upload'], name), width=SMALL_WIDTH)
237     return True
238
239
240 def kamaki_menu(session):
241     d = session['dialog']
242     default_item = "Account"
243
244     if 'account' not in session:
245         token = Kamaki.get_token()
246         if 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
251
252     while 1:
253         account = session["account"]['username'] if "account" in session else \
254             "<none>"
255         upload = session["upload"] if "upload" in session else "<none>"
256
257         choices = [("Account", "Change your ~okeanos account: %s" % account),
258                    ("Upload", "Upload image to pithos+"),
259                    ("Register", "Register the image to cyclades: %s" % upload)]
260
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")
266
267         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
268             return False
269
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):
277                 continue
278             if len(answer) == 0 and "account" in session:
279                     del session["account"]
280             else:
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"
286                 else:
287                     del session['account']
288                     d.msgbox("The token you provided is not valid!",
289                         width=SMALL_WIDTH)
290         elif choice == "Upload":
291             if upload_image(session):
292                 default_item = "Register"
293             else:
294                 default_item = "Upload"
295         elif choice == "Register":
296             if register_image(session):
297                 return True
298             else:
299                 default_item = "Register"
300
301
302 def add_property(session):
303     d = session['dialog']
304
305     while 1:
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):
309             return False
310
311         name = answer.strip()
312         if len(name) == 0:
313             d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
314             continue
315
316         break
317
318     while 1:
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):
322             return False
323
324         value = answer.strip()
325         if len(value) == 0:
326             d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
327             continue
328
329         break
330
331     session['metadata'][name] = value
332
333     return True
334
335
336 def modify_properties(session):
337     d = session['dialog']
338
339     while 1:
340         choices = []
341         for (key, val) in session['metadata'].items():
342             choices.append((str(key), str(val)))
343
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")
352
353         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
354             return True
355         # Edit button
356         elif code == d.DIALOG_OK:
357             (code, answer) = d.inputbox("Please provide a new value for the "
358                                         "image property with name `%s':" %
359                                         choice,
360                                         init=session['metadata'][choice],
361                                         width=WIDTH)
362             if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
363                 value = answer.strip()
364                 if len(value) == 0:
365                     d.msgbox("Value cannot be empty!")
366                     continue
367                 else:
368                     session['metadata'][choice] = value
369         # ADD button
370         elif code == d.DIALOG_EXTRA:
371             add_property(session)
372         elif code == 'help':
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)
376
377
378 def delete_properties(session):
379     d = session['dialog']
380
381     choices = []
382     for (key, val) in session['metadata'].items():
383         choices.append((key, "%s" % val, 0))
384
385     (code, to_delete) = d.checklist("Choose which properties to delete:",
386                                     choices=choices, width=WIDTH)
387
388     # If the user exits with ESC or CANCEL, the returned tag list is empty.
389     for i in to_delete:
390         del session['metadata'][i]
391
392     cnt = len(to_delete)
393     if cnt > 0:
394         d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
395         return True
396     else:
397         return False
398
399
400 def exclude_tasks(session):
401     d = session['dialog']
402
403     index = 0
404     displayed_index = 1
405     choices = []
406     mapping = {}
407     if 'excluded_tasks' not in session:
408         session['excluded_tasks'] = []
409
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)
414         else:
415             return False
416
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
422             displayed_index += 1
423         index += 1
424
425     while 1:
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")
435
436         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
437             return False
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",
442                       width=70, height=40)
443         # No Config button
444         elif code == d.DIALOG_EXTRA:
445             session['excluded_tasks'] = [-1]
446             session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
447             break
448         elif code == d.DIALOG_OK:
449             session['excluded_tasks'] = []
450             for tag in tags:
451                 session['excluded_tasks'].append(mapping[int(tag)])
452
453             exclude_metadata = []
454             for task in session['excluded_tasks']:
455                 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
456
457             session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
458                                            exclude_metadata)
459             break
460
461     return True
462
463
464 def sysprep(session):
465     d = session['dialog']
466     image_os = session['image_os']
467
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."
472
473         if d.yesno("%s\n\nDo you really want to continue?" % msg,
474                    width=SMALL_WIDTH, defaultno=1):
475             return
476
477     wrapper = textwrap.TextWrapper(width=WIDTH - 5)
478
479     help_title = "System Preperation Tasks"
480     sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
481
482     if 'exec_syspreps' not in session:
483         session['exec_syspreps'] = []
484
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']]
488
489     if len(syspreps) == 0:
490         d.msgbox("No system preparation task available to run!",
491                  title="System Preperation", width=SMALL_WIDTH)
492         return
493
494     while 1:
495         choices = []
496         index = 0
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))
505             index += 1
506
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)
512
513         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
514             return False
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])
523                 else:
524                     image_os.disable_sysprep(syspreps[i])
525
526             infobox = InfoBoxOutput(d, "Image Configuration")
527             try:
528                 dev = session['device']
529                 dev.out.add(infobox)
530                 try:
531                     dev.mount(readonly=False)
532                     try:
533                         # The checksum is invalid. We have mounted the image rw
534                         if 'checksum' in session:
535                             del session['checksum']
536
537                         # Monitor the metadata changes during syspreps
538                         with metadata_monitor(session, image_os.meta):
539                             image_os.do_sysprep()
540                             infobox.finalize()
541
542                         # Disable syspreps that have ran
543                         for sysprep in session['exec_syspreps']:
544                             image_os.disable_sysprep(sysprep)
545                     finally:
546                         dev.umount()
547                 finally:
548                     dev.out.remove(infobox)
549             finally:
550                 infobox.cleanup()
551             break
552     return True
553
554
555 def shrink(session):
556     d = session['dialog']
557     dev = session['device']
558
559     shrinked = 'shrinked' in session and session['shrinked']
560
561     if shrinked:
562         d.msgbox("The image is already shrinked!", title="Image Shrinking",
563                  width=SMALL_WIDTH)
564         return True
565
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."
571
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)
576             dev.out.add(infobox)
577             try:
578                 dev.shrink()
579                 infobox.finalize()
580             finally:
581                 dev.out.remove(infobox)
582
583         session['shrinked'] = True
584         update_background_title(session)
585     else:
586         return False
587
588     return True
589
590
591 def customization_menu(session):
592     d = session['dialog']
593
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")]
599
600     default_item = 0
601
602     actions = {"Sysprep": sysprep,
603                "Shrink": shrink,
604                "View/Modify": modify_properties,
605                "Delete": delete_properties,
606                "Exclude": exclude_tasks}
607     while 1:
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")
613
614         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
615             break
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)
620
621
622 def main_menu(session):
623     d = session['dialog']
624     dev = session['device']
625
626     update_background_title(session)
627
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")]
633
634     default_item = "Customize"
635
636     actions = {"Customize": customization_menu, "Register": kamaki_menu,
637                "Extract": extract_image}
638     while 1:
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)" %
644                   version)
645
646         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
647             if confirm_exit(d):
648                 break
649         elif choice == "Reset":
650             if confirm_reset(d):
651                 d.infobox("Resetting snf-image-creator. Please wait...",
652                           width=SMALL_WIDTH)
653                 raise Reset
654         elif choice in actions:
655             actions[choice](session)
656
657 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :