Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_main.py @ 5a0399d8

History | View | Annotate | Download (30.2 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 dialog
37
import sys
38
import os
39
import textwrap
40
import signal
41
import StringIO
42
import optparse
43

    
44
from image_creator import __version__ as version
45
from image_creator.util import FatalError, MD5
46
from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
47
from image_creator.disk import Disk
48
from image_creator.os_type import os_cls
49
from image_creator.kamaki_wrapper import Kamaki, ClientError
50
from image_creator.help import get_help_file
51

    
52
MSGBOX_WIDTH = 60
53
YESNO_WIDTH = 50
54
MENU_WIDTH = 70
55
INPUTBOX_WIDTH = 70
56
CHECKBOX_WIDTH = 70
57
HELP_WIDTH = 70
58
INFOBOX_WIDTH = 70
59

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

    
77

    
78
class Reset(Exception):
79
    pass
80

    
81

    
82
class metadata_monitor(object):
83
    def __init__(self, session, meta):
84
        self.session = session
85
        self.meta = meta
86

    
87
    def __enter__(self):
88
        self.old = {}
89
        for (k, v) in self.meta.items():
90
            self.old[k] = v
91

    
92
    def __exit__(self, type, value, traceback):
93
        d = self.session['dialog']
94

    
95
        altered = {}
96
        added = {}
97

    
98
        for (k, v) in self.meta.items():
99
            if k not in self.old:
100
                added[k] = v
101
            elif self.old[k] != v:
102
                altered[k] = v
103

    
104
        if not (len(added) or len(altered)):
105
            return
106

    
107
        msg = "The last action has changed some image properties:\n\n"
108
        if len(added):
109
            msg += "New image properties:\n"
110
            for (k, v) in added.items():
111
                msg += '    %s: "%s"\n' % (k, v)
112
            msg += "\n"
113
        if len(altered):
114
            msg += "Updated image properties:\n"
115
            for (k, v) in altered.items():
116
                msg += '    %s: "%s" -> "%s"\n' % (k, self.old[k], v)
117
            msg += "\n"
118

    
119
        self.session['metadata'].update(added)
120
        self.session['metadata'].update(altered)
121
        d.msgbox(msg, title="Image Property Changes", width=MSGBOX_WIDTH)
122

    
123

    
124
def extract_metadata_string(session):
125
    metadata = ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()]
126

    
127
    if 'task_metadata' in session:
128
        metadata.extend("%s=yes" % m for m in session['task_metadata'])
129

    
130
    return '\n'.join(metadata) + '\n'
131

    
132

    
133
def confirm_exit(d, msg=''):
134
    return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
135

    
136

    
137
def confirm_reset(d):
138
    return not d.yesno("Are you sure you want to reset everything?",
139
                       width=YESNO_WIDTH, defaultno=1)
140

    
141

    
142
def update_background_title(session):
143
    d = session['dialog']
144
    dev = session['device']
145

    
146
    MB = 2 ** 20
147

    
148
    size = (dev.meta['SIZE'] + MB - 1) // MB
149
    shrinked = 'shrinked' in session and session['shrinked']
150
    postfix = " (shrinked)" if shrinked else ''
151

    
152
    title = "OS: %s, Distro: %s, Size: %dMB%s" % \
153
            (dev.ostype, dev.distro, size, postfix)
154

    
155
    d.setBackgroundTitle(title)
156

    
157

    
158
def extract_image(session):
159
    d = session['dialog']
160
    dir = os.getcwd()
161
    while 1:
162
        if dir and dir[-1] != os.sep:
163
            dir = dir + os.sep
164

    
165
        (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
166
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
167
            return False
168

    
169
        if os.path.isdir(path):
170
            dir = path
171
            continue
172

    
173
        if os.path.isdir("%s.meta" % path):
174
            d.msgbox("Can't overwrite directory `%s.meta'" % path,
175
                     width=MSGBOX_WIDTH)
176
            continue
177

    
178
        if os.path.isdir("%s.md5sum" % path):
179
            d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
180
                     width=MSGBOX_WIDTH)
181
            continue
182

    
183
        basedir = os.path.dirname(path)
184
        name = os.path.basename(path)
185
        if not os.path.exists(basedir):
186
            d.msgbox("Directory `%s' does not exist" % basedir,
187
                     width=MSGBOX_WIDTH)
188
            continue
189

    
190
        dir = basedir
191
        if len(name) == 0:
192
            continue
193

    
194
        files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
195
        overwrite = filter(os.path.exists, files)
196

    
197
        if len(overwrite) > 0:
198
            if d.yesno("The following file(s) exist:\n"
199
                       "%s\nDo you want to overwrite them?" %
200
                       "\n".join(overwrite), width=YESNO_WIDTH):
201
                continue
202

    
203
        out = GaugeOutput(d, "Image Extraction", "Extracting image...")
204
        try:
205
            dev = session['device']
206
            if "checksum" not in session:
207
                size = dev.meta['SIZE']
208
                md5 = MD5(out)
209
                session['checksum'] = md5.compute(session['snapshot'], size)
210

    
211
            # Extract image file
212
            dev.out = out
213
            dev.dump(path)
214

    
215
            # Extract metadata file
216
            out.output("Extracting metadata file...")
217
            with open('%s.meta' % path, 'w') as f:
218
                f.write(extract_metadata_string(session))
219
            out.success('done')
220

    
221
            # Extract md5sum file
222
            out.output("Extracting md5sum file...")
223
            md5str = "%s %s\n" % (session['checksum'], name)
224
            with open('%s.md5sum' % path, 'w') as f:
225
                f.write(md5str)
226
            out.success("done")
227

    
228
        finally:
229
            out.cleanup()
230
        d.msgbox("Image file `%s' was successfully extracted!" % path,
231
                 width=MSGBOX_WIDTH)
232
        break
233

    
234
    return True
235

    
236

    
237
def upload_image(session):
238
    d = session["dialog"]
239
    size = session['device'].meta['SIZE']
240

    
241
    if "account" not in session:
242
        d.msgbox("You need to provide your ~okeanos login username before you "
243
                 "can upload images to pithos+", width=MSGBOX_WIDTH)
244
        return False
245

    
246
    if "token" not in session:
247
        d.msgbox("You need to provide your ~okeanos account authentication "
248
                 "token before you can upload images to pithos+",
249
                 width=MSGBOX_WIDTH)
250
        return False
251

    
252
    while 1:
253
        init = session["upload"] if "upload" in session else ''
254
        (code, answer) = d.inputbox("Please provide a filename:", init=init,
255
                                    width=INPUTBOX_WIDTH)
256

    
257
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
258
            return False
259

    
260
        filename = answer.strip()
261
        if len(filename) == 0:
262
            d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
263
            continue
264

    
265
        break
266

    
267
    out = GaugeOutput(d, "Image Upload", "Uploading...")
268
    if 'checksum' not in session:
269
        md5 = MD5(out)
270
        session['checksum'] = md5.compute(session['snapshot'], size)
271
    try:
272
        kamaki = Kamaki(session['account'], session['token'], out)
273
        try:
274
            # Upload image file
275
            with open(session['snapshot'], 'rb') as f:
276
                session["upload"] = kamaki.upload(f, size, filename,
277
                                                  "Calculating block hashes",
278
                                                  "Uploading missing blocks")
279
            # Upload metadata file
280
            out.output("Uploading metadata file...")
281
            metastring = extract_metadata_string(session)
282
            kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
283
                          remote_path="%s.meta" % filename)
284
            out.success("done")
285

    
286
            # Upload md5sum file
287
            out.output("Uploading md5sum file...")
288
            md5str = "%s %s\n" % (session['checksum'], filename)
289
            kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
290
                          remote_path="%s.md5sum" % filename)
291
            out.success("done")
292

    
293
        except ClientError as e:
294
            d.msgbox("Error in pithos+ client: %s" % e.message,
295
                     title="Pithos+ Client Error", width=MSGBOX_WIDTH)
296
            if 'upload' in session:
297
                del session['upload']
298
            return False
299
    finally:
300
        out.cleanup()
301

    
302
    d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
303
             width=MSGBOX_WIDTH)
304

    
305
    return True
306

    
307

    
308
def register_image(session):
309
    d = session["dialog"]
310

    
311
    if "account" not in session:
312
        d.msgbox("You need to provide your ~okeanos login username before you "
313
                 "can register an images to cyclades",
314
                 width=MSGBOX_WIDTH)
315
        return False
316

    
317
    if "token" not in session:
318
        d.msgbox("You need to provide your ~okeanos account authentication "
319
                 "token before you can register an images to cyclades",
320
                 width=MSGBOX_WIDTH)
321
        return False
322

    
323
    if "upload" not in session:
324
        d.msgbox("You need to upload the image to pithos+ before you can "
325
                 "register it to cyclades", width=MSGBOX_WIDTH)
326
        return False
327

    
328
    while 1:
329
        (code, answer) = d.inputbox("Please provide a registration name:",
330
                                    width=INPUTBOX_WIDTH)
331
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
332
            return False
333

    
334
        name = answer.strip()
335
        if len(name) == 0:
336
            d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
337
            continue
338
        break
339

    
340
    metadata = {}
341
    metadata.update(session['metadata'])
342
    if 'task_metadata' in session:
343
        for key in session['task_metadata']:
344
            metadata[key] = 'yes'
345

    
346
    out = GaugeOutput(d, "Image Registration", "Registrating image...")
347
    try:
348
        out.output("Registring image to cyclades...")
349
        try:
350
            kamaki = Kamaki(session['account'], session['token'], out)
351
            kamaki.register(name, session['upload'], metadata)
352
            out.success('done')
353
        except ClientError as e:
354
            d.msgbox("Error in pithos+ client: %s" % e.message)
355
            return False
356
    finally:
357
        out.cleanup()
358

    
359
    d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
360
             (session['upload'], name), width=MSGBOX_WIDTH)
361
    return True
362

    
363

    
364
def kamaki_menu(session):
365
    d = session['dialog']
366
    default_item = "Account"
367
    while 1:
368
        account = session["account"] if "account" in session else "<none>"
369
        token = session["token"] if "token" in session else "<none>"
370
        upload = session["upload"] if "upload" in session else "<none>"
371

    
372
        choices = [("Account", "Change your ~okeanos username: %s" % account),
373
                   ("Token", "Change your ~okeanos token: %s" % token),
374
                   ("Upload", "Upload image to pithos+"),
375
                   ("Register", "Register the image to cyclades: %s" % upload)]
376

    
377
        (code, choice) = d.menu(
378
            text="Choose one of the following or press <Back> to go back.",
379
            width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
380
            menu_height=5, default_item=default_item,
381
            title="Image Registration Menu")
382

    
383
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
384
            return False
385

    
386
        if choice == "Account":
387
            default_item = "Account"
388
            (code, answer) = d.inputbox(
389
                "Please provide your ~okeanos account e-mail address:",
390
                init=session["account"] if "account" in session else '',
391
                width=70)
392
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
393
                continue
394
            if len(answer) == 0 and "account" in session:
395
                    del session["account"]
396
            else:
397
                session["account"] = answer.strip()
398
                default_item = "Token"
399
        elif choice == "Token":
400
            default_item = "Token"
401
            (code, answer) = d.inputbox(
402
                "Please provide your ~okeanos account authetication token:",
403
                init=session["token"] if "token" in session else '',
404
                width=70)
405
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
406
                continue
407
            if len(answer) == 0 and "token" in session:
408
                del session["token"]
409
            else:
410
                session["token"] = answer.strip()
411
                default_item = "Upload"
412
        elif choice == "Upload":
413
            if upload_image(session):
414
                default_item = "Register"
415
            else:
416
                default_item = "Upload"
417
        elif choice == "Register":
418
            if register_image(session):
419
                return True
420
            else:
421
                default_item = "Register"
422

    
423

    
424
def add_property(session):
425
    d = session['dialog']
426

    
427
    while 1:
428
        (code, answer) = d.inputbox("Please provide a name for a new image"
429
                                    " property:", width=INPUTBOX_WIDTH)
430
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
431
            return False
432

    
433
        name = answer.strip()
434
        if len(name) == 0:
435
            d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
436
            continue
437

    
438
        break
439

    
440
    while 1:
441
        (code, answer) = d.inputbox("Please provide a value for image "
442
                                    "property %s" % name, width=INPUTBOX_WIDTH)
443
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
444
            return False
445

    
446
        value = answer.strip()
447
        if len(value) == 0:
448
            d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
449
            continue
450

    
451
        break
452

    
453
    session['metadata'][name] = value
454

    
455
    return True
456

    
457

    
458
def modify_properties(session):
459
    d = session['dialog']
460

    
461
    while 1:
462
        choices = []
463
        for (key, val) in session['metadata'].items():
464
            choices.append((str(key), str(val)))
465

    
466
        (code, choice) = d.menu(
467
            "In this menu you can edit existing image properties or add new "
468
            "ones. Be careful! Most properties have special meaning and "
469
            "alter the image deployment behaviour. Press <HELP> to see more "
470
            "information about image properties. Press <BACK> when done.",
471
            height=18, width=MENU_WIDTH, choices=choices, menu_height=10,
472
            ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
473
            help_button=1, title="Image Properties")
474

    
475
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
476
            return True
477
        # Edit button
478
        elif code == d.DIALOG_OK:
479
            (code, answer) = d.inputbox("Please provide a new value for the "
480
                                        "image property with name `%s':" %
481
                                        choice,
482
                                        init=session['metadata'][choice],
483
                                        width=INPUTBOX_WIDTH)
484
            if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
485
                value = answer.strip()
486
                if len(value) == 0:
487
                    d.msgbox("Value cannot be empty!")
488
                    continue
489
                else:
490
                    session['metadata'][choice] = value
491
        # ADD button
492
        elif code == d.DIALOG_EXTRA:
493
            add_property(session)
494
        elif code == 'help':
495
            help_file = get_help_file("image_properties")
496
            assert os.path.exists(help_file)
497
            d.textbox(help_file, title="Image Properties", width=70, height=40)
498

    
499

    
500
def delete_properties(session):
501
    d = session['dialog']
502

    
503
    choices = []
504
    for (key, val) in session['metadata'].items():
505
        choices.append((key, "%s" % val, 0))
506

    
507
    (code, to_delete) = d.checklist("Choose which properties to delete:",
508
                                    choices=choices, width=CHECKBOX_WIDTH)
509

    
510
    # If the user exits with ESC or CANCEL, the returned tag list is empty.
511
    for i in to_delete:
512
        del session['metadata'][i]
513

    
514
    cnt = len(to_delete)
515
    if cnt > 0:
516
        d.msgbox("%d image properties were deleted." % cnt, width=MSGBOX_WIDTH)
517
        return True
518
    else:
519
        return False
520

    
521

    
522
def exclude_tasks(session):
523
    d = session['dialog']
524

    
525
    index = 0
526
    displayed_index = 1
527
    choices = []
528
    mapping = {}
529
    if 'excluded_tasks' not in session:
530
        session['excluded_tasks'] = []
531

    
532
    if -1 in session['excluded_tasks']:
533
        if not d.yesno("Image deployment configuration is disabled. "
534
                       "Do you wish to enable it?", width=YESNO_WIDTH):
535
            session['excluded_tasks'].remove(-1)
536
        else:
537
            return False
538

    
539
    for (msg, task, osfamily) in CONFIGURATION_TASKS:
540
        if session['metadata']['OSFAMILY'] in osfamily:
541
            checked = 1 if index in session['excluded_tasks'] else 0
542
            choices.append((str(displayed_index), msg, checked))
543
            mapping[displayed_index] = index
544
            displayed_index += 1
545
        index += 1
546

    
547
    while 1:
548
        (code, tags) = d.checklist(
549
            text="Please choose which configuration tasks you would like to "
550
                 "prevent from running during image deployment. "
551
                 "Press <No Config> to supress any configuration. "
552
                 "Press <Help> for more help on the image deployment "
553
                 "configuration tasks.",
554
            choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
555
            help_button=1, extra_button=1, extra_label="No Config",
556
            title="Exclude Configuration Tasks")
557

    
558
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
559
            return False
560
        elif code == d.DIALOG_HELP:
561
            help_file = get_help_file("configuration_tasks")
562
            assert os.path.exists(help_file)
563
            d.textbox(help_file, title="Configuration Tasks",
564
                      width=70, height=40)
565
        # No Config button
566
        elif code == d.DIALOG_EXTRA:
567
            session['excluded_tasks'] = [-1]
568
            session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
569
            break
570
        elif code == d.DIALOG_OK:
571
            session['excluded_tasks'] = []
572
            for tag in tags:
573
                session['excluded_tasks'].append(mapping[int(tag)])
574

    
575
            exclude_metadata = []
576
            for task in session['excluded_tasks']:
577
                exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
578

    
579
            session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
580
                                           exclude_metadata)
581
            break
582

    
583
    return True
584

    
585

    
586
def sysprep(session):
587
    d = session['dialog']
588
    image_os = session['image_os']
589

    
590
    # Is the image already shrinked?
591
    if 'shrinked' in session and session['shrinked']:
592
        msg = "It seems you have shrinked the image. Running system " \
593
              "preparation tasks on a shrinked image is dangerous."
594

    
595
        if d.yesno("%s\n\nDo you really want to continue?" % msg,
596
                   width=YESNO_WIDTH, defaultno=1):
597
            return
598

    
599
    wrapper = textwrap.TextWrapper(width=65)
600

    
601
    help_title = "System Preperation Tasks"
602
    sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
603

    
604
    if 'exec_syspreps' not in session:
605
        session['exec_syspreps'] = []
606

    
607
    all_syspreps = image_os.list_syspreps()
608
    # Only give the user the choice between syspreps that have not ran yet
609
    syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
610

    
611
    if len(syspreps) == 0:
612
        d.msgbox("No system preparation task available to run!",
613
                 title="System Preperation", width=MSGBOX_WIDTH)
614
        return
615

    
616
    while 1:
617
        choices = []
618
        index = 0
619
        for sysprep in syspreps:
620
            name, descr = image_os.sysprep_info(sysprep)
621
            display_name = name.replace('-', ' ').capitalize()
622
            sysprep_help += "%s\n" % display_name
623
            sysprep_help += "%s\n" % ('-' * len(display_name))
624
            sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
625
            enabled = 1 if sysprep.enabled else 0
626
            choices.append((str(index + 1), display_name, enabled))
627
            index += 1
628

    
629
        (code, tags) = d.checklist(
630
            "Please choose which system preperation tasks you would like to "
631
            "run on the image. Press <Help> to see details about the system "
632
            "preperation tasks.", title="Run system preperation tasks",
633
            choices=choices, width=70, ok_label="Run", help_button=1)
634

    
635
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
636
            return False
637
        elif code == d.DIALOG_HELP:
638
            d.scrollbox(sysprep_help, width=HELP_WIDTH)
639
        elif code == d.DIALOG_OK:
640
            # Enable selected syspreps and disable the rest
641
            for i in range(len(syspreps)):
642
                if str(i + 1) in tags:
643
                    image_os.enable_sysprep(syspreps[i])
644
                    session['exec_syspreps'].append(syspreps[i])
645
                else:
646
                    image_os.disable_sysprep(syspreps[i])
647

    
648
            out = InfoBoxOutput(d, "Image Configuration")
649
            try:
650
                dev = session['device']
651
                dev.out = out
652
                dev.mount(readonly=False)
653
                try:
654
                    # The checksum is invalid. We have mounted the image rw
655
                    if 'checksum' in session:
656
                        del session['checksum']
657

    
658
                    # Monitor the metadata changes during syspreps
659
                    with metadata_monitor(session, image_os.meta):
660
                        image_os.out = out
661
                        image_os.do_sysprep()
662
                        image_os.out.finalize()
663

    
664
                    # Disable syspreps that have ran
665
                    for sysprep in session['exec_syspreps']:
666
                        image_os.disable_sysprep(sysprep)
667

    
668
                finally:
669
                    dev.umount()
670
            finally:
671
                out.cleanup()
672
            break
673
    return True
674

    
675

    
676
def shrink(session):
677
    d = session['dialog']
678
    dev = session['device']
679

    
680
    shrinked = 'shrinked' in session and session['shrinked']
681

    
682
    if shrinked:
683
        d.msgbox("The image is already shrinked!", title="Image Shrinking",
684
                 width=MSGBOX_WIDTH)
685
        return True
686

    
687
    msg = "This operation will shrink the last partition of the image to " \
688
          "reduce the total image size. If the last partition is a swap " \
689
          "partition, then this partition is removed and the partition " \
690
          "before that is shrinked. The removed swap partition will be " \
691
          "recreated during image deployment."
692

    
693
    if not d.yesno("%s\n\nDo you want to continue?" % msg, width=70,
694
                   height=12, title="Image Shrinking"):
695
        with metadata_monitor(session, dev.meta):
696
            dev.out = InfoBoxOutput(d, "Image Shrinking", height=4)
697
            dev.shrink()
698
            dev.out.finalize()
699

    
700
        session['shrinked'] = True
701
        update_background_title(session)
702
    else:
703
        return False
704

    
705
    return True
706

    
707

    
708
def customization_menu(session):
709
    d = session['dialog']
710

    
711
    choices = [("Sysprep", "Run various image preperation tasks"),
712
               ("Shrink", "Shrink image"),
713
               ("View/Modify", "View/Modify image properties"),
714
               ("Delete", "Delete image properties"),
715
               ("Exclude", "Exclude various deployment tasks from running")]
716

    
717
    default_item = 0
718

    
719
    actions = {"Sysprep": sysprep,
720
               "Shrink": shrink,
721
               "View/Modify": modify_properties,
722
               "Delete": delete_properties,
723
               "Exclude": exclude_tasks}
724
    while 1:
725
        (code, choice) = d.menu(
726
            text="Choose one of the following or press <Back> to exit.",
727
            width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
728
            menu_height=len(choices), default_item=choices[default_item][0],
729
            title="Image Customization Menu")
730

    
731
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
732
            break
733
        elif choice in actions:
734
            default_item = [entry[0] for entry in choices].index(choice)
735
            if actions[choice](session):
736
                default_item = (default_item + 1) % len(choices)
737

    
738

    
739
def main_menu(session):
740
    d = session['dialog']
741
    dev = session['device']
742

    
743
    update_background_title(session)
744

    
745
    choices = [("Customize", "Customize image & ~okeanos deployment options"),
746
               ("Register", "Register image to ~okeanos"),
747
               ("Extract", "Dump image to local file system"),
748
               ("Reset", "Reset everything and start over again"),
749
               ("Help", "Get help for using snf-image-creator")]
750

    
751
    default_item = "Customize"
752

    
753
    actions = {"Customize": customization_menu, "Register": kamaki_menu,
754
               "Extract": extract_image}
755
    while 1:
756
        (code, choice) = d.menu(
757
            text="Choose one of the following or press <Exit> to exit.",
758
            width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
759
            default_item=default_item, menu_height=len(choices),
760
            title="Image Creator for ~okeanos (snf-image-creator version %s)" %
761
                  version)
762

    
763
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
764
            if confirm_exit(d):
765
                break
766
        elif choice == "Reset":
767
            if confirm_reset(d):
768
                d.infobox("Resetting snf-image-creator. Please wait...",
769
                          width=INFOBOX_WIDTH)
770
                raise Reset
771
        elif choice in actions:
772
            actions[choice](session)
773

    
774

    
775
def select_file(d, media):
776
    root = os.sep
777
    while 1:
778
        if media is not None:
779
            if not os.path.exists(media):
780
                d.msgbox("The file you choose does not exist",
781
                         width=MSGBOX_WIDTH)
782
            else:
783
                break
784

    
785
        (code, media) = d.fselect(root, 10, 50,
786
                                  title="Please select input media")
787
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
788
            if confirm_exit(d, "You canceled the media selection dialog box."):
789
                sys.exit(0)
790
            else:
791
                media = None
792
                continue
793

    
794
    return media
795

    
796

    
797
def wizard(session):
798
    pass
799

    
800

    
801
def image_creator(d):
802

    
803
    usage = "Usage: %prog [options] [<input_media>]"
804
    parser = optparse.OptionParser(version=version, usage=usage)
805

    
806
    options, args = parser.parse_args(sys.argv[1:])
807

    
808
    if len(args) > 1:
809
        parser.error("Wrong numver of arguments")
810

    
811
    d.setBackgroundTitle('snf-image-creator')
812

    
813
    if os.geteuid() != 0:
814
        raise FatalError("You must run %s as root" % basename)
815

    
816
    media = select_file(d, args[0] if len(args) == 1 else None)
817

    
818
    out = GaugeOutput(d, "Initialization", "Initializing...")
819
    disk = Disk(media, out)
820

    
821
    def signal_handler(signum, frame):
822
        out.cleanup()
823
        disk.cleanup()
824

    
825
    signal.signal(signal.SIGINT, signal_handler)
826
    try:
827
        snapshot = disk.snapshot()
828
        dev = disk.get_device(snapshot)
829

    
830
        metadata = {}
831
        for (key, value) in dev.meta.items():
832
            metadata[str(key)] = str(value)
833

    
834
        dev.mount(readonly=True)
835
        out.output("Collecting image metadata...")
836
        cls = os_cls(dev.distro, dev.ostype)
837
        image_os = cls(dev.root, dev.g, out)
838
        dev.umount()
839

    
840
        for (key, value) in image_os.meta.items():
841
            metadata[str(key)] = str(value)
842

    
843
        out.success("done")
844
        out.cleanup()
845

    
846
        # Make sure the signal handler does not call out.cleanup again
847
        def dummy(self):
848
            pass
849
        out.cleanup = type(GaugeOutput.cleanup)(dummy, out, GaugeOutput)
850

    
851
        session = {"dialog": d,
852
                   "disk": disk,
853
                   "snapshot": snapshot,
854
                   "device": dev,
855
                   "image_os": image_os,
856
                   "metadata": metadata}
857

    
858
        msg = "Would you like to run the snf-image-creator wizard? " \
859
              "Choose <Yes> if you want to run a wizards to assists " \
860
              "you through the image creation process. Choose <No> to run " \
861
              "the program in expert mode."
862

    
863
        if d.yesno(msg, width=YESNO_WIDTH):
864
            main_menu(session)
865
        else:
866
            wizard(session)
867

    
868
        d.infobox("Thank you for using snf-image-creator. Bye", width=53)
869
    finally:
870
        disk.cleanup()
871

    
872
    return 0
873

    
874

    
875
def main():
876

    
877
    d = dialog.Dialog(dialog="dialog")
878

    
879
    # Add extra button in dialog library
880
    dialog._common_args_syntax["extra_button"] = \
881
        lambda enable: dialog._simple_option("--extra-button", enable)
882

    
883
    dialog._common_args_syntax["extra_label"] = \
884
        lambda string: ("--extra-label", string)
885

    
886
    while 1:
887
        try:
888
            try:
889
                ret = image_creator(d)
890
                sys.exit(ret)
891
            except FatalError as e:
892
                msg = textwrap.fill(str(e), width=70)
893
                d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
894
                sys.exit(1)
895
        except Reset:
896
            continue
897

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