Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_menu.py @ 63af9c37

History | View | Annotate | Download (30.2 kB)

1
# -*- coding: utf-8 -*-
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
"""This module implements the "expert" mode of the dialog-based version of
37
snf-image-creator.
38
"""
39

    
40
import os
41
import textwrap
42
import StringIO
43
import json
44

    
45
from image_creator import __version__ as version
46
from image_creator.util import MD5, FatalError
47
from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
48
from image_creator.kamaki_wrapper import Kamaki, ClientError
49
from image_creator.help import get_help_file
50
from image_creator.dialog_util import SMALL_WIDTH, WIDTH, \
51
    update_background_title, confirm_reset, confirm_exit, Reset, \
52
    extract_image, extract_metadata_string, add_cloud, edit_cloud
53

    
54
CONFIGURATION_TASKS = [
55
    ("Partition table manipulation", ["FixPartitionTable"],
56
        ["linux", "windows"]),
57
    ("File system resize",
58
        ["FilesystemResizeUnmounted", "FilesystemResizeMounted"],
59
        ["linux", "windows"]),
60
    ("Swap partition configuration", ["AddSwap"], ["linux"]),
61
    ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]),
62
    ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"],
63
        ["windows"]),
64
    ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]),
65
    ("Hostname/Computer Name assignment", ["AssignHostname"],
66
        ["windows", "linux"]),
67
    ("Password change", ["ChangePassword"], ["windows", "linux"]),
68
    ("File injection", ["EnforcePersonality"], ["windows", "linux"])
69
]
70

    
71

    
72
class MetadataMonitor(object):
73
    """Monitors image metadata chages"""
74
    def __init__(self, session, meta):
75
        self.session = session
76
        self.meta = meta
77

    
78
    def __enter__(self):
79
        self.old = {}
80
        for (k, v) in self.meta.items():
81
            self.old[k] = v
82

    
83
    def __exit__(self, type, value, traceback):
84
        d = self.session['dialog']
85

    
86
        altered = {}
87
        added = {}
88

    
89
        for (k, v) in self.meta.items():
90
            if k not in self.old:
91
                added[k] = v
92
            elif self.old[k] != v:
93
                altered[k] = v
94

    
95
        if not (len(added) or len(altered)):
96
            return
97

    
98
        msg = "The last action has changed some image properties:\n\n"
99
        if len(added):
100
            msg += "New image properties:\n"
101
            for (k, v) in added.items():
102
                msg += '    %s: "%s"\n' % (k, v)
103
            msg += "\n"
104
        if len(altered):
105
            msg += "Updated image properties:\n"
106
            for (k, v) in altered.items():
107
                msg += '    %s: "%s" -> "%s"\n' % (k, self.old[k], v)
108
            msg += "\n"
109

    
110
        self.session['metadata'].update(added)
111
        self.session['metadata'].update(altered)
112
        d.msgbox(msg, title="Image Property Changes", width=SMALL_WIDTH)
113

    
114

    
115
def upload_image(session):
116
    """Upload the image to the storage service"""
117
    d = session["dialog"]
118
    image = session['image']
119
    meta = session['metadata']
120
    size = image.size
121

    
122
    if "account" not in session:
123
        d.msgbox("You need to select a valid cloud before you can upload "
124
                 "images to it", width=SMALL_WIDTH)
125
        return False
126

    
127
    while 1:
128
        if 'upload' in session:
129
            init = session['upload']
130
        elif 'OS' in meta:
131
            init = "%s.diskdump" % meta['OS']
132
        else:
133
            init = ""
134
        (code, answer) = d.inputbox("Please provide a filename:", init=init,
135
                                    width=WIDTH)
136

    
137
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
138
            return False
139

    
140
        filename = answer.strip()
141
        if len(filename) == 0:
142
            d.msgbox("Filename cannot be empty", width=SMALL_WIDTH)
143
            continue
144

    
145
        kamaki = Kamaki(session['account'], None)
146
        overwrite = []
147
        for f in (filename, "%s.md5sum" % filename, "%s.meta" % filename):
148
            if kamaki.object_exists(f):
149
                overwrite.append(f)
150

    
151
        if len(overwrite) > 0:
152
            if d.yesno("The following storage service object(s) already "
153
                       "exist(s):\n%s\nDo you want to overwrite them?" %
154
                       "\n".join(overwrite), width=WIDTH, defaultno=1):
155
                continue
156

    
157
        session['upload'] = filename
158
        break
159

    
160
    gauge = GaugeOutput(d, "Image Upload", "Uploading...")
161
    try:
162
        out = image.out
163
        out.add(gauge)
164
        kamaki.out = out
165
        try:
166
            if 'checksum' not in session:
167
                md5 = MD5(out)
168
                session['checksum'] = md5.compute(image.device, size)
169

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

    
184
            except ClientError as e:
185
                d.msgbox(
186
                    "Error in storage service client: %s" % e.message,
187
                    title="Storage Service Client Error", width=SMALL_WIDTH)
188
                if 'pithos_uri' in session:
189
                    del session['pithos_uri']
190
                return False
191
        finally:
192
            out.remove(gauge)
193
    finally:
194
        gauge.cleanup()
195

    
196
    d.msgbox("Image file `%s' was successfully uploaded" % filename,
197
             width=SMALL_WIDTH)
198

    
199
    return True
200

    
201

    
202
def register_image(session):
203
    """Register image with the compute service"""
204
    d = session["dialog"]
205

    
206
    is_public = False
207

    
208
    if "account" not in session:
209
        d.msgbox("You need to select a valid cloud before you "
210
                 "can register an images with it", width=SMALL_WIDTH)
211
        return False
212

    
213
    if "pithos_uri" not in session:
214
        d.msgbox("You need to upload the image to the cloud before you can "
215
                 "register it", width=SMALL_WIDTH)
216
        return False
217

    
218
    while 1:
219
        (code, answer) = d.inputbox("Please provide a registration name:",
220
                                    width=WIDTH)
221
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
222
            return False
223

    
224
        name = answer.strip()
225
        if len(name) == 0:
226
            d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH)
227
            continue
228

    
229
        ret = d.yesno("Make the image public?\\nA public image is accessible "
230
                      "by every user of the service.", defaultno=1,
231
                      width=WIDTH)
232
        if ret not in (0, 1):
233
            continue
234

    
235
        is_public = True if ret == 0 else False
236

    
237
        break
238

    
239
    metadata = {}
240
    metadata.update(session['metadata'])
241
    if 'task_metadata' in session:
242
        for key in session['task_metadata']:
243
            metadata[key] = 'yes'
244

    
245
    img_type = "public" if is_public else "private"
246
    gauge = GaugeOutput(d, "Image Registration", "Registering image...")
247
    try:
248
        out = session['image'].out
249
        out.add(gauge)
250
        try:
251
            try:
252
                out.output("Registering %s image with the cloud..." % img_type)
253
                kamaki = Kamaki(session['account'], out)
254
                result = kamaki.register(name, session['pithos_uri'], metadata,
255
                                         is_public)
256
                out.success('done')
257
                # Upload metadata file
258
                out.output("Uploading metadata file...")
259
                metastring = unicode(json.dumps(result, ensure_ascii=False))
260
                kamaki.upload(StringIO.StringIO(metastring),
261
                              size=len(metastring),
262
                              remote_path="%s.meta" % session['upload'])
263
                out.success("done")
264
                if is_public:
265
                    out.output("Sharing metadata and md5sum files...")
266
                    kamaki.share("%s.meta" % session['upload'])
267
                    kamaki.share("%s.md5sum" % session['upload'])
268
                    out.success('done')
269
            except ClientError as e:
270
                d.msgbox("Error in storage service client: %s" % e.message)
271
                return False
272
        finally:
273
            out.remove(gauge)
274
    finally:
275
        gauge.cleanup()
276

    
277
    d.msgbox("%s image `%s' was successfully registered with the cloud as `%s'"
278
             % (img_type.title(), session['upload'], name), width=SMALL_WIDTH)
279
    return True
280

    
281

    
282
def modify_clouds(session):
283
    """Modify existing cloud accounts"""
284
    d = session['dialog']
285

    
286
    while 1:
287
        clouds = Kamaki.get_clouds()
288
        if not len(clouds):
289
            if not add_cloud(session):
290
                break
291
            continue
292

    
293
        choices = []
294
        for (name, cloud) in clouds.items():
295
            descr = cloud['description'] if 'description' in cloud else ''
296
            choices.append((name, descr))
297

    
298
        (code, choice) = d.menu(
299
            "In this menu you can edit existing cloud accounts or add new "
300
            " ones. Press <Edit> to edit an existing account or <Add> to add "
301
            " a new one. Press <Back> or hit <ESC> when done.", height=18,
302
            width=WIDTH, choices=choices, menu_height=10, ok_label="Edit",
303
            extra_button=1, extra_label="Add", cancel="Back", help_button=1,
304
            title="Clouds")
305

    
306
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
307
            return True
308
        elif code == d.DIALOG_OK:  # Edit button
309
            edit_cloud(session, choice)
310
        elif code == d.DIALOG_EXTRA:  # Add button
311
            add_cloud(session)
312

    
313

    
314
def delete_clouds(session):
315
    """Delete existing cloud accounts"""
316
    d = session['dialog']
317

    
318
    choices = []
319
    for (name, cloud) in Kamaki.get_clouds().items():
320
        descr = cloud['description'] if 'description' in cloud else ''
321
        choices.append((name, descr, 0))
322

    
323
    if len(choices) == 0:
324
        d.msgbox("No available clouds to delete!", width=SMALL_WIDTH)
325
        return True
326

    
327
    (code, to_delete) = d.checklist("Choose which cloud accounts to delete:",
328
                                    choices=choices, width=WIDTH)
329

    
330
    if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
331
        return False
332

    
333
    if not len(to_delete):
334
        d.msgbox("Nothing selected!", width=SMALL_WIDTH)
335
        return False
336

    
337
    if not d.yesno("Are you sure you want to remove the selected cloud "
338
                   "accounts?", width=WIDTH, defaultno=1):
339
        for i in to_delete:
340
            Kamaki.remove_cloud(i)
341
            if 'cloud' in session and session['cloud'] == i:
342
                del session['cloud']
343
                if 'account' in session:
344
                    del session['account']
345
    else:
346
        return False
347

    
348
    d.msgbox("%d cloud accounts were deleted." % len(to_delete),
349
             width=SMALL_WIDTH)
350
    return True
351

    
352

    
353
def kamaki_menu(session):
354
    """Show kamaki related actions"""
355
    d = session['dialog']
356
    default_item = "Cloud"
357

    
358
    if 'cloud' not in session:
359
        cloud = Kamaki.get_default_cloud_name()
360
        if cloud:
361
            session['cloud'] = cloud
362
            session['account'] = Kamaki.get_account(cloud)
363
            if not session['account']:
364
                del session['account']
365
        else:
366
            default_item = "Add/Edit"
367

    
368
    while 1:
369
        cloud = session["cloud"] if "cloud" in session else "<none>"
370
        if 'account' not in session and 'cloud' in session:
371
            cloud += " <invalid>"
372

    
373
        upload = session["upload"] if "upload" in session else "<none>"
374

    
375
        choices = [("Add/Edit", "Add/Edit cloud accounts"),
376
                   ("Delete", "Delete existing cloud accounts"),
377
                   ("Cloud", "Select cloud account to use: %s" % cloud),
378
                   ("Upload", "Upload image to the cloud"),
379
                   ("Register", "Register image with the cloud: %s" % upload)]
380

    
381
        (code, choice) = d.menu(
382
            text="Choose one of the following or press <Back> to go back.",
383
            width=WIDTH, choices=choices, cancel="Back", height=13,
384
            menu_height=5, default_item=default_item,
385
            title="Image Registration Menu")
386

    
387
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
388
            return False
389

    
390
        if choice == "Add/Edit":
391
            if modify_clouds(session):
392
                default_item = "Cloud"
393
        elif choice == "Delete":
394
            if delete_clouds(session):
395
                if len(Kamaki.get_clouds()):
396
                    default_item = "Cloud"
397
                else:
398
                    default_time = "Add/Edit"
399
            else:
400
                default_time = "Delete"
401
        elif choice == "Cloud":
402
            default_item = "Cloud"
403
            clouds = Kamaki.get_clouds()
404
            if not len(clouds):
405
                d.msgbox("No clouds available. Please add a new cloud!",
406
                         width=SMALL_WIDTH)
407
                default_item = "Add/Edit"
408
                continue
409

    
410
            if 'cloud' not in session:
411
                session['cloud'] = clouds.keys()[0]
412

    
413
            choices = []
414
            for name, info in clouds.items():
415
                default = 1 if session['cloud'] == name else 0
416
                descr = info['description'] if 'description' in info else ""
417
                choices.append((name, descr, default))
418

    
419
            (code, answer) = d.radiolist("Please select a cloud:",
420
                                         width=WIDTH, choices=choices)
421
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
422
                continue
423
            else:
424
                session['account'] = Kamaki.get_account(answer)
425

    
426
                if session['account'] is None:  # invalid account
427
                    if not d.yesno("The cloud %s' is not valid! Would you "
428
                                   "like to edit it?" % answer, width=WIDTH):
429
                        if edit_cloud(session, answer):
430
                            session['account'] = Kamaki.get_account(answer)
431
                            Kamaki.set_default_cloud(answer)
432

    
433
                if session['account'] is not None:
434
                    session['cloud'] = answer
435
                    Kamaki.set_default_cloud(answer)
436
                    default_item = "Upload"
437
                else:
438
                    del session['account']
439
                    del session['cloud']
440
        elif choice == "Upload":
441
            if upload_image(session):
442
                default_item = "Register"
443
            else:
444
                default_item = "Upload"
445
        elif choice == "Register":
446
            if register_image(session):
447
                return True
448
            else:
449
                default_item = "Register"
450

    
451

    
452
def add_property(session):
453
    """Add a new property to the image"""
454
    d = session['dialog']
455

    
456
    while 1:
457
        (code, answer) = d.inputbox("Please provide a name for a new image"
458
                                    " property:", width=WIDTH)
459
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
460
            return False
461

    
462
        name = answer.strip()
463
        if len(name) == 0:
464
            d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
465
            continue
466

    
467
        break
468

    
469
    while 1:
470
        (code, answer) = d.inputbox("Please provide a value for image "
471
                                    "property %s" % name, width=WIDTH)
472
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
473
            return False
474

    
475
        value = answer.strip()
476
        if len(value) == 0:
477
            d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
478
            continue
479

    
480
        break
481

    
482
    session['metadata'][name] = value
483

    
484
    return True
485

    
486

    
487
def modify_properties(session):
488
    """Modify an existing image property"""
489
    d = session['dialog']
490

    
491
    while 1:
492
        choices = []
493
        for (key, val) in session['metadata'].items():
494
            choices.append((str(key), str(val)))
495

    
496
        (code, choice) = d.menu(
497
            "In this menu you can edit existing image properties or add new "
498
            "ones. Be careful! Most properties have special meaning and "
499
            "alter the image deployment behaviour. Press <HELP> to see more "
500
            "information about image properties. Press <BACK> when done.",
501
            height=18, width=WIDTH, choices=choices, menu_height=10,
502
            ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
503
            help_button=1, title="Image Properties")
504

    
505
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
506
            return True
507
        # Edit button
508
        elif code == d.DIALOG_OK:
509
            (code, answer) = d.inputbox("Please provide a new value for the "
510
                                        "image property with name `%s':" %
511
                                        choice,
512
                                        init=session['metadata'][choice],
513
                                        width=WIDTH)
514
            if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
515
                value = answer.strip()
516
                if len(value) == 0:
517
                    d.msgbox("Value cannot be empty!")
518
                    continue
519
                else:
520
                    session['metadata'][choice] = value
521
        # ADD button
522
        elif code == d.DIALOG_EXTRA:
523
            add_property(session)
524
        elif code == 'help':
525
            help_file = get_help_file("image_properties")
526
            assert os.path.exists(help_file)
527
            d.textbox(help_file, title="Image Properties", width=70, height=40)
528

    
529

    
530
def delete_properties(session):
531
    """Delete an image property"""
532
    d = session['dialog']
533

    
534
    choices = []
535
    for (key, val) in session['metadata'].items():
536
        choices.append((key, "%s" % val, 0))
537

    
538
    (code, to_delete) = d.checklist("Choose which properties to delete:",
539
                                    choices=choices, width=WIDTH)
540

    
541
    # If the user exits with ESC or CANCEL, the returned tag list is empty.
542
    for i in to_delete:
543
        del session['metadata'][i]
544

    
545
    cnt = len(to_delete)
546
    if cnt > 0:
547
        d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
548
        return True
549
    else:
550
        return False
551

    
552

    
553
def exclude_tasks(session):
554
    """Exclude specific tasks from running during image deployment"""
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=SMALL_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=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_params(session):
619

    
620
    d = session['dialog']
621
    image = session['image']
622

    
623
    available = image.os.sysprep_params
624
    needed = image.os.needed_sysprep_params()
625

    
626
    if len(needed) == 0:
627
        return True
628

    
629
    fields = []
630
    for param in needed:
631
        default = available[param.name] if param.name in available else ""
632
        fields.append(("%s: " % param.description, default, param.length))
633

    
634
    txt = "Please provide the following system preparation parameters:"
635
    code, output = d.form(txt, height=13, width=WIDTH, form_height=len(fields),
636
                          fields=fields)
637

    
638
    if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
639
        return False
640

    
641
    sysprep_params = {}
642
    for i in range(len(fields)):
643
        if needed[i].validator(output[i]):
644
            image.os.sysprep_params[needed[i].name] = output[i]
645
        else:
646
            d.msgbox("The value you provided for parameter: %s is not valid" %
647
                     name, width=SMALL_WIDTH)
648
            return False
649

    
650
    return True
651

    
652

    
653
def sysprep(session):
654
    """Perform various system preperation tasks on the image"""
655
    d = session['dialog']
656
    image = session['image']
657

    
658
    # Is the image already shrinked?
659
    if 'shrinked' in session and session['shrinked']:
660
        msg = "It seems you have shrinked the image. Running system " \
661
              "preparation tasks on a shrinked image is dangerous."
662

    
663
        if d.yesno("%s\n\nDo you really want to continue?" % msg,
664
                   width=SMALL_WIDTH, defaultno=1):
665
            return
666

    
667
    wrapper = textwrap.TextWrapper(width=WIDTH - 5)
668

    
669
    help_title = "System Preperation Tasks"
670
    sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
671

    
672
    syspreps = image.os.list_syspreps()
673

    
674
    if len(syspreps) == 0:
675
        d.msgbox("No system preparation task available to run!",
676
                 title="System Preperation", width=SMALL_WIDTH)
677
        return
678

    
679
    while 1:
680
        choices = []
681
        index = 0
682
        for sysprep in syspreps:
683
            name, descr = image.os.sysprep_info(sysprep)
684
            display_name = name.replace('-', ' ').capitalize()
685
            sysprep_help += "%s\n" % display_name
686
            sysprep_help += "%s\n" % ('-' * len(display_name))
687
            sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
688
            enabled = 1 if sysprep.enabled else 0
689
            choices.append((str(index + 1), display_name, enabled))
690
            index += 1
691

    
692
        (code, tags) = d.checklist(
693
            "Please choose which system preparation tasks you would like to "
694
            "run on the image. Press <Help> to see details about the system "
695
            "preparation tasks.", title="Run system preparation tasks",
696
            choices=choices, width=70, ok_label="Run", help_button=1)
697

    
698
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
699
            return False
700
        elif code == d.DIALOG_HELP:
701
            d.scrollbox(sysprep_help, width=WIDTH)
702
        elif code == d.DIALOG_OK:
703
            # Enable selected syspreps and disable the rest
704
            for i in range(len(syspreps)):
705
                if str(i + 1) in tags:
706
                    image.os.enable_sysprep(syspreps[i])
707
                else:
708
                    image.os.disable_sysprep(syspreps[i])
709

    
710
            if len([s for s in image.os.list_syspreps() if s.enabled]) == 0:
711
                d.msgbox("No system preperation task is selected!",
712
                         title="System Preperation", width=SMALL_WIDTH)
713
                continue
714

    
715
            if not sysprep_params(session):
716
                continue
717

    
718
            infobox = InfoBoxOutput(d, "Image Configuration")
719
            try:
720
                image.out.add(infobox)
721
                try:
722
                    # The checksum is invalid. We have mounted the image rw
723
                    if 'checksum' in session:
724
                        del session['checksum']
725

    
726
                    # Monitor the metadata changes during syspreps
727
                    with MetadataMonitor(session, image.os.meta):
728
                        try:
729
                            image.os.do_sysprep()
730
                            infobox.finalize()
731
                        except FatalError as e:
732
                            title = "System Preparation"
733
                            d.msgbox("System Preparation failed: %s" % e,
734
                                     title=title, width=SMALL_WIDTH)
735
                finally:
736
                    image.out.remove(infobox)
737
            finally:
738
                infobox.cleanup()
739
            break
740
    return True
741

    
742

    
743
def shrink(session):
744
    """Shrink the image"""
745
    d = session['dialog']
746
    image = session['image']
747

    
748
    shrinked = 'shrinked' in session and session['shrinked']
749

    
750
    if shrinked:
751
        d.msgbox("The image is already shrinked!", title="Image Shrinking",
752
                 width=SMALL_WIDTH)
753
        return True
754

    
755
    msg = "This operation will shrink the last partition of the image to " \
756
          "reduce the total image size. If the last partition is a swap " \
757
          "partition, then this partition is removed and the partition " \
758
          "before that is shrinked. The removed swap partition will be " \
759
          "recreated during image deployment."
760

    
761
    if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH,
762
                   height=12, title="Image Shrinking"):
763
        with MetadataMonitor(session, image.meta):
764
            infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
765
            image.out.add(infobox)
766
            try:
767
                image.shrink()
768
                infobox.finalize()
769
            finally:
770
                image.out.remove(infobox)
771

    
772
        session['shrinked'] = True
773
        update_background_title(session)
774
    else:
775
        return False
776

    
777
    return True
778

    
779

    
780
def customization_menu(session):
781
    """Show image customization menu"""
782
    d = session['dialog']
783

    
784
    choices = [("Sysprep", "Run various image preparation tasks"),
785
               ("Shrink", "Shrink image"),
786
               ("View/Modify", "View/Modify image properties"),
787
               ("Delete", "Delete image properties"),
788
               ("Exclude", "Exclude various deployment tasks from running")]
789

    
790
    default_item = 0
791

    
792
    actions = {"Sysprep": sysprep,
793
               "Shrink": shrink,
794
               "View/Modify": modify_properties,
795
               "Delete": delete_properties,
796
               "Exclude": exclude_tasks}
797
    while 1:
798
        (code, choice) = d.menu(
799
            text="Choose one of the following or press <Back> to exit.",
800
            width=WIDTH, choices=choices, cancel="Back", height=13,
801
            menu_height=len(choices), default_item=choices[default_item][0],
802
            title="Image Customization Menu")
803

    
804
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
805
            break
806
        elif choice in actions:
807
            default_item = [entry[0] for entry in choices].index(choice)
808
            if actions[choice](session):
809
                default_item = (default_item + 1) % len(choices)
810

    
811

    
812
def main_menu(session):
813
    """Show the main menu of the program"""
814
    d = session['dialog']
815

    
816
    update_background_title(session)
817

    
818
    choices = [("Customize", "Customize image & cloud deployment options"),
819
               ("Register", "Register image to a cloud"),
820
               ("Extract", "Dump image to local file system"),
821
               ("Reset", "Reset everything and start over again"),
822
               ("Help", "Get help for using snf-image-creator")]
823

    
824
    default_item = "Customize"
825

    
826
    actions = {"Customize": customization_menu, "Register": kamaki_menu,
827
               "Extract": extract_image}
828
    while 1:
829
        (code, choice) = d.menu(
830
            text="Choose one of the following or press <Exit> to exit.",
831
            width=WIDTH, choices=choices, cancel="Exit", height=13,
832
            default_item=default_item, menu_height=len(choices),
833
            title="Image Creator for synnefo (snf-image-creator version %s)" %
834
                  version)
835

    
836
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
837
            if confirm_exit(d):
838
                break
839
        elif choice == "Reset":
840
            if confirm_reset(d):
841
                d.infobox("Resetting snf-image-creator. Please wait...",
842
                          width=SMALL_WIDTH)
843
                raise Reset
844
        elif choice == "Help":
845
            d.msgbox("For help, check the online documentation:\n\nhttp://www"
846
                     ".synnefo.org/docs/snf-image-creator/latest/",
847
                     width=WIDTH, title="Help")
848
        elif choice in actions:
849
            actions[choice](session)
850

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