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