Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_menu.py @ 82e8c357

History | View | Annotate | Download (31 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
SYSPREP_PARAM_MAXLEN = 20
72

    
73

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

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

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

    
88
        altered = {}
89
        added = {}
90

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

    
97
        if not (len(added) or len(altered)):
98
            return
99

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

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

    
116

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

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

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

    
139
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
140
            return False
141

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

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

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

    
159
        session['upload'] = filename
160
        break
161

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

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

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

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

    
201
    return True
202

    
203

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

    
208
    is_public = False
209

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

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

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

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

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

    
237
        is_public = True if ret == 0 else False
238

    
239
        break
240

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

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

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

    
284

    
285
def modify_clouds(session):
286
    """Modify existing cloud accounts"""
287
    d = session['dialog']
288

    
289
    while 1:
290
        clouds = Kamaki.get_clouds()
291
        if not len(clouds):
292
            if not add_cloud(session):
293
                break
294
            continue
295

    
296
        choices = []
297
        for (name, cloud) in clouds.items():
298
            descr = cloud['description'] if 'description' in cloud else ''
299
            choices.append((name, descr))
300

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

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

    
316

    
317
def delete_clouds(session):
318
    """Delete existing cloud accounts"""
319
    d = session['dialog']
320

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

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

    
330
    (code, to_delete) = d.checklist("Choose which cloud accounts to delete:",
331
                                    choices=choices, width=WIDTH)
332
    to_delete = map(lambda x: x.strip('"'), to_delete)  # Needed for OpenSUSE
333

    
334
    if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
335
        return False
336

    
337
    if not len(to_delete):
338
        d.msgbox("Nothing selected!", width=SMALL_WIDTH)
339
        return False
340

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

    
352
    d.msgbox("%d cloud accounts were deleted." % len(to_delete),
353
             width=SMALL_WIDTH)
354
    return True
355

    
356

    
357
def kamaki_menu(session):
358
    """Show kamaki related actions"""
359
    d = session['dialog']
360
    default_item = "Cloud"
361

    
362
    if 'cloud' not in session:
363
        cloud = Kamaki.get_default_cloud_name()
364
        if cloud:
365
            session['cloud'] = cloud
366
            session['account'] = Kamaki.get_account(cloud)
367
            if not session['account']:
368
                del session['account']
369
        else:
370
            default_item = "Add/Edit"
371

    
372
    while 1:
373
        cloud = session["cloud"] if "cloud" in session else "<none>"
374
        if 'account' not in session and 'cloud' in session:
375
            cloud += " <invalid>"
376

    
377
        upload = session["upload"] if "upload" in session else "<none>"
378

    
379
        choices = [("Add/Edit", "Add/Edit cloud accounts"),
380
                   ("Delete", "Delete existing cloud accounts"),
381
                   ("Cloud", "Select cloud account to use: %s" % cloud),
382
                   ("Upload", "Upload image to the cloud"),
383
                   ("Register", "Register image with the cloud: %s" % upload)]
384

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

    
391
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
392
            return False
393

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

    
414
            if 'cloud' not in session:
415
                session['cloud'] = clouds.keys()[0]
416

    
417
            choices = []
418
            for name, info in clouds.items():
419
                default = 1 if session['cloud'] == name else 0
420
                descr = info['description'] if 'description' in info else ""
421
                choices.append((name, descr, default))
422

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

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

    
437
                if session['account'] is not None:
438
                    session['cloud'] = answer
439
                    Kamaki.set_default_cloud(answer)
440
                    default_item = "Upload"
441
                else:
442
                    del session['account']
443
                    del session['cloud']
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
    """Add a new property to the image"""
458
    d = session['dialog']
459

    
460
    while 1:
461
        (code, answer) = d.inputbox("Please provide a name for a new image"
462
                                    " property:", width=WIDTH)
463
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
464
            return False
465

    
466
        name = answer.strip()
467
        if len(name) == 0:
468
            d.msgbox("A property name cannot be empty", width=SMALL_WIDTH)
469
            continue
470

    
471
        break
472

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

    
479
        value = answer.strip()
480
        if len(value) == 0:
481
            d.msgbox("Value cannot be empty", width=SMALL_WIDTH)
482
            continue
483

    
484
        break
485

    
486
    session['metadata'][name] = value
487

    
488
    return True
489

    
490

    
491
def modify_properties(session):
492
    """Modify an existing image property"""
493
    d = session['dialog']
494

    
495
    while 1:
496
        choices = []
497
        for (key, val) in session['metadata'].items():
498
            choices.append((str(key), str(val)))
499

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

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

    
533

    
534
def delete_properties(session):
535
    """Delete an image property"""
536
    d = session['dialog']
537

    
538
    choices = []
539
    for (key, val) in session['metadata'].items():
540
        choices.append((key, "%s" % val, 0))
541

    
542
    (code, to_delete) = d.checklist("Choose which properties to delete:",
543
                                    choices=choices, width=WIDTH)
544
    to_delete = map(lambda x: x.strip('"'), to_delete)  # needed for OpenSUSE
545

    
546
    # If the user exits with ESC or CANCEL, the returned tag list is empty.
547
    for i in to_delete:
548
        del session['metadata'][i]
549

    
550
    cnt = len(to_delete)
551
    if cnt > 0:
552
        d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH)
553
        return True
554
    else:
555
        return False
556

    
557

    
558
def exclude_tasks(session):
559
    """Exclude specific tasks from running during image deployment"""
560
    d = session['dialog']
561

    
562
    index = 0
563
    displayed_index = 1
564
    choices = []
565
    mapping = {}
566
    if 'excluded_tasks' not in session:
567
        session['excluded_tasks'] = []
568

    
569
    if -1 in session['excluded_tasks']:
570
        if not d.yesno("Image deployment configuration is disabled. "
571
                       "Do you wish to enable it?", width=SMALL_WIDTH):
572
            session['excluded_tasks'].remove(-1)
573
        else:
574
            return False
575

    
576
    for (msg, task, osfamily) in CONFIGURATION_TASKS:
577
        if session['metadata']['OSFAMILY'] in osfamily:
578
            checked = 1 if index in session['excluded_tasks'] else 0
579
            choices.append((str(displayed_index), msg, checked))
580
            mapping[displayed_index] = index
581
            displayed_index += 1
582
        index += 1
583

    
584
    while 1:
585
        (code, tags) = d.checklist(
586
            text="Please choose which configuration tasks you would like to "
587
                 "prevent from running during image deployment. "
588
                 "Press <No Config> to supress any configuration. "
589
                 "Press <Help> for more help on the image deployment "
590
                 "configuration tasks.",
591
            choices=choices, height=19, list_height=8, width=WIDTH,
592
            help_button=1, extra_button=1, extra_label="No Config",
593
            title="Exclude Configuration Tasks")
594
        tags = map(lambda x: x.strip('"'), tags)  # Needed for OpenSUSE
595

    
596
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
597
            return False
598
        elif code == d.DIALOG_HELP:
599
            help_file = get_help_file("configuration_tasks")
600
            assert os.path.exists(help_file)
601
            d.textbox(help_file, title="Configuration Tasks",
602
                      width=70, height=40)
603
        # No Config button
604
        elif code == d.DIALOG_EXTRA:
605
            session['excluded_tasks'] = [-1]
606
            session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
607
            break
608
        elif code == d.DIALOG_OK:
609
            session['excluded_tasks'] = []
610
            for tag in tags:
611
                session['excluded_tasks'].append(mapping[int(tag)])
612

    
613
            exclude_metadata = []
614
            for task in session['excluded_tasks']:
615
                exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
616

    
617
            session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
618
                                           exclude_metadata)
619
            break
620

    
621
    return True
622

    
623

    
624
def sysprep_params(session):
625
    """Collect the needed sysprep parameters"""
626
    d = session['dialog']
627
    image = session['image']
628

    
629
    available = image.os.sysprep_params
630
    needed = image.os.needed_sysprep_params
631
    names = needed.keys()
632

    
633
    if len(needed) == 0:
634
        return True
635

    
636
    while 1:
637
        fields = []
638
        for name in names:
639
            param = needed[name]
640
            default = str(available[name]) if name in available else ""
641
            fields.append(("%s: " % param.description, default,
642
                           SYSPREP_PARAM_MAXLEN))
643

    
644
        txt = "Please provide the following system preparation parameters:"
645
        code, output = d.form(txt, height=13, width=WIDTH,
646
                              form_height=len(fields), fields=fields)
647

    
648
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
649
            return False
650

    
651
        def check_params():
652
            for i in range(len(fields)):
653
                param = needed[names[i]]
654
                try:
655
                    value = param.type(output[i])
656
                    if param.validate(value):
657
                        image.os.sysprep_params[names[i]] = value
658
                        continue
659
                except ValueError:
660
                    pass
661

    
662
                d.msgbox("Invalid value for parameter: `%s'" % names[i],
663
                         width=SMALL_WIDTH)
664
                return False
665
            return True
666

    
667
        if check_params():
668
            break
669

    
670
    return True
671

    
672

    
673
def sysprep(session):
674
    """Perform various system preperation tasks on the image"""
675
    d = session['dialog']
676
    image = session['image']
677

    
678
    # Is the image already shrinked?
679
    if 'shrinked' in session and session['shrinked']:
680
        msg = "It seems you have shrinked the image. Running system " \
681
              "preparation tasks on a shrinked image is dangerous."
682

    
683
        if d.yesno("%s\n\nDo you really want to continue?" % msg,
684
                   width=SMALL_WIDTH, defaultno=1):
685
            return
686

    
687
    wrapper = textwrap.TextWrapper(width=WIDTH - 5)
688

    
689
    syspreps = image.os.list_syspreps()
690

    
691
    if len(syspreps) == 0:
692
        d.msgbox("No system preparation task available to run!",
693
                 title="System Preperation", width=SMALL_WIDTH)
694
        return
695

    
696
    while 1:
697
        choices = []
698
        index = 0
699

    
700
        help_title = "System Preperation Tasks"
701
        sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
702

    
703
        for sysprep in syspreps:
704
            name, descr = image.os.sysprep_info(sysprep)
705
            display_name = name.replace('-', ' ').capitalize()
706
            sysprep_help += "%s\n" % display_name
707
            sysprep_help += "%s\n" % ('-' * len(display_name))
708
            sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
709
            enabled = 1 if sysprep.enabled else 0
710
            choices.append((str(index + 1), display_name, enabled))
711
            index += 1
712

    
713
        (code, tags) = d.checklist(
714
            "Please choose which system preparation tasks you would like to "
715
            "run on the image. Press <Help> to see details about the system "
716
            "preparation tasks.", title="Run system preparation tasks",
717
            choices=choices, width=70, ok_label="Run", help_button=1)
718
        tags = map(lambda x: x.strip('"'), tags)  # Needed for OpenSUSE
719

    
720
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
721
            return False
722
        elif code == d.DIALOG_HELP:
723
            d.scrollbox(sysprep_help, width=WIDTH)
724
        elif code == d.DIALOG_OK:
725
            # Enable selected syspreps and disable the rest
726
            for i in range(len(syspreps)):
727
                if str(i + 1) in tags:
728
                    image.os.enable_sysprep(syspreps[i])
729
                else:
730
                    image.os.disable_sysprep(syspreps[i])
731

    
732
            if len([s for s in image.os.list_syspreps() if s.enabled]) == 0:
733
                d.msgbox("No system preperation task is selected!",
734
                         title="System Preperation", width=SMALL_WIDTH)
735
                continue
736

    
737
            if not sysprep_params(session):
738
                continue
739

    
740
            infobox = InfoBoxOutput(d, "Image Configuration")
741
            try:
742
                image.out.add(infobox)
743
                try:
744
                    # The checksum is invalid. We have mounted the image rw
745
                    if 'checksum' in session:
746
                        del session['checksum']
747

    
748
                    # Monitor the metadata changes during syspreps
749
                    with MetadataMonitor(session, image.os.meta):
750
                        try:
751
                            image.os.do_sysprep()
752
                            infobox.finalize()
753
                        except FatalError as e:
754
                            title = "System Preparation"
755
                            d.msgbox("System Preparation failed: %s" % e,
756
                                     title=title, width=SMALL_WIDTH)
757
                finally:
758
                    image.out.remove(infobox)
759
            finally:
760
                infobox.cleanup()
761
            break
762
    return True
763

    
764

    
765
def shrink(session):
766
    """Shrink the image"""
767
    d = session['dialog']
768
    image = session['image']
769

    
770
    shrinked = 'shrinked' in session and session['shrinked']
771

    
772
    if shrinked:
773
        d.msgbox("The image is already shrinked!", title="Image Shrinking",
774
                 width=SMALL_WIDTH)
775
        return True
776

    
777
    msg = "This operation will shrink the last partition of the image to " \
778
          "reduce the total image size. If the last partition is a swap " \
779
          "partition, then this partition is removed and the partition " \
780
          "before that is shrinked. The removed swap partition will be " \
781
          "recreated during image deployment."
782

    
783
    if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH,
784
                   height=12, title="Image Shrinking"):
785
        with MetadataMonitor(session, image.meta):
786
            infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
787
            image.out.add(infobox)
788
            try:
789
                image.shrink()
790
                infobox.finalize()
791
            finally:
792
                image.out.remove(infobox)
793

    
794
        session['shrinked'] = True
795
        update_background_title(session)
796
    else:
797
        return False
798

    
799
    return True
800

    
801

    
802
def customization_menu(session):
803
    """Show image customization menu"""
804
    d = session['dialog']
805

    
806
    choices = [("Sysprep", "Run various image preparation tasks"),
807
               ("Shrink", "Shrink image"),
808
               ("View/Modify", "View/Modify image properties"),
809
               ("Delete", "Delete image properties"),
810
               ("Exclude", "Exclude various deployment tasks from running")]
811

    
812
    default_item = 0
813

    
814
    actions = {"Sysprep": sysprep,
815
               "Shrink": shrink,
816
               "View/Modify": modify_properties,
817
               "Delete": delete_properties,
818
               "Exclude": exclude_tasks}
819
    while 1:
820
        (code, choice) = d.menu(
821
            text="Choose one of the following or press <Back> to exit.",
822
            width=WIDTH, choices=choices, cancel="Back", height=13,
823
            menu_height=len(choices), default_item=choices[default_item][0],
824
            title="Image Customization Menu")
825

    
826
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
827
            break
828
        elif choice in actions:
829
            default_item = [entry[0] for entry in choices].index(choice)
830
            if actions[choice](session):
831
                default_item = (default_item + 1) % len(choices)
832

    
833

    
834
def main_menu(session):
835
    """Show the main menu of the program"""
836
    d = session['dialog']
837

    
838
    update_background_title(session)
839

    
840
    choices = [("Customize", "Customize image & cloud deployment options"),
841
               ("Register", "Register image to a cloud"),
842
               ("Extract", "Dump image to local file system"),
843
               ("Reset", "Reset everything and start over again"),
844
               ("Help", "Get help for using snf-image-creator")]
845

    
846
    default_item = "Customize"
847

    
848
    actions = {"Customize": customization_menu, "Register": kamaki_menu,
849
               "Extract": extract_image}
850
    while 1:
851
        (code, choice) = d.menu(
852
            text="Choose one of the following or press <Exit> to exit.",
853
            width=WIDTH, choices=choices, cancel="Exit", height=13,
854
            default_item=default_item, menu_height=len(choices),
855
            title="Image Creator for synnefo (snf-image-creator version %s)" %
856
                  version)
857

    
858
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
859
            if confirm_exit(d):
860
                break
861
        elif choice == "Reset":
862
            if confirm_reset(d):
863
                d.infobox("Resetting snf-image-creator. Please wait ...",
864
                          width=SMALL_WIDTH)
865
                raise Reset
866
        elif choice == "Help":
867
            d.msgbox("For help, check the online documentation:\n\nhttp://www"
868
                     ".synnefo.org/docs/snf-image-creator/latest/",
869
                     width=WIDTH, title="Help")
870
        elif choice in actions:
871
            actions[choice](session)
872

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