Revision 023e1217 image_creator/dialog_main.py

b/image_creator/dialog_main.py
38 38
import os
39 39
import textwrap
40 40
import signal
41
import StringIO
42 41
import optparse
43 42

  
44 43
from image_creator import __version__ as version
45
from image_creator.util import FatalError, MD5
44
from image_creator.util import FatalError
46 45
from image_creator.output import Output
47 46
from image_creator.output.cli import SimpleOutput
48
from image_creator.output.dialog import GaugeOutput, InfoBoxOutput
47
from image_creator.output.dialog import GaugeOutput
49 48
from image_creator.output.composite import CompositeOutput
50 49
from image_creator.disk import Disk
51 50
from image_creator.os_type import os_cls
52
from image_creator.kamaki_wrapper import Kamaki, ClientError
53
from image_creator.help import get_help_file
54 51
from image_creator.dialog_wizard import wizard
55

  
56
MSGBOX_WIDTH = 60
57
YESNO_WIDTH = 50
58
MENU_WIDTH = 70
59
INPUTBOX_WIDTH = 70
60
CHECKBOX_WIDTH = 70
61
HELP_WIDTH = 70
62
INFOBOX_WIDTH = 70
63

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

  
81

  
82
class Reset(Exception):
83
    pass
84

  
85

  
86
class metadata_monitor(object):
87
    def __init__(self, session, meta):
88
        self.session = session
89
        self.meta = meta
90

  
91
    def __enter__(self):
92
        self.old = {}
93
        for (k, v) in self.meta.items():
94
            self.old[k] = v
95

  
96
    def __exit__(self, type, value, traceback):
97
        d = self.session['dialog']
98

  
99
        altered = {}
100
        added = {}
101

  
102
        for (k, v) in self.meta.items():
103
            if k not in self.old:
104
                added[k] = v
105
            elif self.old[k] != v:
106
                altered[k] = v
107

  
108
        if not (len(added) or len(altered)):
109
            return
110

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

  
123
        self.session['metadata'].update(added)
124
        self.session['metadata'].update(altered)
125
        d.msgbox(msg, title="Image Property Changes", width=MSGBOX_WIDTH)
126

  
127

  
128
def extract_metadata_string(session):
129
    metadata = ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()]
130

  
131
    if 'task_metadata' in session:
132
        metadata.extend("%s=yes" % m for m in session['task_metadata'])
133

  
134
    return '\n'.join(metadata) + '\n'
135

  
136

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

  
140

  
141
def confirm_reset(d):
142
    return not d.yesno("Are you sure you want to reset everything?",
143
                       width=YESNO_WIDTH, defaultno=1)
144

  
145

  
146
def update_background_title(session):
147
    d = session['dialog']
148
    dev = session['device']
149

  
150
    MB = 2 ** 20
151

  
152
    size = (dev.size + MB - 1) // MB
153
    shrinked = 'shrinked' in session and session['shrinked']
154
    postfix = " (shrinked)" if shrinked else ''
155

  
156
    title = "OS: %s, Distro: %s, Size: %dMB%s" % \
157
            (dev.ostype, dev.distro, size, postfix)
158

  
159
    d.setBackgroundTitle(title)
160

  
161

  
162
def extract_image(session):
163
    d = session['dialog']
164
    dir = os.getcwd()
165
    while 1:
166
        if dir and dir[-1] != os.sep:
167
            dir = dir + os.sep
168

  
169
        (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
170
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
171
            return False
172

  
173
        if os.path.isdir(path):
174
            dir = path
175
            continue
176

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

  
182
        if os.path.isdir("%s.md5sum" % path):
183
            d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
184
                     width=MSGBOX_WIDTH)
185
            continue
186

  
187
        basedir = os.path.dirname(path)
188
        name = os.path.basename(path)
189
        if not os.path.exists(basedir):
190
            d.msgbox("Directory `%s' does not exist" % basedir,
191
                     width=MSGBOX_WIDTH)
192
            continue
193

  
194
        dir = basedir
195
        if len(name) == 0:
196
            continue
197

  
198
        files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
199
        overwrite = filter(os.path.exists, files)
200

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

  
207
        gauge = GaugeOutput(d, "Image Extraction", "Extracting image...")
208
        try:
209
            dev = session['device']
210
            out = dev.out
211
            out.add(gauge)
212
            try:
213
                if "checksum" not in session:
214
                    size = dev.size
215
                    md5 = MD5(out)
216
                    session['checksum'] = md5.compute(session['snapshot'],
217
                                                      size)
218

  
219
                # Extract image file
220
                dev.dump(path)
221

  
222
                # Extract metadata file
223
                out.output("Extracting metadata file...")
224
                with open('%s.meta' % path, 'w') as f:
225
                    f.write(extract_metadata_string(session))
226
                out.success('done')
227

  
228
                # Extract md5sum file
229
                out.output("Extracting md5sum file...")
230
                md5str = "%s %s\n" % (session['checksum'], name)
231
                with open('%s.md5sum' % path, 'w') as f:
232
                    f.write(md5str)
233
                out.success("done")
234
            finally:
235
                out.remove(gauge)
236
        finally:
237
            gauge.cleanup()
238
        d.msgbox("Image file `%s' was successfully extracted!" % path,
239
                 width=MSGBOX_WIDTH)
240
        break
241

  
242
    return True
243

  
244

  
245
def upload_image(session):
246
    d = session["dialog"]
247
    dev = session['device']
248
    size = dev.size
249

  
250
    if "account" not in session:
251
        d.msgbox("You need to provide your ~okeanos login username before you "
252
                 "can upload images to pithos+", width=MSGBOX_WIDTH)
253
        return False
254

  
255
    if "token" not in session:
256
        d.msgbox("You need to provide your ~okeanos account authentication "
257
                 "token before you can upload images to pithos+",
258
                 width=MSGBOX_WIDTH)
259
        return False
260

  
261
    while 1:
262
        init = session["upload"] if "upload" in session else ''
263
        (code, answer) = d.inputbox("Please provide a filename:", init=init,
264
                                    width=INPUTBOX_WIDTH)
265

  
266
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
267
            return False
268

  
269
        filename = answer.strip()
270
        if len(filename) == 0:
271
            d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
272
            continue
273
        session['upload'] = filename
274
        break
275

  
276
    gauge = GaugeOutput(d, "Image Upload", "Uploading...")
277
    try:
278
        out = dev.out
279
        out.add(gauge)
280
        try:
281
            if 'checksum' not in session:
282
                md5 = MD5(out)
283
                session['checksum'] = md5.compute(session['snapshot'], size)
284

  
285
            kamaki = Kamaki(session['account'], session['token'], out)
286
            try:
287
                # Upload image file
288
                with open(session['snapshot'], 'rb') as f:
289
                    session["pithos_uri"] = kamaki.upload(f, size, filename,
290
                                                    "Calculating block hashes",
291
                                                    "Uploading missing blocks")
292
                # Upload metadata file
293
                out.output("Uploading metadata file...")
294
                metastring = extract_metadata_string(session)
295
                kamaki.upload(StringIO.StringIO(metastring),
296
                              size=len(metastring),
297
                              remote_path="%s.meta" % filename)
298
                out.success("done")
299

  
300
                # Upload md5sum file
301
                out.output("Uploading md5sum file...")
302
                md5str = "%s %s\n" % (session['checksum'], filename)
303
                kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
304
                              remote_path="%s.md5sum" % filename)
305
                out.success("done")
306

  
307
            except ClientError as e:
308
                d.msgbox("Error in pithos+ client: %s" % e.message,
309
                         title="Pithos+ Client Error", width=MSGBOX_WIDTH)
310
                if 'pithos_uri' in session:
311
                    del session['pithos_uri']
312
                return False
313
        finally:
314
            out.remove(gauge)
315
    finally:
316
        gauge.cleanup()
317

  
318
    d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
319
             width=MSGBOX_WIDTH)
320

  
321
    return True
322

  
323

  
324
def register_image(session):
325
    d = session["dialog"]
326
    dev = session['device']
327

  
328
    if "account" not in session:
329
        d.msgbox("You need to provide your ~okeanos login username before you "
330
                 "can register an images to cyclades",
331
                 width=MSGBOX_WIDTH)
332
        return False
333

  
334
    if "token" not in session:
335
        d.msgbox("You need to provide your ~okeanos account authentication "
336
                 "token before you can register an images to cyclades",
337
                 width=MSGBOX_WIDTH)
338
        return False
339

  
340
    if "pithos_uri" not in session:
341
        d.msgbox("You need to upload the image to pithos+ before you can "
342
                 "register it to cyclades", width=MSGBOX_WIDTH)
343
        return False
344

  
345
    while 1:
346
        (code, answer) = d.inputbox("Please provide a registration name:",
347
                                    width=INPUTBOX_WIDTH)
348
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
349
            return False
350

  
351
        name = answer.strip()
352
        if len(name) == 0:
353
            d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
354
            continue
355
        break
356

  
357
    metadata = {}
358
    metadata.update(session['metadata'])
359
    if 'task_metadata' in session:
360
        for key in session['task_metadata']:
361
            metadata[key] = 'yes'
362

  
363
    gauge = GaugeOutput(d, "Image Registration", "Registering image...")
364
    try:
365
        out = dev.out
366
        out.add(gauge)
367
        try:
368
            out.output("Registering image with Cyclades...")
369
            try:
370
                kamaki = Kamaki(session['account'], session['token'], out)
371
                kamaki.register(name, session['pithos_uri'], metadata)
372
                out.success('done')
373
            except ClientError as e:
374
                d.msgbox("Error in pithos+ client: %s" % e.message)
375
                return False
376
        finally:
377
            out.remove(gauge)
378
    finally:
379
        gauge.cleanup()
380

  
381
    d.msgbox("Image `%s' was successfully registered with Cyclades as `%s'" %
382
             (session['upload'], name), width=MSGBOX_WIDTH)
383
    return True
384

  
385

  
386
def kamaki_menu(session):
387
    d = session['dialog']
388
    default_item = "Account"
389

  
390
    account = Kamaki.get_account()
391
    if account:
392
        session['account'] = account
393

  
394
    token = Kamaki.get_token()
395
    if token:
396
        session['token'] = token
397

  
398
    while 1:
399
        account = session["account"] if "account" in session else "<none>"
400
        token = session["token"] if "token" in session else "<none>"
401
        upload = session["upload"] if "upload" in session else "<none>"
402

  
403
        choices = [("Account", "Change your ~okeanos username: %s" % account),
404
                   ("Token", "Change your ~okeanos token: %s" % token),
405
                   ("Upload", "Upload image to pithos+"),
406
                   ("Register", "Register the image to cyclades: %s" % upload)]
407

  
408
        (code, choice) = d.menu(
409
            text="Choose one of the following or press <Back> to go back.",
410
            width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
411
            menu_height=5, default_item=default_item,
412
            title="Image Registration Menu")
413

  
414
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
415
            return False
416

  
417
        if choice == "Account":
418
            default_item = "Account"
419
            (code, answer) = d.inputbox(
420
                "Please provide your ~okeanos account e-mail address:",
421
                init=session["account"] if "account" in session else '',
422
                width=70)
423
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
424
                continue
425
            if len(answer) == 0 and "account" in session:
426
                    del session["account"]
427
            else:
428
                session["account"] = answer.strip()
429
                Kamaki.save_account(session['account'])
430
                default_item = "Token"
431
        elif choice == "Token":
432
            default_item = "Token"
433
            (code, answer) = d.inputbox(
434
                "Please provide your ~okeanos account authetication token:",
435
                init=session["token"] if "token" in session else '',
436
                width=70)
437
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
438
                continue
439
            if len(answer) == 0 and "token" in session:
440
                del session["token"]
441
            else:
442
                session["token"] = answer.strip()
443
                Kamaki.save_token(session['token'])
444
                default_item = "Upload"
445
        elif choice == "Upload":
446
            if upload_image(session):
447
                default_item = "Register"
448
            else:
449
                default_item = "Upload"
450
        elif choice == "Register":
451
            if register_image(session):
452
                return True
453
            else:
454
                default_item = "Register"
455

  
456

  
457
def add_property(session):
458
    d = session['dialog']
459

  
460
    while 1:
461
        (code, answer) = d.inputbox("Please provide a name for a new image"
462
                                    " property:", width=INPUTBOX_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=MSGBOX_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=INPUTBOX_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=MSGBOX_WIDTH)
482
            continue
483

  
484
        break
485

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

  
488
    return True
489

  
490

  
491
def modify_properties(session):
492
    d = session['dialog']
493

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

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

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

  
532

  
533
def delete_properties(session):
534
    d = session['dialog']
535

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

  
540
    (code, to_delete) = d.checklist("Choose which properties to delete:",
541
                                    choices=choices, width=CHECKBOX_WIDTH)
542

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

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

  
554

  
555
def exclude_tasks(session):
556
    d = session['dialog']
557

  
558
    index = 0
559
    displayed_index = 1
560
    choices = []
561
    mapping = {}
562
    if 'excluded_tasks' not in session:
563
        session['excluded_tasks'] = []
564

  
565
    if -1 in session['excluded_tasks']:
566
        if not d.yesno("Image deployment configuration is disabled. "
567
                       "Do you wish to enable it?", width=YESNO_WIDTH):
568
            session['excluded_tasks'].remove(-1)
569
        else:
570
            return False
571

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

  
580
    while 1:
581
        (code, tags) = d.checklist(
582
            text="Please choose which configuration tasks you would like to "
583
                 "prevent from running during image deployment. "
584
                 "Press <No Config> to supress any configuration. "
585
                 "Press <Help> for more help on the image deployment "
586
                 "configuration tasks.",
587
            choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
588
            help_button=1, extra_button=1, extra_label="No Config",
589
            title="Exclude Configuration Tasks")
590

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

  
608
            exclude_metadata = []
609
            for task in session['excluded_tasks']:
610
                exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
611

  
612
            session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
613
                                           exclude_metadata)
614
            break
615

  
616
    return True
617

  
618

  
619
def sysprep(session):
620
    d = session['dialog']
621
    image_os = session['image_os']
622

  
623
    # Is the image already shrinked?
624
    if 'shrinked' in session and session['shrinked']:
625
        msg = "It seems you have shrinked the image. Running system " \
626
              "preparation tasks on a shrinked image is dangerous."
627

  
628
        if d.yesno("%s\n\nDo you really want to continue?" % msg,
629
                   width=YESNO_WIDTH, defaultno=1):
630
            return
631

  
632
    wrapper = textwrap.TextWrapper(width=65)
633

  
634
    help_title = "System Preperation Tasks"
635
    sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
636

  
637
    if 'exec_syspreps' not in session:
638
        session['exec_syspreps'] = []
639

  
640
    all_syspreps = image_os.list_syspreps()
641
    # Only give the user the choice between syspreps that have not ran yet
642
    syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
643

  
644
    if len(syspreps) == 0:
645
        d.msgbox("No system preparation task available to run!",
646
                 title="System Preperation", width=MSGBOX_WIDTH)
647
        return
648

  
649
    while 1:
650
        choices = []
651
        index = 0
652
        for sysprep in syspreps:
653
            name, descr = image_os.sysprep_info(sysprep)
654
            display_name = name.replace('-', ' ').capitalize()
655
            sysprep_help += "%s\n" % display_name
656
            sysprep_help += "%s\n" % ('-' * len(display_name))
657
            sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
658
            enabled = 1 if sysprep.enabled else 0
659
            choices.append((str(index + 1), display_name, enabled))
660
            index += 1
661

  
662
        (code, tags) = d.checklist(
663
            "Please choose which system preparation tasks you would like to "
664
            "run on the image. Press <Help> to see details about the system "
665
            "preparation tasks.", title="Run system preparation tasks",
666
            choices=choices, width=70, ok_label="Run", help_button=1)
667

  
668
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
669
            return False
670
        elif code == d.DIALOG_HELP:
671
            d.scrollbox(sysprep_help, width=HELP_WIDTH)
672
        elif code == d.DIALOG_OK:
673
            # Enable selected syspreps and disable the rest
674
            for i in range(len(syspreps)):
675
                if str(i + 1) in tags:
676
                    image_os.enable_sysprep(syspreps[i])
677
                    session['exec_syspreps'].append(syspreps[i])
678
                else:
679
                    image_os.disable_sysprep(syspreps[i])
680

  
681
            infobox = InfoBoxOutput(d, "Image Configuration")
682
            try:
683
                dev = session['device']
684
                dev.out.add(infobox)
685
                try:
686
                    dev.mount(readonly=False)
687
                    try:
688
                        # The checksum is invalid. We have mounted the image rw
689
                        if 'checksum' in session:
690
                            del session['checksum']
691

  
692
                        # Monitor the metadata changes during syspreps
693
                        with metadata_monitor(session, image_os.meta):
694
                            image_os.do_sysprep()
695
                            infobox.finalize()
696

  
697
                        # Disable syspreps that have ran
698
                        for sysprep in session['exec_syspreps']:
699
                            image_os.disable_sysprep(sysprep)
700
                    finally:
701
                        dev.umount()
702
                finally:
703
                    dev.out.remove(infobox)
704
            finally:
705
                infobox.cleanup()
706
            break
707
    return True
708

  
709

  
710
def shrink(session):
711
    d = session['dialog']
712
    dev = session['device']
713

  
714
    shrinked = 'shrinked' in session and session['shrinked']
715

  
716
    if shrinked:
717
        d.msgbox("The image is already shrinked!", title="Image Shrinking",
718
                 width=MSGBOX_WIDTH)
719
        return True
720

  
721
    msg = "This operation will shrink the last partition of the image to " \
722
          "reduce the total image size. If the last partition is a swap " \
723
          "partition, then this partition is removed and the partition " \
724
          "before that is shrinked. The removed swap partition will be " \
725
          "recreated during image deployment."
726

  
727
    if not d.yesno("%s\n\nDo you want to continue?" % msg, width=70,
728
                   height=12, title="Image Shrinking"):
729
        with metadata_monitor(session, dev.meta):
730
            infobox = InfoBoxOutput(d, "Image Shrinking", height=4)
731
            dev.out.add(infobox)
732
            try:
733
                dev.shrink()
734
                infobox.finalize()
735
            finally:
736
                dev.out.remove(infobox)
737

  
738
        session['shrinked'] = True
739
        update_background_title(session)
740
    else:
741
        return False
742

  
743
    return True
744

  
745

  
746
def customization_menu(session):
747
    d = session['dialog']
748

  
749
    choices = [("Sysprep", "Run various image preparation tasks"),
750
               ("Shrink", "Shrink image"),
751
               ("View/Modify", "View/Modify image properties"),
752
               ("Delete", "Delete image properties"),
753
               ("Exclude", "Exclude various deployment tasks from running")]
754

  
755
    default_item = 0
756

  
757
    actions = {"Sysprep": sysprep,
758
               "Shrink": shrink,
759
               "View/Modify": modify_properties,
760
               "Delete": delete_properties,
761
               "Exclude": exclude_tasks}
762
    while 1:
763
        (code, choice) = d.menu(
764
            text="Choose one of the following or press <Back> to exit.",
765
            width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
766
            menu_height=len(choices), default_item=choices[default_item][0],
767
            title="Image Customization Menu")
768

  
769
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
770
            break
771
        elif choice in actions:
772
            default_item = [entry[0] for entry in choices].index(choice)
773
            if actions[choice](session):
774
                default_item = (default_item + 1) % len(choices)
775

  
776

  
777
def main_menu(session):
778
    d = session['dialog']
779
    dev = session['device']
780

  
781
    update_background_title(session)
782

  
783
    choices = [("Customize", "Customize image & ~okeanos deployment options"),
784
               ("Register", "Register image to ~okeanos"),
785
               ("Extract", "Dump image to local file system"),
786
               ("Reset", "Reset everything and start over again"),
787
               ("Help", "Get help for using snf-image-creator")]
788

  
789
    default_item = "Customize"
790

  
791
    actions = {"Customize": customization_menu, "Register": kamaki_menu,
792
               "Extract": extract_image}
793
    while 1:
794
        (code, choice) = d.menu(
795
            text="Choose one of the following or press <Exit> to exit.",
796
            width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
797
            default_item=default_item, menu_height=len(choices),
798
            title="Image Creator for ~okeanos (snf-image-creator version %s)" %
799
                  version)
800

  
801
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
802
            if confirm_exit(d):
803
                break
804
        elif choice == "Reset":
805
            if confirm_reset(d):
806
                d.infobox("Resetting snf-image-creator. Please wait...",
807
                          width=INFOBOX_WIDTH)
808
                raise Reset
809
        elif choice in actions:
810
            actions[choice](session)
52
from image_creator.dialog_menu import main_menu
53
from image_creator.dialog_util import SMALL_WIDTH, WIDTH, confirm_exit, \
54
    Reset, update_background_title
811 55

  
812 56

  
813 57
def image_creator(d, media, out):
......
859 103
        msg = "snf-image-creator detected a %s system on the input media. " \
860 104
              "Would you like to run a wizard to assist you through the " \
861 105
              "image creation process?\n\nChoose <Wizard> to run the wizard," \
862
              " <Expert> to run the snf-image-creator in expert mode or press " \
863
              "ESC to quit the program." \
106
              " <Expert> to run the snf-image-creator in expert mode or " \
107
              "press ESC to quit the program." \
864 108
              % (dev.ostype if dev.ostype == dev.distro else "%s (%s)" %
865 109
                 (dev.ostype, dev.distro))
866 110

  
867 111
        update_background_title(session)
868 112

  
869 113
        while True:
870
            code = d.yesno(msg, width=YESNO_WIDTH, height=12,
871
                           yes_label="Wizard", no_label="Expert")
114
            code = d.yesno(msg, width=WIDTH, height=12, yes_label="Wizard",
115
                           no_label="Expert")
872 116
            if code == d.DIALOG_OK:
873 117
                if wizard(session):
874 118
                    break
......
892 136
        if media is not None:
893 137
            if not os.path.exists(media):
894 138
                d.msgbox("The file `%s' you choose does not exist." % media,
895
                         width=MSGBOX_WIDTH)
139
                         width=SMALL_WIDTH)
896 140
            else:
897 141
                break
898 142

  
......
941 185

  
942 186
    try:
943 187
        if os.geteuid() != 0:
944
            raise FatalError("You must run %s as root" % \
188
            raise FatalError("You must run %s as root" %
945 189
                             parser.get_prog_name())
946 190

  
947 191
        media = select_file(d, args[0] if len(args) == 1 else None)
......
952 196
                logfile = open(options.logfile, 'w')
953 197
            except IOError as e:
954 198
                raise FatalError(
955
                    "Unable to open logfile `%s' for writing. Reason: %s" % \
199
                    "Unable to open logfile `%s' for writing. Reason: %s" %
956 200
                    (options.logfile, e.strerror))
957 201
        try:
958 202
            log = SimpleOutput(False, logfile) if logfile is not None \
959
                                               else Output()
203
                else Output()
960 204
            while 1:
961 205
                try:
962 206
                    out = CompositeOutput([log])
963
                    out.output("Starting %s v%s..." % \
207
                    out.output("Starting %s v%s..." %
964 208
                               (parser.get_prog_name(), version))
965 209
                    ret = image_creator(d, media, out)
966 210
                    sys.exit(ret)
......
971 215
            if logfile is not None:
972 216
                logfile.close()
973 217
    except FatalError as e:
974
        msg = textwrap.fill(str(e), width=70)
975
        d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
218
        msg = textwrap.fill(str(e), width=WIDTH)
219
        d.infobox(msg, width=WIDTH, title="Fatal Error")
976 220
        sys.exit(1)
977 221

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

Also available in: Unified diff