Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_main.py @ 7f623b20

History | View | Annotate | Download (24.1 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

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

    
51
MSGBOX_WIDTH = 60
52
YESNO_WIDTH = 50
53
MENU_WIDTH = 70
54
INPUTBOX_WIDTH = 70
55
CHECKBOX_WIDTH = 70
56

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

    
74

    
75
class Reset(Exception):
76
    pass
77

    
78

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

    
82

    
83
def confirm_reset(d):
84
    return not d.yesno(
85
        "Are you sure you want to reset everything?",
86
        width=YESNO_WIDTH)
87

    
88

    
89
def extract_image(session):
90
    d = session['dialog']
91
    dir = os.getcwd()
92
    while 1:
93
        if dir and dir[-1] != os.sep:
94
            dir = dir + os.sep
95

    
96
        (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
97
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
98
            return False
99

    
100
        if os.path.isdir(path):
101
            dir = path
102
            continue
103

    
104
        if os.path.isdir("%s.meta" % path):
105
            d.msgbox("Can't overwrite directory `%s.meta'" % path,
106
                     width=MSGBOX_WIDTH)
107
            continue
108

    
109
        if os.path.isdir("%s.md5sum" % path):
110
            d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
111
                     width=MSGBOX_WIDTH)
112
            continue
113

    
114
        basedir = os.path.dirname(path)
115
        name = os.path.basename(path)
116
        if not os.path.exists(basedir):
117
            d.msgbox("Directory `%s' does not exist" % basedir,
118
                     width=MSGBOX_WIDTH)
119
            continue
120

    
121
        dir = basedir
122
        if len(name) == 0:
123
            continue
124

    
125
        files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
126
        overwrite = filter(os.path.exists, files)
127

    
128
        if len(overwrite) > 0:
129
            if d.yesno("The following file(s) exist:\n"
130
                        "%s\nDo you want to overwrite them?" %
131
                        "\n".join(overwrite), width=YESNO_WIDTH):
132
                continue
133

    
134
        out = GaugeOutput(d, "Image Extraction", "Extracting image...")
135
        try:
136
            dev = session['device']
137
            if "checksum" not in session:
138
                size = dev.meta['SIZE']
139
                md5 = MD5(out)
140
                session['checksum'] = md5.compute(session['snapshot'], size)
141

    
142
            # Extract image file
143
            dev.out = out
144
            dev.dump(path)
145

    
146
            # Extract metadata file
147
            out.output("Extracting metadata file...")
148
            metastring = '\n'.join(
149
                ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
150
            metastring += '\n'
151
            with open('%s.meta' % path, 'w') as f:
152
                f.write(metastring)
153
            out.success('done')
154

    
155
            # Extract md5sum file
156
            out.output("Extracting md5sum file...")
157
            md5str = "%s %s\n" % (session['checksum'], name)
158
            with open('%s.md5sum' % path, 'w') as f:
159
                f.write(md5str)
160
            out.success("done")
161

    
162
        finally:
163
            out.cleanup()
164
        d.msgbox("Image file `%s' was successfully extracted!" % path,
165
                 width=MSGBOX_WIDTH)
166
        break
167

    
168
    return True
169

    
170

    
171
def upload_image(session):
172
    d = session["dialog"]
173
    size = session['device'].meta['SIZE']
174

    
175
    if "account" not in session:
176
        d.msgbox("You need to provide your ~okeanos login username before you "
177
                 "can upload images to pithos+", width=MSGBOX_WIDTH)
178
        return False
179

    
180
    if "token" not in session:
181
        d.msgbox("You need to provide your ~okeanos account authentication "
182
                 "token before you can upload images to pithos+",
183
                 width=MSGBOX_WIDTH)
184
        return False
185

    
186
    while 1:
187
        init = session["upload"] if "upload" in session else ''
188
        (code, answer) = d.inputbox("Please provide a filename:", init=init,
189
                                    width=INPUTBOX_WIDTH)
190

    
191
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
192
            return False
193

    
194
        filename = answer.strip()
195
        if len(filename) == 0:
196
            d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
197
            continue
198

    
199
        break
200

    
201
    out = GaugeOutput(d, "Image Upload", "Uploading...")
202
    if 'checksum' not in session:
203
        md5 = MD5(out)
204
        session['checksum'] = md5.compute(session['snapshot'], size)
205
    try:
206
        kamaki = Kamaki(session['account'], session['token'], out)
207
        try:
208
            # Upload image file
209
            with open(session['snapshot'], 'rb') as f:
210
                session["upload"] = kamaki.upload(f, size, filename,
211
                                                  "Calculating block hashes",
212
                                                  "Uploading missing blocks")
213
            # Upload metadata file
214
            out.output("Uploading metadata file...")
215
            metastring = '\n'.join(
216
                ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
217
            metastring += '\n'
218
            kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
219
                          remote_path="%s.meta" % filename)
220
            out.success("done")
221

    
222
            # Upload md5sum file
223
            out.output("Uploading md5sum file...")
224
            md5str = "%s %s\n" % (session['checksum'], filename)
225
            kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
226
                          remote_path="%s.md5sum" % filename)
227
            out.success("done")
228

    
229
        except ClientError as e:
230
            d.msgbox("Error in pithos+ client: %s" % e.message,
231
                     title="Pithos+ Client Error", width=MSGBOX_WIDTH)
232
            if 'upload' in session:
233
                del session['upload']
234
            return False
235
    finally:
236
        out.cleanup()
237

    
238
    d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
239
             width=MSGBOX_WIDTH)
240

    
241
    return True
242

    
243

    
244
def register_image(session):
245
    d = session["dialog"]
246

    
247
    if "account" not in session:
248
        d.msgbox("You need to provide your ~okeanos login username before you "
249
                 "can register an images to cyclades",
250
                 width=MSGBOX_WIDTH)
251
        return False
252

    
253
    if "token" not in session:
254
        d.msgbox("You need to provide your ~okeanos account authentication "
255
                 "token before you can register an images to cyclades",
256
                 width=MSGBOX_WIDTH)
257
        return False
258

    
259
    if "upload" not in session:
260
        d.msgbox("You need to have an image uploaded to pithos+ before you "
261
                 "can register it to cyclades",
262
                 width=MSGBOX_WIDTH)
263
        return False
264

    
265
    while 1:
266
        (code, answer) = d.inputbox("Please provide a registration name:"
267
                                " be registered:", width=INPUTBOX_WIDTH)
268
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
269
            return False
270

    
271
        name = answer.strip()
272
        if len(name) == 0:
273
            d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
274
            continue
275
        break
276

    
277
    out = GaugeOutput(d, "Image Registration", "Registrating image...")
278
    try:
279
        out.output("Registring image to cyclades...")
280
        try:
281
            kamaki = Kamaki(session['account'], session['token'], out)
282
            kamaki.register(name, session['upload'], session['metadata'])
283
            out.success('done')
284
        except ClientError as e:
285
            d.msgbox("Error in pithos+ client: %s" % e.message)
286
            return False
287
    finally:
288
        out.cleanup()
289

    
290
    d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
291
             (session['upload'], name), width=MSGBOX_WIDTH)
292
    return True
293

    
294

    
295
def kamaki_menu(session):
296
    d = session['dialog']
297
    default_item = "Account"
298
    while 1:
299
        account = session["account"] if "account" in session else "<none>"
300
        token = session["token"] if "token" in session else "<none>"
301
        upload = session["upload"] if "upload" in session else "<none>"
302
        (code, choice) = d.menu(
303
            "Choose one of the following or press <Back> to go back.",
304
            width=MENU_WIDTH,
305
            choices=[("Account", "Change your ~okeanos username: %s" %
306
                      account),
307
                     ("Token", "Change your ~okeanos token: %s" % token),
308
                     ("Upload", "Upload image to pithos+"),
309
                     ("Register", "Register image to cyclades: %s" % upload)],
310
            cancel="Back",
311
            default_item=default_item,
312
            help_button=1,
313
            title="Image Registration Menu")
314

    
315
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
316
            return False
317

    
318
        if choice == "Account":
319
            default_item = "Account"
320
            (code, answer) = d.inputbox(
321
                "Please provide your ~okeanos account e-mail address:",
322
                init=session["account"] if "account" in session else '',
323
                width=70)
324
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
325
                continue
326
            if len(answer) == 0 and "account" in session:
327
                    del session["account"]
328
            else:
329
                session["account"] = answer.strip()
330
                default_item = "Token"
331
        elif choice == "Token":
332
            default_item = "Token"
333
            (code, answer) = d.inputbox(
334
                "Please provide your ~okeanos account authetication token:",
335
                init=session["token"] if "token" in session else '',
336
                width=70)
337
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
338
                continue
339
            if len(answer) == 0 and "token" in session:
340
                del session["token"]
341
            else:
342
                session["token"] = answer.strip()
343
                default_item = "Upload"
344
        elif choice == "Upload":
345
            if upload_image(session):
346
                default_item = "Register"
347
            else:
348
                default_item = "Upload"
349
        elif choice == "Register":
350
            if register_image(session):
351
                return True
352
            else:
353
                default_item = "Register"
354

    
355

    
356
def add_property(session):
357
    d = session['dialog']
358

    
359
    while 1:
360
        (code, answer) = d.inputbox("Please provide a name for a new image"
361
                                    " property:", width=INPUTBOX_WIDTH)
362
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
363
            return False
364

    
365
        name = answer.strip()
366
        if len(name) == 0:
367
            d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
368
            continue
369

    
370
        break
371

    
372
    while 1:
373
        (code, answer) = d.inputbox("Please provide a value for image "
374
                                   "property %s" % name, width=INPUTBOX_WIDTH)
375
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
376
            return False
377

    
378
        value = answer.strip()
379
        if len(value) == 0:
380
            d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
381
            continue
382

    
383
        break
384

    
385
    session['metadata'][name] = value
386

    
387
    return True
388

    
389

    
390
def modify_properties(session):
391
    d = session['dialog']
392

    
393
    while 1:
394
        choices = []
395
        for (key, val) in session['metadata'].items():
396
            choices.append((str(key), str(val)))
397

    
398
        (code, choice) = d.menu(
399
            "In this menu you can edit existing image properties or add new "
400
            "ones. Be carefull! Most properties have special meaning and "
401
            "alter the image deployment behaviour. Press <HELP> to see more "
402
            "information about image properties. Press <BACK> when done.",
403
            height=18,
404
            width=MENU_WIDTH,
405
            choices=choices, menu_height=10,
406
            ok_label="EDIT", extra_button=1, extra_label="ADD", cancel="BACK",
407
            help_button=1, help_label="HELP", title="Image Metadata")
408

    
409
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
410
            break
411
        # Edit button
412
        elif code == d.DIALOG_OK:
413
            (code, answer) = d.inputbox("Please provide a new value for "
414
                    "the image property with name `%s':" % choice,
415
                    init=session['metadata'][choice], width=INPUTBOX_WIDTH)
416
            if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
417
                value = answer.strip()
418
                if len(value) == 0:
419
                    d.msgbox("Value cannot be empty!")
420
                    continue
421
                else:
422
                    session['metadata'][choice] = value
423
        # ADD button
424
        elif code == d.DIALOG_EXTRA:
425
            add_property(session)
426

    
427

    
428
def delete_properties(session):
429
    d = session['dialog']
430

    
431
    choices = []
432
    for (key, val) in session['metadata'].items():
433
        choices.append((key, "%s" % val, 0))
434

    
435
    (code, to_delete) = d.checklist("Choose which properties to delete:",
436
                                    choices=choices, width=CHECKBOX_WIDTH)
437
    count = len(to_delete)
438
    # If the user exits with ESC or CANCEL, the returned tag list is empty.
439
    for i in to_delete:
440
        del session['metadata'][i]
441

    
442
    if count > 0:
443
        d.msgbox("%d image properties were deleted.", width=MSGBOX_WIDTH)
444

    
445

    
446
def exclude_tasks(session):
447
    d = session['dialog']
448

    
449
    index = 0
450
    displayed_index = 1
451
    choices = []
452
    mapping = {}
453
    if 'excluded_tasks' not in session:
454
        session['excluded_tasks'] = []
455

    
456
    if -1 in session['excluded_tasks']:
457
        if not d.yesno("Image deployment configuration is disabled. "
458
                       "Do you wish to enable it?", width=YESNO_WIDTH):
459
            session['excluded_tasks'].remove(-1)
460
        else:
461
            return
462

    
463
    for (msg, task, osfamily) in CONFIGURATION_TASKS:
464
        if session['metadata']['OSFAMILY'] in osfamily:
465
            checked = 1 if index in session['excluded_tasks'] else 0
466
            choices.append((str(displayed_index), msg, checked))
467
            mapping[displayed_index] = index
468
            displayed_index += 1
469
        index += 1
470

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

    
482
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
483
            break
484
        elif code == d.DIALOG_HELP:
485
            help_file = get_help_file("configuration_tasks")
486
            assert os.path.exists(help_file)
487
            d.textbox(help_file, title="Configuration Tasks",
488
                                                        width=70, height=40)
489
            continue
490
        elif code == d.DIALOG_EXTRA:
491
            session['excluded_tasks'] = [-1]
492
            session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
493
            break
494
        elif code == d.DIALOG_OK:
495
            session['excluded_tasks'] = []
496
            for tag in tags:
497
                session['excluded_tasks'].append(mapping[int(tag)])
498

    
499
            exclude_metadata = []
500
            for task in session['excluded_tasks']:
501
                exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
502

    
503
            session['task_metadata'] = \
504
                        map(lambda x: "EXCLUDE_TASK_%s" % x, exclude_metadata)
505
            break
506

    
507

    
508
def sysprep(session):
509
    d = session['dialog']
510
    image_os = session['image_os']
511

    
512
    syspreps = image_os.list_syspreps()
513

    
514
    wrapper = textwrap.TextWrapper()
515
    wrapper.width = 65
516
    sysprep_help = "System Preperation Tasks"
517
    sysprep_help += "\n%s\n\n" % ('=' * len(sysprep_help))
518

    
519
    while 1:
520
        choices = []
521
        index = 0
522
        for sysprep in syspreps:
523
            name, descr = image_os.sysprep_info(sysprep)
524
            display_name = name.replace('-', ' ').capitalize()
525
            sysprep_help += "%s\n%s\n%s\n\n" % \
526
                            (display_name, '-' * len(display_name),
527
                            wrapper.fill(" ".join(descr.split())))
528
            enabled = 1 if sysprep.enabled else 0
529
            choices.append((str(index + 1), display_name, enabled))
530
            index += 1
531

    
532
        (code, tags) = d.checklist(
533
            "Please choose which system preperation tasks you would like to "
534
            "run on the image. Press <Help> to see details about the system "
535
            "preperation tasks.",
536
            title="Run system preperation tasks", choices=choices,
537
            width=70, ok_label="Run", help_button=1)
538

    
539
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
540
            break
541
        if code == d.DIALOG_HELP:
542
            d.scrollbox(sysprep_help, width=70)
543
            continue
544

    
545

    
546
def customize_menu(session):
547
    d = session['dialog']
548

    
549
    default_item = "Sysprep"
550
    actions = {"Sysprep": sysprep,
551
               "View/Modify": modify_properties,
552
               "Delete": delete_properties,
553
               "Exclude": exclude_tasks}
554
    while 1:
555
        (code, choice) = d.menu(
556
            "Choose one of the following or press <Back> to exit.",
557
            width=MENU_WIDTH,
558
            choices=[("Sysprep", "Run various image preperation tasks"),
559
                     ("Shrink", "Shrink image"),
560
                     ("View/Modify", "View/Modify image properties"),
561
                     ("Delete", "Delete image properties"),
562
                     ("Exclude",
563
                      "Exclude various deployment tasks from running")],
564
            cancel="Back",
565
            default_item=default_item,
566
            title="Image Customization Menu")
567

    
568
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
569
            break
570
        elif choice in actions:
571
            default_item = choice
572
            actions[choice](session)
573

    
574

    
575
def main_menu(session):
576
    d = session['dialog']
577
    dev = session['device']
578
    d.setBackgroundTitle("OS: %s, Distro: %s" % (dev.ostype, dev.distro))
579
    actions = {"Customize": customize_menu,
580
               "Register": kamaki_menu,
581
               "Extract": extract_image}
582
    default_item = "Customize"
583

    
584
    while 1:
585
        (code, choice) = d.menu(
586
            "Choose one of the following or press <Exit> to exit.",
587
            width=MENU_WIDTH,
588
            choices=[("Customize",
589
                      "Customize image and ~okeanos deployment options"),
590
                     ("Register", "Register image to ~okeanos"),
591
                     ("Extract", "Dump image to local file system"),
592
                     ("Reset", "Reset everything and start over again"),
593
                     ("Help", "Get help for using snf-image-creator")],
594
            cancel="Exit", menu_height=5, height=13, default_item=default_item,
595
            title="Image Creator for ~okeanos (snf-image-creator version %s)" %
596
                  version)
597

    
598
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
599
            if confirm_exit(d):
600
                break
601
        elif choice == "Reset":
602
            if confirm_reset(d):
603
                d.infobox("Resetting snf-image-creator. Please wait...")
604
                raise Reset
605
        elif choice in actions:
606
            actions[choice](session)
607

    
608

    
609
def select_file(d, media):
610
    root = os.sep
611
    while 1:
612
        if media is not None:
613
            if not os.path.exists(media):
614
                d.msgbox("The file you choose does not exist",
615
                         width=MSGBOX_WIDTH)
616
            else:
617
                break
618

    
619
        (code, media) = d.fselect(root, 10, 50,
620
                                 title="Please select input media")
621
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
622
            if confirm_exit(d, "You canceled the media selection dialog box."):
623
                sys.exit(0)
624
            else:
625
                media = None
626
                continue
627

    
628
    return media
629

    
630

    
631
def image_creator(d):
632
    basename = os.path.basename(sys.argv[0])
633
    usage = "Usage: %s [input_media]" % basename
634
    if len(sys.argv) > 2:
635
        sys.stderr.write("%s\n" % usage)
636
        return 1
637

    
638
    if os.geteuid() != 0:
639
        raise FatalError("You must run %s as root" % basename)
640

    
641
    media = select_file(d, sys.argv[1] if len(sys.argv) == 2 else None)
642

    
643
    out = InitializationOutput(d)
644
    disk = Disk(media, out)
645

    
646
    def signal_handler(signum, fram):
647
        out.cleanup()
648
        disk.cleanup()
649

    
650
    signal.signal(signal.SIGINT, signal_handler)
651
    try:
652
        snapshot = disk.snapshot()
653
        dev = disk.get_device(snapshot)
654

    
655
        out.output("Collecting image metadata...")
656
        metadata = dev.meta
657
        dev.mount(readonly=True)
658
        cls = os_cls(dev.distro, dev.ostype)
659
        image_os = cls(dev.root, dev.g, out)
660
        dev.umount()
661
        metadata.update(image_os.meta)
662
        out.success("done")
663
        out.cleanup()
664

    
665
        # Make sure the signal handler does not call out.cleanup again
666
        def dummy(self):
667
            pass
668
        instancemethod = type(InitializationOutput.cleanup)
669
        out.cleanup = instancemethod(dummy, out, InitializationOutput)
670

    
671
        session = {"dialog": d,
672
                   "disk": disk,
673
                   "snapshot": snapshot,
674
                   "device": dev,
675
                   "image_os": image_os,
676
                   "metadata": metadata}
677

    
678
        main_menu(session)
679
        d.infobox("Thank you for using snf-image-creator. Bye", width=53)
680
    finally:
681
        disk.cleanup()
682

    
683
    return 0
684

    
685

    
686
def main():
687

    
688
    d = dialog.Dialog(dialog="dialog")
689

    
690
    # Add extra button in dialog library
691
    dialog._common_args_syntax["extra_button"] = \
692
        lambda enable: dialog._simple_option("--extra-button", enable)
693

    
694
    dialog._common_args_syntax["extra_label"] = \
695
        lambda string: ("--extra-label", string)
696

    
697
    while 1:
698
        try:
699
            try:
700
                ret = image_creator(d)
701
                sys.exit(ret)
702
            except FatalError as e:
703
                msg = textwrap.fill(str(e), width=70)
704
                d.infobox(msg, width=70, title="Fatal Error")
705
                sys.exit(1)
706
        except Reset:
707
            continue
708

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