Add logging service in snf-image-creator-dialog
[snf-image-creator] / image_creator / dialog_main.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 dialog
37 import sys
38 import os
39 import textwrap
40 import signal
41 import StringIO
42 import optparse
43
44 from image_creator import __version__ as version
45 from image_creator.util import FatalError, MD5
46 from image_creator.output import Output, CombinedOutput
47 from image_creator.output.cli import SimpleOutput
48 from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
49 from image_creator.disk import Disk
50 from image_creator.os_type import os_cls
51 from image_creator.kamaki_wrapper import Kamaki, ClientError
52 from image_creator.help import get_help_file
53 from image_creator.dialog_wizard import wizard
54
55 MSGBOX_WIDTH = 60
56 YESNO_WIDTH = 50
57 MENU_WIDTH = 70
58 INPUTBOX_WIDTH = 70
59 CHECKBOX_WIDTH = 70
60 HELP_WIDTH = 70
61 INFOBOX_WIDTH = 70
62
63 CONFIGURATION_TASKS = [
64     ("Partition table manipulation", ["FixPartitionTable"],
65         ["linux", "windows"]),
66     ("File system resize",
67         ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
68         ["linux", "windows"]),
69     ("Swap partition configuration", ["AddSwap"], ["linux"]),
70     ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
71     ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
72         ["windows"]),
73     ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
74     ("Hostname/Computer Name assignment", ["AssignHostname"],
75         ["windows", "linux"]),
76     ("Password change", ["ChangePassword"], ["windows", "linux"]),
77     ("File injection", ["EnforcePersonality"], ["windows", "linux"])
78 ]
79
80
81 class Reset(Exception):
82     pass
83
84
85 class metadata_monitor(object):
86     def __init__(self, session, meta):
87         self.session = session
88         self.meta = meta
89
90     def __enter__(self):
91         self.old = {}
92         for (k, v) in self.meta.items():
93             self.old[k] = v
94
95     def __exit__(self, type, value, traceback):
96         d = self.session['dialog']
97
98         altered = {}
99         added = {}
100
101         for (k, v) in self.meta.items():
102             if k not in self.old:
103                 added[k] = v
104             elif self.old[k] != v:
105                 altered[k] = v
106
107         if not (len(added) or len(altered)):
108             return
109
110         msg = "The last action has changed some image properties:\n\n"
111         if len(added):
112             msg += "New image properties:\n"
113             for (k, v) in added.items():
114                 msg += '    %s: "%s"\n' % (k, v)
115             msg += "\n"
116         if len(altered):
117             msg += "Updated image properties:\n"
118             for (k, v) in altered.items():
119                 msg += '    %s: "%s" -> "%s"\n' % (k, self.old[k], v)
120             msg += "\n"
121
122         self.session['metadata'].update(added)
123         self.session['metadata'].update(altered)
124         d.msgbox(msg, title="Image Property Changes", width=MSGBOX_WIDTH)
125
126
127 def extract_metadata_string(session):
128     metadata = ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()]
129
130     if 'task_metadata' in session:
131         metadata.extend("%s=yes" % m for m in session['task_metadata'])
132
133     return '\n'.join(metadata) + '\n'
134
135
136 def confirm_exit(d, msg=''):
137     return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
138
139
140 def confirm_reset(d):
141     return not d.yesno("Are you sure you want to reset everything?",
142                        width=YESNO_WIDTH, defaultno=1)
143
144
145 def update_background_title(session):
146     d = session['dialog']
147     dev = session['device']
148
149     MB = 2 ** 20
150
151     size = (dev.size + MB - 1) // MB
152     shrinked = 'shrinked' in session and session['shrinked']
153     postfix = " (shrinked)" if shrinked else ''
154
155     title = "OS: %s, Distro: %s, Size: %dMB%s" % \
156             (dev.ostype, dev.distro, size, postfix)
157
158     d.setBackgroundTitle(title)
159
160
161 def extract_image(session):
162     d = session['dialog']
163     dir = os.getcwd()
164     while 1:
165         if dir and dir[-1] != os.sep:
166             dir = dir + os.sep
167
168         (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
169         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
170             return False
171
172         if os.path.isdir(path):
173             dir = path
174             continue
175
176         if os.path.isdir("%s.meta" % path):
177             d.msgbox("Can't overwrite directory `%s.meta'" % path,
178                      width=MSGBOX_WIDTH)
179             continue
180
181         if os.path.isdir("%s.md5sum" % path):
182             d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
183                      width=MSGBOX_WIDTH)
184             continue
185
186         basedir = os.path.dirname(path)
187         name = os.path.basename(path)
188         if not os.path.exists(basedir):
189             d.msgbox("Directory `%s' does not exist" % basedir,
190                      width=MSGBOX_WIDTH)
191             continue
192
193         dir = basedir
194         if len(name) == 0:
195             continue
196
197         files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
198         overwrite = filter(os.path.exists, files)
199
200         if len(overwrite) > 0:
201             if d.yesno("The following file(s) exist:\n"
202                        "%s\nDo you want to overwrite them?" %
203                        "\n".join(overwrite), width=YESNO_WIDTH):
204                 continue
205
206         gauge = GaugeOutput(d, "Image Extraction", "Extracting image...")
207         try:
208             dev = session['device']
209             out = dev.out
210             out.add(gauge)
211             try:
212                 if "checksum" not in session:
213                     size = dev.size
214                     md5 = MD5(out)
215                     session['checksum'] = md5.compute(session['snapshot'],
216                                                       size)
217
218                 # Extract image file
219                 dev.dump(path)
220
221                 # Extract metadata file
222                 out.output("Extracting metadata file...")
223                 with open('%s.meta' % path, 'w') as f:
224                     f.write(extract_metadata_string(session))
225                 out.success('done')
226
227                 # Extract md5sum file
228                 out.output("Extracting md5sum file...")
229                 md5str = "%s %s\n" % (session['checksum'], name)
230                 with open('%s.md5sum' % path, 'w') as f:
231                     f.write(md5str)
232                 out.success("done")
233             finally:
234                 out.remove(gauge)
235         finally:
236             gauge.cleanup()
237         d.msgbox("Image file `%s' was successfully extracted!" % path,
238                  width=MSGBOX_WIDTH)
239         break
240
241     return True
242
243
244 def upload_image(session):
245     d = session["dialog"]
246     dev = session['device']
247     size = dev.size
248
249     if "account" not in session:
250         d.msgbox("You need to provide your ~okeanos login username before you "
251                  "can upload images to pithos+", width=MSGBOX_WIDTH)
252         return False
253
254     if "token" not in session:
255         d.msgbox("You need to provide your ~okeanos account authentication "
256                  "token before you can upload images to pithos+",
257                  width=MSGBOX_WIDTH)
258         return False
259
260     while 1:
261         init = session["upload"] if "upload" in session else ''
262         (code, answer) = d.inputbox("Please provide a filename:", init=init,
263                                     width=INPUTBOX_WIDTH)
264
265         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
266             return False
267
268         filename = answer.strip()
269         if len(filename) == 0:
270             d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
271             continue
272
273         break
274
275     gauge = GaugeOutput(d, "Image Upload", "Uploading...")
276     try:
277         out = dev.out
278         out.add(gauge)
279         try:
280             if 'checksum' not in session:
281                 md5 = MD5(out)
282                 session['checksum'] = md5.compute(session['snapshot'], size)
283
284             kamaki = Kamaki(session['account'], session['token'], out)
285             try:
286                 # Upload image file
287                 with open(session['snapshot'], 'rb') as f:
288                     session["upload"] = kamaki.upload(f, size, filename,
289                                                     "Calculating block hashes",
290                                                     "Uploading missing blocks")
291                 # Upload metadata file
292                 out.output("Uploading metadata file...")
293                 metastring = extract_metadata_string(session)
294                 kamaki.upload(StringIO.StringIO(metastring),
295                               size=len(metastring),
296                               remote_path="%s.meta" % filename)
297                 out.success("done")
298
299                 # Upload md5sum file
300                 out.output("Uploading md5sum file...")
301                 md5str = "%s %s\n" % (session['checksum'], filename)
302                 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
303                               remote_path="%s.md5sum" % filename)
304                 out.success("done")
305
306             except ClientError as e:
307                 d.msgbox("Error in pithos+ client: %s" % e.message,
308                          title="Pithos+ Client Error", width=MSGBOX_WIDTH)
309                 if 'upload' in session:
310                     del session['upload']
311                 return False
312         finally:
313             out.remove(gauge)
314     finally:
315         gauge.cleanup()
316
317     d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
318              width=MSGBOX_WIDTH)
319
320     return True
321
322
323 def register_image(session):
324     d = session["dialog"]
325     dev = session['device']
326
327     if "account" not in session:
328         d.msgbox("You need to provide your ~okeanos login username before you "
329                  "can register an images to cyclades",
330                  width=MSGBOX_WIDTH)
331         return False
332
333     if "token" not in session:
334         d.msgbox("You need to provide your ~okeanos account authentication "
335                  "token before you can register an images to cyclades",
336                  width=MSGBOX_WIDTH)
337         return False
338
339     if "upload" not in session:
340         d.msgbox("You need to upload the image to pithos+ before you can "
341                  "register it to cyclades", width=MSGBOX_WIDTH)
342         return False
343
344     while 1:
345         (code, answer) = d.inputbox("Please provide a registration name:",
346                                     width=INPUTBOX_WIDTH)
347         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
348             return False
349
350         name = answer.strip()
351         if len(name) == 0:
352             d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
353             continue
354         break
355
356     metadata = {}
357     metadata.update(session['metadata'])
358     if 'task_metadata' in session:
359         for key in session['task_metadata']:
360             metadata[key] = 'yes'
361
362     gauge = GaugeOutput(d, "Image Registration", "Registrating image...")
363     try:
364         out = dev.out
365         out.add(gauge)
366         try:
367             out.output("Registring image to cyclades...")
368             try:
369                 kamaki = Kamaki(session['account'], session['token'], out)
370                 kamaki.register(name, session['upload'], metadata)
371                 out.success('done')
372             except ClientError as e:
373                 d.msgbox("Error in pithos+ client: %s" % e.message)
374                 return False
375         finally:
376             out.remove(gauge)
377     finally:
378         gauge.cleanup()
379
380     d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
381              (session['upload'], name), width=MSGBOX_WIDTH)
382     return True
383
384
385 def kamaki_menu(session):
386     d = session['dialog']
387     default_item = "Account"
388
389     account = Kamaki.get_account()
390     if account:
391         session['account'] = account
392
393     token = Kamaki.get_token()
394     if token:
395         session['token'] = token
396
397     while 1:
398         account = session["account"] if "account" in session else "<none>"
399         token = session["token"] if "token" in session else "<none>"
400         upload = session["upload"] if "upload" in session else "<none>"
401
402         choices = [("Account", "Change your ~okeanos username: %s" % account),
403                    ("Token", "Change your ~okeanos token: %s" % token),
404                    ("Upload", "Upload image to pithos+"),
405                    ("Register", "Register the image to cyclades: %s" % upload)]
406
407         (code, choice) = d.menu(
408             text="Choose one of the following or press <Back> to go back.",
409             width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
410             menu_height=5, default_item=default_item,
411             title="Image Registration Menu")
412
413         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
414             return False
415
416         if choice == "Account":
417             default_item = "Account"
418             (code, answer) = d.inputbox(
419                 "Please provide your ~okeanos account e-mail address:",
420                 init=session["account"] if "account" in session else '',
421                 width=70)
422             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
423                 continue
424             if len(answer) == 0 and "account" in session:
425                     del session["account"]
426             else:
427                 session["account"] = answer.strip()
428                 Kamaki.save_account(session['account'])
429                 default_item = "Token"
430         elif choice == "Token":
431             default_item = "Token"
432             (code, answer) = d.inputbox(
433                 "Please provide your ~okeanos account authetication token:",
434                 init=session["token"] if "token" in session else '',
435                 width=70)
436             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
437                 continue
438             if len(answer) == 0 and "token" in session:
439                 del session["token"]
440             else:
441                 session["token"] = answer.strip()
442                 Kamaki.save_token(session['account'])
443                 default_item = "Upload"
444         elif choice == "Upload":
445             if upload_image(session):
446                 default_item = "Register"
447             else:
448                 default_item = "Upload"
449         elif choice == "Register":
450             if register_image(session):
451                 return True
452             else:
453                 default_item = "Register"
454
455
456 def add_property(session):
457     d = session['dialog']
458
459     while 1:
460         (code, answer) = d.inputbox("Please provide a name for a new image"
461                                     " property:", width=INPUTBOX_WIDTH)
462         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
463             return False
464
465         name = answer.strip()
466         if len(name) == 0:
467             d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
468             continue
469
470         break
471
472     while 1:
473         (code, answer) = d.inputbox("Please provide a value for image "
474                                     "property %s" % name, width=INPUTBOX_WIDTH)
475         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
476             return False
477
478         value = answer.strip()
479         if len(value) == 0:
480             d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
481             continue
482
483         break
484
485     session['metadata'][name] = value
486
487     return True
488
489
490 def modify_properties(session):
491     d = session['dialog']
492
493     while 1:
494         choices = []
495         for (key, val) in session['metadata'].items():
496             choices.append((str(key), str(val)))
497
498         (code, choice) = d.menu(
499             "In this menu you can edit existing image properties or add new "
500             "ones. Be careful! Most properties have special meaning and "
501             "alter the image deployment behaviour. Press <HELP> to see more "
502             "information about image properties. Press <BACK> when done.",
503             height=18, width=MENU_WIDTH, choices=choices, menu_height=10,
504             ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
505             help_button=1, title="Image Properties")
506
507         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
508             return True
509         # Edit button
510         elif code == d.DIALOG_OK:
511             (code, answer) = d.inputbox("Please provide a new value for the "
512                                         "image property with name `%s':" %
513                                         choice,
514                                         init=session['metadata'][choice],
515                                         width=INPUTBOX_WIDTH)
516             if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
517                 value = answer.strip()
518                 if len(value) == 0:
519                     d.msgbox("Value cannot be empty!")
520                     continue
521                 else:
522                     session['metadata'][choice] = value
523         # ADD button
524         elif code == d.DIALOG_EXTRA:
525             add_property(session)
526         elif code == 'help':
527             help_file = get_help_file("image_properties")
528             assert os.path.exists(help_file)
529             d.textbox(help_file, title="Image Properties", width=70, height=40)
530
531
532 def delete_properties(session):
533     d = session['dialog']
534
535     choices = []
536     for (key, val) in session['metadata'].items():
537         choices.append((key, "%s" % val, 0))
538
539     (code, to_delete) = d.checklist("Choose which properties to delete:",
540                                     choices=choices, width=CHECKBOX_WIDTH)
541
542     # If the user exits with ESC or CANCEL, the returned tag list is empty.
543     for i in to_delete:
544         del session['metadata'][i]
545
546     cnt = len(to_delete)
547     if cnt > 0:
548         d.msgbox("%d image properties were deleted." % cnt, width=MSGBOX_WIDTH)
549         return True
550     else:
551         return False
552
553
554 def exclude_tasks(session):
555     d = session['dialog']
556
557     index = 0
558     displayed_index = 1
559     choices = []
560     mapping = {}
561     if 'excluded_tasks' not in session:
562         session['excluded_tasks'] = []
563
564     if -1 in session['excluded_tasks']:
565         if not d.yesno("Image deployment configuration is disabled. "
566                        "Do you wish to enable it?", width=YESNO_WIDTH):
567             session['excluded_tasks'].remove(-1)
568         else:
569             return False
570
571     for (msg, task, osfamily) in CONFIGURATION_TASKS:
572         if session['metadata']['OSFAMILY'] in osfamily:
573             checked = 1 if index in session['excluded_tasks'] else 0
574             choices.append((str(displayed_index), msg, checked))
575             mapping[displayed_index] = index
576             displayed_index += 1
577         index += 1
578
579     while 1:
580         (code, tags) = d.checklist(
581             text="Please choose which configuration tasks you would like to "
582                  "prevent from running during image deployment. "
583                  "Press <No Config> to supress any configuration. "
584                  "Press <Help> for more help on the image deployment "
585                  "configuration tasks.",
586             choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
587             help_button=1, extra_button=1, extra_label="No Config",
588             title="Exclude Configuration Tasks")
589
590         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
591             return False
592         elif code == d.DIALOG_HELP:
593             help_file = get_help_file("configuration_tasks")
594             assert os.path.exists(help_file)
595             d.textbox(help_file, title="Configuration Tasks",
596                       width=70, height=40)
597         # No Config button
598         elif code == d.DIALOG_EXTRA:
599             session['excluded_tasks'] = [-1]
600             session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
601             break
602         elif code == d.DIALOG_OK:
603             session['excluded_tasks'] = []
604             for tag in tags:
605                 session['excluded_tasks'].append(mapping[int(tag)])
606
607             exclude_metadata = []
608             for task in session['excluded_tasks']:
609                 exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
610
611             session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
612                                            exclude_metadata)
613             break
614
615     return True
616
617
618 def sysprep(session):
619     d = session['dialog']
620     image_os = session['image_os']
621
622     # Is the image already shrinked?
623     if 'shrinked' in session and session['shrinked']:
624         msg = "It seems you have shrinked the image. Running system " \
625               "preparation tasks on a shrinked image is dangerous."
626
627         if d.yesno("%s\n\nDo you really want to continue?" % msg,
628                    width=YESNO_WIDTH, defaultno=1):
629             return
630
631     wrapper = textwrap.TextWrapper(width=65)
632
633     help_title = "System Preperation Tasks"
634     sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
635
636     if 'exec_syspreps' not in session:
637         session['exec_syspreps'] = []
638
639     all_syspreps = image_os.list_syspreps()
640     # Only give the user the choice between syspreps that have not ran yet
641     syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
642
643     if len(syspreps) == 0:
644         d.msgbox("No system preparation task available to run!",
645                  title="System Preperation", width=MSGBOX_WIDTH)
646         return
647
648     while 1:
649         choices = []
650         index = 0
651         for sysprep in syspreps:
652             name, descr = image_os.sysprep_info(sysprep)
653             display_name = name.replace('-', ' ').capitalize()
654             sysprep_help += "%s\n" % display_name
655             sysprep_help += "%s\n" % ('-' * len(display_name))
656             sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
657             enabled = 1 if sysprep.enabled else 0
658             choices.append((str(index + 1), display_name, enabled))
659             index += 1
660
661         (code, tags) = d.checklist(
662             "Please choose which system preperation tasks you would like to "
663             "run on the image. Press <Help> to see details about the system "
664             "preperation tasks.", title="Run system preperation tasks",
665             choices=choices, width=70, ok_label="Run", help_button=1)
666
667         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
668             return False
669         elif code == d.DIALOG_HELP:
670             d.scrollbox(sysprep_help, width=HELP_WIDTH)
671         elif code == d.DIALOG_OK:
672             # Enable selected syspreps and disable the rest
673             for i in range(len(syspreps)):
674                 if str(i + 1) in tags:
675                     image_os.enable_sysprep(syspreps[i])
676                     session['exec_syspreps'].append(syspreps[i])
677                 else:
678                     image_os.disable_sysprep(syspreps[i])
679
680             infobox = InfoBoxOutput(d, "Image Configuration")
681             try:
682                 dev = session['device']
683                 dev.out.add(infobox)
684                 try:
685                     dev.mount(readonly=False)
686                     try:
687                         # The checksum is invalid. We have mounted the image rw
688                         if 'checksum' in session:
689                             del session['checksum']
690
691                         # Monitor the metadata changes during syspreps
692                         with metadata_monitor(session, image_os.meta):
693                             image_os.do_sysprep()
694                             infobox.finalize()
695
696                         # Disable syspreps that have ran
697                         for sysprep in session['exec_syspreps']:
698                             image_os.disable_sysprep(sysprep)
699                     finally:
700                         dev.umount()
701                 finally:
702                     dev.out.remove(infobox)
703             finally:
704                 infobox.cleanup()
705             break
706     return True
707
708
709 def shrink(session):
710     d = session['dialog']
711     dev = session['device']
712
713     shrinked = 'shrinked' in session and session['shrinked']
714
715     if shrinked:
716         d.msgbox("The image is already shrinked!", title="Image Shrinking",
717                  width=MSGBOX_WIDTH)
718         return True
719
720     msg = "This operation will shrink the last partition of the image to " \
721           "reduce the total image size. If the last partition is a swap " \
722           "partition, then this partition is removed and the partition " \
723           "before that is shrinked. The removed swap partition will be " \
724           "recreated during image deployment."
725
726     if not d.yesno("%s\n\nDo you want to continue?" % msg, width=70,
727                    height=12, title="Image Shrinking"):
728         with metadata_monitor(session, dev.meta):
729             infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
730             dev.out.add(infobox)
731             try:
732                 dev.shrink()
733                 infobox.finalize()
734             finally:
735                 dev.out.remove(infobox)
736
737         session['shrinked'] = True
738         update_background_title(session)
739     else:
740         return False
741
742     return True
743
744
745 def customization_menu(session):
746     d = session['dialog']
747
748     choices = [("Sysprep", "Run various image preperation tasks"),
749                ("Shrink", "Shrink image"),
750                ("View/Modify", "View/Modify image properties"),
751                ("Delete", "Delete image properties"),
752                ("Exclude", "Exclude various deployment tasks from running")]
753
754     default_item = 0
755
756     actions = {"Sysprep": sysprep,
757                "Shrink": shrink,
758                "View/Modify": modify_properties,
759                "Delete": delete_properties,
760                "Exclude": exclude_tasks}
761     while 1:
762         (code, choice) = d.menu(
763             text="Choose one of the following or press <Back> to exit.",
764             width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
765             menu_height=len(choices), default_item=choices[default_item][0],
766             title="Image Customization Menu")
767
768         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
769             break
770         elif choice in actions:
771             default_item = [entry[0] for entry in choices].index(choice)
772             if actions[choice](session):
773                 default_item = (default_item + 1) % len(choices)
774
775
776 def main_menu(session):
777     d = session['dialog']
778     dev = session['device']
779
780     update_background_title(session)
781
782     choices = [("Customize", "Customize image & ~okeanos deployment options"),
783                ("Register", "Register image to ~okeanos"),
784                ("Extract", "Dump image to local file system"),
785                ("Reset", "Reset everything and start over again"),
786                ("Help", "Get help for using snf-image-creator")]
787
788     default_item = "Customize"
789
790     actions = {"Customize": customization_menu, "Register": kamaki_menu,
791                "Extract": extract_image}
792     while 1:
793         (code, choice) = d.menu(
794             text="Choose one of the following or press <Exit> to exit.",
795             width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
796             default_item=default_item, menu_height=len(choices),
797             title="Image Creator for ~okeanos (snf-image-creator version %s)" %
798                   version)
799
800         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
801             if confirm_exit(d):
802                 break
803         elif choice == "Reset":
804             if confirm_reset(d):
805                 d.infobox("Resetting snf-image-creator. Please wait...",
806                           width=INFOBOX_WIDTH)
807                 raise Reset
808         elif choice in actions:
809             actions[choice](session)
810
811
812 def image_creator(d, media, out):
813
814     d.setBackgroundTitle('snf-image-creator')
815
816     gauge = GaugeOutput(d, "Initialization", "Initializing...")
817     out.add(gauge)
818     disk = Disk(media, out)
819
820     def signal_handler(signum, frame):
821         gauge.cleanup()
822         disk.cleanup()
823
824     signal.signal(signal.SIGINT, signal_handler)
825     try:
826         snapshot = disk.snapshot()
827         dev = disk.get_device(snapshot)
828
829         metadata = {}
830         for (key, value) in dev.meta.items():
831             metadata[str(key)] = str(value)
832
833         dev.mount(readonly=True)
834         out.output("Collecting image metadata...")
835         cls = os_cls(dev.distro, dev.ostype)
836         image_os = cls(dev.root, dev.g, out)
837         dev.umount()
838
839         for (key, value) in image_os.meta.items():
840             metadata[str(key)] = str(value)
841
842         out.success("done")
843         gauge.cleanup()
844         out.remove(gauge)
845
846         # Make sure the signal handler does not call gauge.cleanup again
847         def dummy(self):
848             pass
849         gauge.cleanup = type(GaugeOutput.cleanup)(dummy, gauge, GaugeOutput)
850
851         session = {"dialog": d,
852                    "disk": disk,
853                    "snapshot": snapshot,
854                    "device": dev,
855                    "image_os": image_os,
856                    "metadata": metadata}
857
858         msg = "snf-image-creator detected a %s system on the input media. " \
859               "Would you like to run a wizards to assists you through the " \
860               "image creation process?\n\nChoose <Yes> to run the wizard, " \
861               "<No> to run the snf-image-creator in expert mode or press " \
862               "ESC to quit the program." \
863               % (dev.ostype if dev.ostype == dev.distro else "%s (%s)" %
864                  (dev.ostype, dev.distro))
865
866         update_background_title(session)
867
868         while True:
869             code = d.yesno(msg, width=YESNO_WIDTH, height=12)
870             if code == d.DIALOG_OK:
871                 if wizard(session):
872                     break
873             elif code == d.DIALOG_CANCEL:
874                 main_menu(session)
875                 break
876
877             if confirm_exit(d):
878                 break
879
880         d.infobox("Thank you for using snf-image-creator. Bye", width=53)
881     finally:
882         disk.cleanup()
883
884     return 0
885
886
887 def select_file(d, media):
888     root = os.sep
889     while 1:
890         if media is not None:
891             if not os.path.exists(media):
892                 d.msgbox("The file `%s' you choose does not exist." % media,
893                          width=MSGBOX_WIDTH)
894             else:
895                 break
896
897         (code, media) = d.fselect(root, 10, 50,
898                                   title="Please select input media")
899         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
900             if confirm_exit(d, "You canceled the media selection dialog box."):
901                 sys.exit(0)
902             else:
903                 media = None
904                 continue
905
906     return media
907
908
909 def main():
910
911     d = dialog.Dialog(dialog="dialog")
912
913     # Add extra button in dialog library
914     dialog._common_args_syntax["extra_button"] = \
915         lambda enable: dialog._simple_option("--extra-button", enable)
916
917     dialog._common_args_syntax["extra_label"] = \
918         lambda string: ("--extra-label", string)
919
920     usage = "Usage: %prog [options] [<input_media>]"
921     parser = optparse.OptionParser(version=version, usage=usage)
922     parser.add_option("-l", "--logfile", type="string", dest="logfile",
923                       default=None, help="log all messages to FILE",
924                       metavar="FILE")
925
926     options, args = parser.parse_args(sys.argv[1:])
927
928     if len(args) > 1:
929         parser.error("Wrong number of arguments")
930
931     d.setBackgroundTitle('snf-image-creator')
932
933     try:
934         if os.geteuid() != 0:
935             raise FatalError("You must run %s as root" % \
936                              parser.get_prog_name())
937
938         media = select_file(d, args[0] if len(args) == 1 else None)
939
940         logfile = None
941         if options.logfile is not None:
942             try:
943                 logfile = open(options.logfile, 'w')
944             except IOError as e:
945                 raise FatalError(
946                     "Unable to open logfile `%s' for writing. Reason: %s" % \
947                     (options.logfile, e.strerror))
948         try:
949             log = SimpleOutput(False, logfile) if logfile is not None \
950                                                else Output()
951             while 1:
952                 try:
953                     out = CombinedOutput([log])
954                     out.output("Starting %s version %s..." % \
955                                (parser.get_prog_name(), version))
956                     ret = image_creator(d, media, out)
957                     sys.exit(ret)
958                 except Reset:
959                     log.output("Resetting everything...")
960                     continue
961         finally:
962             if logfile is not None:
963                 logfile.close()
964     except FatalError as e:
965         msg = textwrap.fill(str(e), width=70)
966         d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
967         sys.exit(1)
968
969 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :