Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_menu.py @ 71b0ab28

History | View | Annotate | Download (25.3 kB)

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, FatalError
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
    """Monitors image metadata chages"""
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
    """Upload the image to pithos+"""
112
    d = session["dialog"]
113
    image = session['image']
114
    meta = session['metadata']
115
    size = image.size
116

    
117
    if "account" not in session:
118
        d.msgbox("You need to provide your ~okeanos credentials before you "
119
                 "can upload images to pithos+", width=SMALL_WIDTH)
120
        return False
121

    
122
    while 1:
123
        if 'upload' in session:
124
            init = session['upload']
125
        elif 'OS' in meta:
126
            init = "%s.diskdump" % meta['OS']
127
        else:
128
            init = ""
129
        (code, answer) = d.inputbox("Please provide a filename:", init=init,
130
                                    width=WIDTH)
131

    
132
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
133
            return False
134

    
135
        filename = answer.strip()
136
        if len(filename) == 0:
137
            d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
138
            continue
139

    
140
        kamaki = Kamaki(session['account'], None)
141
        overwrite = []
142
        for f in (filename, "%s.md5sum" % filename, "%s.meta" % filename):
143
            if kamaki.object_exists(f):
144
                overwrite.append(f)
145

    
146
        if len(overwrite) > 0:
147
            if d.yesno("The following pithos object(s) already exist(s):\n"
148
                       "%s\nDo you want to overwrite them?" %
149
                       "\n".join(overwrite), width=WIDTH, defaultno=1):
150
                continue
151

    
152
        session['upload'] = filename
153
        break
154

    
155
    gauge = GaugeOutput(d, "Image Upload", "Uploading...")
156
    try:
157
        out = image.out
158
        out.add(gauge)
159
        kamaki.out = out
160
        try:
161
            if 'checksum' not in session:
162
                md5 = MD5(out)
163
                session['checksum'] = md5.compute(image.device, size)
164

    
165
            try:
166
                # Upload image file
167
                with open(image.device, 'rb') as f:
168
                    session["pithos_uri"] = \
169
                        kamaki.upload(f, size, filename,
170
                                      "Calculating block hashes",
171
                                      "Uploading missing blocks")
172
                # Upload md5sum file
173
                out.output("Uploading md5sum file...")
174
                md5str = "%s %s\n" % (session['checksum'], filename)
175
                kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
176
                              remote_path="%s.md5sum" % filename)
177
                out.success("done")
178

    
179
            except ClientError as e:
180
                d.msgbox("Error in pithos+ client: %s" % e.message,
181
                         title="Pithos+ Client Error", width=SMALL_WIDTH)
182
                if 'pithos_uri' in session:
183
                    del session['pithos_uri']
184
                return False
185
        finally:
186
            out.remove(gauge)
187
    finally:
188
        gauge.cleanup()
189

    
190
    d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
191
             width=SMALL_WIDTH)
192

    
193
    return True
194

    
195

    
196
def register_image(session):
197
    """Register image with cyclades"""
198
    d = session["dialog"]
199

    
200
    is_public = False
201

    
202
    if "account" not in session:
203
        d.msgbox("You need to provide your ~okeanos credentians before you "
204
                 "can register an images with cyclades", width=SMALL_WIDTH)
205
        return False
206

    
207
    if "pithos_uri" not in session:
208
        d.msgbox("You need to upload the image to pithos+ before you can "
209
                 "register it with cyclades", width=SMALL_WIDTH)
210
        return False
211

    
212
    while 1:
213
        (code, answer) = d.inputbox("Please provide a registration name:",
214
                                    width=WIDTH)
215
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
216
            return False
217

    
218
        name = answer.strip()
219
        if len(name) == 0:
220
            d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
221
            continue
222

    
223
        ret = d.yesno("Make the image public?\\nA public image is accessible "
224
                      "by every user of the service.", defaultno=1,
225
                      width=WIDTH)
226
        if ret not in (0, 1):
227
            continue
228

    
229
        is_public = True if ret == 0 else False
230

    
231
        break
232

    
233
    metadata = {}
234
    metadata.update(session['metadata'])
235
    if 'task_metadata' in session:
236
        for key in session['task_metadata']:
237
            metadata[key] = 'yes'
238

    
239
    img_type = "public" if is_public else "private"
240
    gauge = GaugeOutput(d, "Image Registration", "Registering image...")
241
    try:
242
        out = session['image'].out
243
        out.add(gauge)
244
        try:
245
            try:
246
                out.output("Registering %s image with Cyclades..." % img_type)
247
                kamaki = Kamaki(session['account'], out)
248
                kamaki.register(name, session['pithos_uri'], metadata,
249
                                is_public)
250
                out.success('done')
251
                # Upload metadata file
252
                out.output("Uploading metadata file...")
253
                metastring = extract_metadata_string(session)
254
                kamaki.upload(StringIO.StringIO(metastring),
255
                              size=len(metastring),
256
                              remote_path="%s.meta" % session['upload'])
257
                out.success("done")
258
                if is_public:
259
                    out.output("Sharing metadata and md5sum files...")
260
                    kamaki.share("%s.meta" % session['upload'])
261
                    kamaki.share("%s.md5sum" % session['upload'])
262
                    out.success('done')
263
            except ClientError as e:
264
                d.msgbox("Error in pithos+ client: %s" % e.message)
265
                return False
266
        finally:
267
            out.remove(gauge)
268
    finally:
269
        gauge.cleanup()
270

    
271
    d.msgbox("%s image `%s' was successfully registered with Cyclades as `%s'"
272
             % (img_type.title(), session['upload'], name), width=SMALL_WIDTH)
273
    return True
274

    
275

    
276
def kamaki_menu(session):
277
    """Show kamaki related actions"""
278
    d = session['dialog']
279
    default_item = "Account"
280

    
281
    if 'account' not in session:
282
        token = Kamaki.get_token()
283
        if token:
284
            session['account'] = Kamaki.get_account(token)
285
            if not session['account']:
286
                del session['account']
287
                Kamaki.save_token('')  # The token was not valid. Remove it
288

    
289
    while 1:
290
        account = session["account"]['username'] if "account" in session else \
291
            "<none>"
292
        upload = session["upload"] if "upload" in session else "<none>"
293

    
294
        choices = [("Account", "Change your ~okeanos account: %s" % account),
295
                   ("Upload", "Upload image to pithos+"),
296
                   ("Register", "Register the image to cyclades: %s" % upload)]
297

    
298
        (code, choice) = d.menu(
299
            text="Choose one of the following or press <Back> to go back.",
300
            width=WIDTH, choices=choices, cancel="Back", height=13,
301
            menu_height=5, default_item=default_item,
302
            title="Image Registration Menu")
303

    
304
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
305
            return False
306

    
307
        if choice == "Account":
308
            default_item = "Account"
309
            (code, answer) = d.inputbox(
310
                "Please provide your ~okeanos authentication token:",
311
                init=session["account"]['auth_token'] if "account" in session
312
                else '', width=WIDTH)
313
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
314
                continue
315
            if len(answer) == 0 and "account" in session:
316
                    del session["account"]
317
            else:
318
                token = answer.strip()
319
                session['account'] = Kamaki.get_account(token)
320
                if session['account'] is not None:
321
                    Kamaki.save_token(token)
322
                    default_item = "Upload"
323
                else:
324
                    del session['account']
325
                    d.msgbox("The token you provided is not valid!",
326
                             width=SMALL_WIDTH)
327
        elif choice == "Upload":
328
            if upload_image(session):
329
                default_item = "Register"
330
            else:
331
                default_item = "Upload"
332
        elif choice == "Register":
333
            if register_image(session):
334
                return True
335
            else:
336
                default_item = "Register"
337

    
338

    
339
def add_property(session):
340
    """Add a new property to the image"""
341
    d = session['dialog']
342

    
343
    while 1:
344
        (code, answer) = d.inputbox("Please provide a name for a new image"
345
                                    " property:", width=WIDTH)
346
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
347
            return False
348

    
349
        name = answer.strip()
350
        if len(name) == 0:
351
            d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
352
            continue
353

    
354
        break
355

    
356
    while 1:
357
        (code, answer) = d.inputbox("Please provide a value for image "
358
                                    "property %s" % name, width=WIDTH)
359
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
360
            return False
361

    
362
        value = answer.strip()
363
        if len(value) == 0:
364
            d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
365
            continue
366

    
367
        break
368

    
369
    session['metadata'][name] = value
370

    
371
    return True
372

    
373

    
374
def modify_properties(session):
375
    """Modify an existing image property"""
376
    d = session['dialog']
377

    
378
    while 1:
379
        choices = []
380
        for (key, val) in session['metadata'].items():
381
            choices.append((str(key), str(val)))
382

    
383
        (code, choice) = d.menu(
384
            "In this menu you can edit existing image properties or add new "
385
            "ones. Be careful! Most properties have special meaning and "
386
            "alter the image deployment behaviour. Press <HELP> to see more "
387
            "information about image properties. Press <BACK> when done.",
388
            height=18, width=WIDTH, choices=choices, menu_height=10,
389
            ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
390
            help_button=1, title="Image Properties")
391

    
392
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
393
            return True
394
        # Edit button
395
        elif code == d.DIALOG_OK:
396
            (code, answer) = d.inputbox("Please provide a new value for the "
397
                                        "image property with name `%s':" %
398
                                        choice,
399
                                        init=session['metadata'][choice],
400
                                        width=WIDTH)
401
            if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
402
                value = answer.strip()
403
                if len(value) == 0:
404
                    d.msgbox("Value cannot be empty!")
405
                    continue
406
                else:
407
                    session['metadata'][choice] = value
408
        # ADD button
409
        elif code == d.DIALOG_EXTRA:
410
            add_property(session)
411
        elif code == 'help':
412
            help_file = get_help_file("image_properties")
413
            assert os.path.exists(help_file)
414
            d.textbox(help_file, title="Image Properties", width=70, height=40)
415

    
416

    
417
def delete_properties(session):
418
    """Delete an image property"""
419
    d = session['dialog']
420

    
421
    choices = []
422
    for (key, val) in session['metadata'].items():
423
        choices.append((key, "%s" % val, 0))
424

    
425
    (code, to_delete) = d.checklist("Choose which properties to delete:",
426
                                    choices=choices, width=WIDTH)
427

    
428
    # If the user exits with ESC or CANCEL, the returned tag list is empty.
429
    for i in to_delete:
430
        del session['metadata'][i]
431

    
432
    cnt = len(to_delete)
433
    if cnt > 0:
434
        d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
435
        return True
436
    else:
437
        return False
438

    
439

    
440
def exclude_tasks(session):
441
    """Exclude specific tasks from running during image deployment"""
442
    d = session['dialog']
443

    
444
    index = 0
445
    displayed_index = 1
446
    choices = []
447
    mapping = {}
448
    if 'excluded_tasks' not in session:
449
        session['excluded_tasks'] = []
450

    
451
    if -1 in session['excluded_tasks']:
452
        if not d.yesno("Image deployment configuration is disabled. "
453
                       "Do you wish to enable it?", width=SMALL_WIDTH):
454
            session['excluded_tasks'].remove(-1)
455
        else:
456
            return False
457

    
458
    for (msg, task, osfamily) in CONFIGURATION_TASKS:
459
        if session['metadata']['OSFAMILY'] in osfamily:
460
            checked = 1 if index in session['excluded_tasks'] else 0
461
            choices.append((str(displayed_index), msg, checked))
462
            mapping[displayed_index] = index
463
            displayed_index += 1
464
        index += 1
465

    
466
    while 1:
467
        (code, tags) = d.checklist(
468
            text="Please choose which configuration tasks you would like to "
469
                 "prevent from running during image deployment. "
470
                 "Press <No Config> to supress any configuration. "
471
                 "Press <Help> for more help on the image deployment "
472
                 "configuration tasks.",
473
            choices=choices, height=19, list_height=8, width=WIDTH,
474
            help_button=1, extra_button=1, extra_label="No Config",
475
            title="Exclude Configuration Tasks")
476

    
477
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
478
            return False
479
        elif code == d.DIALOG_HELP:
480
            help_file = get_help_file("configuration_tasks")
481
            assert os.path.exists(help_file)
482
            d.textbox(help_file, title="Configuration Tasks",
483
                      width=70, height=40)
484
        # No Config button
485
        elif code == d.DIALOG_EXTRA:
486
            session['excluded_tasks'] = [-1]
487
            session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
488
            break
489
        elif code == d.DIALOG_OK:
490
            session['excluded_tasks'] = []
491
            for tag in tags:
492
                session['excluded_tasks'].append(mapping[int(tag)])
493

    
494
            exclude_metadata = []
495
            for task in session['excluded_tasks']:
496
                exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
497

    
498
            session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
499
                                           exclude_metadata)
500
            break
501

    
502
    return True
503

    
504

    
505
def sysprep(session):
506
    """Perform various system preperation tasks on the image"""
507
    d = session['dialog']
508
    image = session['image']
509

    
510
    # Is the image already shrinked?
511
    if 'shrinked' in session and session['shrinked']:
512
        msg = "It seems you have shrinked the image. Running system " \
513
              "preparation tasks on a shrinked image is dangerous."
514

    
515
        if d.yesno("%s\n\nDo you really want to continue?" % msg,
516
                   width=SMALL_WIDTH, defaultno=1):
517
            return
518

    
519
    wrapper = textwrap.TextWrapper(width=WIDTH - 5)
520

    
521
    help_title = "System Preperation Tasks"
522
    sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
523

    
524
    syspreps = image.os.list_syspreps()
525

    
526
    if len(syspreps) == 0:
527
        d.msgbox("No system preparation task available to run!",
528
                 title="System Preperation", width=SMALL_WIDTH)
529
        return
530

    
531
    while 1:
532
        choices = []
533
        index = 0
534
        for sysprep in syspreps:
535
            name, descr = image.os.sysprep_info(sysprep)
536
            display_name = name.replace('-', ' ').capitalize()
537
            sysprep_help += "%s\n" % display_name
538
            sysprep_help += "%s\n" % ('-' * len(display_name))
539
            sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
540
            enabled = 1 if sysprep.enabled else 0
541
            choices.append((str(index + 1), display_name, enabled))
542
            index += 1
543

    
544
        (code, tags) = d.checklist(
545
            "Please choose which system preparation tasks you would like to "
546
            "run on the image. Press <Help> to see details about the system "
547
            "preparation tasks.", title="Run system preparation tasks",
548
            choices=choices, width=70, ok_label="Run", help_button=1)
549

    
550
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
551
            return False
552
        elif code == d.DIALOG_HELP:
553
            d.scrollbox(sysprep_help, width=WIDTH)
554
        elif code == d.DIALOG_OK:
555
            # Enable selected syspreps and disable the rest
556
            for i in range(len(syspreps)):
557
                if str(i + 1) in tags:
558
                    image.os.enable_sysprep(syspreps[i])
559
                else:
560
                    image.os.disable_sysprep(syspreps[i])
561

    
562
            if len([s for s in image.os.list_syspreps() if s.enabled]) == 0:
563
                d.msgbox("No system preperation task is selected!",
564
                         title="System Preperation", width=SMALL_WIDTH)
565
                continue
566

    
567
            infobox = InfoBoxOutput(d, "Image Configuration")
568
            try:
569
                image.out.add(infobox)
570
                try:
571
                    # The checksum is invalid. We have mounted the image rw
572
                    if 'checksum' in session:
573
                        del session['checksum']
574

    
575
                    # Monitor the metadata changes during syspreps
576
                    with MetadataMonitor(session, image.os.meta):
577
                        try:
578
                            image.os.do_sysprep()
579
                            infobox.finalize()
580
                        except FatalError as e:
581
                            title = "System Preparation"
582
                            d.msgbox("System Preparation failed: %s" % e,
583
                                     title=title, width=SMALL_WIDTH)
584
                finally:
585
                    image.out.remove(infobox)
586
            finally:
587
                infobox.cleanup()
588
            break
589
    return True
590

    
591

    
592
def shrink(session):
593
    """Shrink the image"""
594
    d = session['dialog']
595
    image = session['image']
596

    
597
    shrinked = 'shrinked' in session and session['shrinked']
598

    
599
    if shrinked:
600
        d.msgbox("The image is already shrinked!", title="Image Shrinking",
601
                 width=SMALL_WIDTH)
602
        return True
603

    
604
    msg = "This operation will shrink the last partition of the image to " \
605
          "reduce the total image size. If the last partition is a swap " \
606
          "partition, then this partition is removed and the partition " \
607
          "before that is shrinked. The removed swap partition will be " \
608
          "recreated during image deployment."
609

    
610
    if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH,
611
                   height=12, title="Image Shrinking"):
612
        with MetadataMonitor(session, image.meta):
613
            infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
614
            image.out.add(infobox)
615
            try:
616
                image.shrink()
617
                infobox.finalize()
618
            finally:
619
                image.out.remove(infobox)
620

    
621
        session['shrinked'] = True
622
        update_background_title(session)
623
    else:
624
        return False
625

    
626
    return True
627

    
628

    
629
def customization_menu(session):
630
    """Show image customization menu"""
631
    d = session['dialog']
632

    
633
    choices = [("Sysprep", "Run various image preparation tasks"),
634
               ("Shrink", "Shrink image"),
635
               ("View/Modify", "View/Modify image properties"),
636
               ("Delete", "Delete image properties"),
637
               ("Exclude", "Exclude various deployment tasks from running")]
638

    
639
    default_item = 0
640

    
641
    actions = {"Sysprep": sysprep,
642
               "Shrink": shrink,
643
               "View/Modify": modify_properties,
644
               "Delete": delete_properties,
645
               "Exclude": exclude_tasks}
646
    while 1:
647
        (code, choice) = d.menu(
648
            text="Choose one of the following or press <Back> to exit.",
649
            width=WIDTH, choices=choices, cancel="Back", height=13,
650
            menu_height=len(choices), default_item=choices[default_item][0],
651
            title="Image Customization Menu")
652

    
653
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
654
            break
655
        elif choice in actions:
656
            default_item = [entry[0] for entry in choices].index(choice)
657
            if actions[choice](session):
658
                default_item = (default_item + 1) % len(choices)
659

    
660

    
661
def main_menu(session):
662
    """Show the main menu of the program"""
663
    d = session['dialog']
664

    
665
    update_background_title(session)
666

    
667
    choices = [("Customize", "Customize image & ~okeanos deployment options"),
668
               ("Register", "Register image to ~okeanos"),
669
               ("Extract", "Dump image to local file system"),
670
               ("Reset", "Reset everything and start over again"),
671
               ("Help", "Get help for using snf-image-creator")]
672

    
673
    default_item = "Customize"
674

    
675
    actions = {"Customize": customization_menu, "Register": kamaki_menu,
676
               "Extract": extract_image}
677
    while 1:
678
        (code, choice) = d.menu(
679
            text="Choose one of the following or press <Exit> to exit.",
680
            width=WIDTH, choices=choices, cancel="Exit", height=13,
681
            default_item=default_item, menu_height=len(choices),
682
            title="Image Creator for ~okeanos (snf-image-creator version %s)" %
683
                  version)
684

    
685
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
686
            if confirm_exit(d):
687
                break
688
        elif choice == "Reset":
689
            if confirm_reset(d):
690
                d.infobox("Resetting snf-image-creator. Please wait...",
691
                          width=SMALL_WIDTH)
692
                raise Reset
693
        elif choice == "Help":
694
            d.msgbox("For help, check the online documentation:\n\nhttp://www"
695
                     ".synnefo.org/docs/snf-image-creator/latest/",
696
                     width=WIDTH, title="Help")
697
        elif choice in actions:
698
            actions[choice](session)
699

    
700
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :