Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_main.py @ fbdf1d8f

History | View | Annotate | Download (31 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
from image_creator.dialog_wizard import wizard
52

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

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

    
78

    
79
class Reset(Exception):
80
    pass
81

    
82

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

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

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

    
96
        altered = {}
97
        added = {}
98

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

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

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

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

    
124

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

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

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

    
133

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

    
137

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

    
142

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

    
147
    MB = 2 ** 20
148

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

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

    
156
    d.setBackgroundTitle(title)
157

    
158

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
235
    return True
236

    
237

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

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

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

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

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

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

    
266
        break
267

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

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

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

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

    
306
    return True
307

    
308

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

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

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

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

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

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

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

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

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

    
364

    
365
def kamaki_menu(session):
366
    d = session['dialog']
367
    default_item = "Account"
368

    
369
    account = Kamaki.get_account()
370
    if account:
371
        session['account'] = account
372

    
373
    token = Kamaki.get_token()
374
    if token:
375
        session['token'] = token
376

    
377
    while 1:
378
        account = session["account"] if "account" in session else "<none>"
379
        token = session["token"] if "token" in session else "<none>"
380
        upload = session["upload"] if "upload" in session else "<none>"
381

    
382
        choices = [("Account", "Change your ~okeanos username: %s" % account),
383
                   ("Token", "Change your ~okeanos token: %s" % token),
384
                   ("Upload", "Upload image to pithos+"),
385
                   ("Register", "Register the image to cyclades: %s" % upload)]
386

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

    
393
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
394
            return False
395

    
396
        if choice == "Account":
397
            default_item = "Account"
398
            (code, answer) = d.inputbox(
399
                "Please provide your ~okeanos account e-mail address:",
400
                init=session["account"] if "account" in session else '',
401
                width=70)
402
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
403
                continue
404
            if len(answer) == 0 and "account" in session:
405
                    del session["account"]
406
            else:
407
                session["account"] = answer.strip()
408
                Kamaki.save_account(session['account'])
409
                default_item = "Token"
410
        elif choice == "Token":
411
            default_item = "Token"
412
            (code, answer) = d.inputbox(
413
                "Please provide your ~okeanos account authetication token:",
414
                init=session["token"] if "token" in session else '',
415
                width=70)
416
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
417
                continue
418
            if len(answer) == 0 and "token" in session:
419
                del session["token"]
420
            else:
421
                session["token"] = answer.strip()
422
                Kamaki.save_token(session['account'])
423
                default_item = "Upload"
424
        elif choice == "Upload":
425
            if upload_image(session):
426
                default_item = "Register"
427
            else:
428
                default_item = "Upload"
429
        elif choice == "Register":
430
            if register_image(session):
431
                return True
432
            else:
433
                default_item = "Register"
434

    
435

    
436
def add_property(session):
437
    d = session['dialog']
438

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

    
445
        name = answer.strip()
446
        if len(name) == 0:
447
            d.msgbox("A property name cannot be empty", width=MSGBOX_WIDTH)
448
            continue
449

    
450
        break
451

    
452
    while 1:
453
        (code, answer) = d.inputbox("Please provide a value for image "
454
                                    "property %s" % name, width=INPUTBOX_WIDTH)
455
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
456
            return False
457

    
458
        value = answer.strip()
459
        if len(value) == 0:
460
            d.msgbox("Value cannot be empty", width=MSGBOX_WIDTH)
461
            continue
462

    
463
        break
464

    
465
    session['metadata'][name] = value
466

    
467
    return True
468

    
469

    
470
def modify_properties(session):
471
    d = session['dialog']
472

    
473
    while 1:
474
        choices = []
475
        for (key, val) in session['metadata'].items():
476
            choices.append((str(key), str(val)))
477

    
478
        (code, choice) = d.menu(
479
            "In this menu you can edit existing image properties or add new "
480
            "ones. Be careful! Most properties have special meaning and "
481
            "alter the image deployment behaviour. Press <HELP> to see more "
482
            "information about image properties. Press <BACK> when done.",
483
            height=18, width=MENU_WIDTH, choices=choices, menu_height=10,
484
            ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back",
485
            help_button=1, title="Image Properties")
486

    
487
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
488
            return True
489
        # Edit button
490
        elif code == d.DIALOG_OK:
491
            (code, answer) = d.inputbox("Please provide a new value for the "
492
                                        "image property with name `%s':" %
493
                                        choice,
494
                                        init=session['metadata'][choice],
495
                                        width=INPUTBOX_WIDTH)
496
            if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC):
497
                value = answer.strip()
498
                if len(value) == 0:
499
                    d.msgbox("Value cannot be empty!")
500
                    continue
501
                else:
502
                    session['metadata'][choice] = value
503
        # ADD button
504
        elif code == d.DIALOG_EXTRA:
505
            add_property(session)
506
        elif code == 'help':
507
            help_file = get_help_file("image_properties")
508
            assert os.path.exists(help_file)
509
            d.textbox(help_file, title="Image Properties", width=70, height=40)
510

    
511

    
512
def delete_properties(session):
513
    d = session['dialog']
514

    
515
    choices = []
516
    for (key, val) in session['metadata'].items():
517
        choices.append((key, "%s" % val, 0))
518

    
519
    (code, to_delete) = d.checklist("Choose which properties to delete:",
520
                                    choices=choices, width=CHECKBOX_WIDTH)
521

    
522
    # If the user exits with ESC or CANCEL, the returned tag list is empty.
523
    for i in to_delete:
524
        del session['metadata'][i]
525

    
526
    cnt = len(to_delete)
527
    if cnt > 0:
528
        d.msgbox("%d image properties were deleted." % cnt, width=MSGBOX_WIDTH)
529
        return True
530
    else:
531
        return False
532

    
533

    
534
def exclude_tasks(session):
535
    d = session['dialog']
536

    
537
    index = 0
538
    displayed_index = 1
539
    choices = []
540
    mapping = {}
541
    if 'excluded_tasks' not in session:
542
        session['excluded_tasks'] = []
543

    
544
    if -1 in session['excluded_tasks']:
545
        if not d.yesno("Image deployment configuration is disabled. "
546
                       "Do you wish to enable it?", width=YESNO_WIDTH):
547
            session['excluded_tasks'].remove(-1)
548
        else:
549
            return False
550

    
551
    for (msg, task, osfamily) in CONFIGURATION_TASKS:
552
        if session['metadata']['OSFAMILY'] in osfamily:
553
            checked = 1 if index in session['excluded_tasks'] else 0
554
            choices.append((str(displayed_index), msg, checked))
555
            mapping[displayed_index] = index
556
            displayed_index += 1
557
        index += 1
558

    
559
    while 1:
560
        (code, tags) = d.checklist(
561
            text="Please choose which configuration tasks you would like to "
562
                 "prevent from running during image deployment. "
563
                 "Press <No Config> to supress any configuration. "
564
                 "Press <Help> for more help on the image deployment "
565
                 "configuration tasks.",
566
            choices=choices, height=19, list_height=8, width=CHECKBOX_WIDTH,
567
            help_button=1, extra_button=1, extra_label="No Config",
568
            title="Exclude Configuration Tasks")
569

    
570
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
571
            return False
572
        elif code == d.DIALOG_HELP:
573
            help_file = get_help_file("configuration_tasks")
574
            assert os.path.exists(help_file)
575
            d.textbox(help_file, title="Configuration Tasks",
576
                      width=70, height=40)
577
        # No Config button
578
        elif code == d.DIALOG_EXTRA:
579
            session['excluded_tasks'] = [-1]
580
            session['task_metadata'] = ["EXCLUDE_ALL_TASKS"]
581
            break
582
        elif code == d.DIALOG_OK:
583
            session['excluded_tasks'] = []
584
            for tag in tags:
585
                session['excluded_tasks'].append(mapping[int(tag)])
586

    
587
            exclude_metadata = []
588
            for task in session['excluded_tasks']:
589
                exclude_metadata.extend(CONFIGURATION_TASKS[task][1])
590

    
591
            session['task_metadata'] = map(lambda x: "EXCLUDE_TASK_%s" % x,
592
                                           exclude_metadata)
593
            break
594

    
595
    return True
596

    
597

    
598
def sysprep(session):
599
    d = session['dialog']
600
    image_os = session['image_os']
601

    
602
    # Is the image already shrinked?
603
    if 'shrinked' in session and session['shrinked']:
604
        msg = "It seems you have shrinked the image. Running system " \
605
              "preparation tasks on a shrinked image is dangerous."
606

    
607
        if d.yesno("%s\n\nDo you really want to continue?" % msg,
608
                   width=YESNO_WIDTH, defaultno=1):
609
            return
610

    
611
    wrapper = textwrap.TextWrapper(width=65)
612

    
613
    help_title = "System Preperation Tasks"
614
    sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title))
615

    
616
    if 'exec_syspreps' not in session:
617
        session['exec_syspreps'] = []
618

    
619
    all_syspreps = image_os.list_syspreps()
620
    # Only give the user the choice between syspreps that have not ran yet
621
    syspreps = [s for s in all_syspreps if s not in session['exec_syspreps']]
622

    
623
    if len(syspreps) == 0:
624
        d.msgbox("No system preparation task available to run!",
625
                 title="System Preperation", width=MSGBOX_WIDTH)
626
        return
627

    
628
    while 1:
629
        choices = []
630
        index = 0
631
        for sysprep in syspreps:
632
            name, descr = image_os.sysprep_info(sysprep)
633
            display_name = name.replace('-', ' ').capitalize()
634
            sysprep_help += "%s\n" % display_name
635
            sysprep_help += "%s\n" % ('-' * len(display_name))
636
            sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split()))
637
            enabled = 1 if sysprep.enabled else 0
638
            choices.append((str(index + 1), display_name, enabled))
639
            index += 1
640

    
641
        (code, tags) = d.checklist(
642
            "Please choose which system preperation tasks you would like to "
643
            "run on the image. Press <Help> to see details about the system "
644
            "preperation tasks.", title="Run system preperation tasks",
645
            choices=choices, width=70, ok_label="Run", help_button=1)
646

    
647
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
648
            return False
649
        elif code == d.DIALOG_HELP:
650
            d.scrollbox(sysprep_help, width=HELP_WIDTH)
651
        elif code == d.DIALOG_OK:
652
            # Enable selected syspreps and disable the rest
653
            for i in range(len(syspreps)):
654
                if str(i + 1) in tags:
655
                    image_os.enable_sysprep(syspreps[i])
656
                    session['exec_syspreps'].append(syspreps[i])
657
                else:
658
                    image_os.disable_sysprep(syspreps[i])
659

    
660
            out = InfoBoxOutput(d, "Image Configuration")
661
            try:
662
                dev = session['device']
663
                dev.out = out
664
                dev.mount(readonly=False)
665
                try:
666
                    # The checksum is invalid. We have mounted the image rw
667
                    if 'checksum' in session:
668
                        del session['checksum']
669

    
670
                    # Monitor the metadata changes during syspreps
671
                    with metadata_monitor(session, image_os.meta):
672
                        image_os.out = out
673
                        image_os.do_sysprep()
674
                        image_os.out.finalize()
675

    
676
                    # Disable syspreps that have ran
677
                    for sysprep in session['exec_syspreps']:
678
                        image_os.disable_sysprep(sysprep)
679

    
680
                finally:
681
                    dev.umount()
682
            finally:
683
                out.cleanup()
684
            break
685
    return True
686

    
687

    
688
def shrink(session):
689
    d = session['dialog']
690
    dev = session['device']
691

    
692
    shrinked = 'shrinked' in session and session['shrinked']
693

    
694
    if shrinked:
695
        d.msgbox("The image is already shrinked!", title="Image Shrinking",
696
                 width=MSGBOX_WIDTH)
697
        return True
698

    
699
    msg = "This operation will shrink the last partition of the image to " \
700
          "reduce the total image size. If the last partition is a swap " \
701
          "partition, then this partition is removed and the partition " \
702
          "before that is shrinked. The removed swap partition will be " \
703
          "recreated during image deployment."
704

    
705
    if not d.yesno("%s\n\nDo you want to continue?" % msg, width=70,
706
                   height=12, title="Image Shrinking"):
707
        with metadata_monitor(session, dev.meta):
708
            dev.out = InfoBoxOutput(d, "Image Shrinking", height=4)
709
            dev.shrink()
710
            dev.out.finalize()
711

    
712
        session['shrinked'] = True
713
        update_background_title(session)
714
    else:
715
        return False
716

    
717
    return True
718

    
719

    
720
def customization_menu(session):
721
    d = session['dialog']
722

    
723
    choices = [("Sysprep", "Run various image preperation tasks"),
724
               ("Shrink", "Shrink image"),
725
               ("View/Modify", "View/Modify image properties"),
726
               ("Delete", "Delete image properties"),
727
               ("Exclude", "Exclude various deployment tasks from running")]
728

    
729
    default_item = 0
730

    
731
    actions = {"Sysprep": sysprep,
732
               "Shrink": shrink,
733
               "View/Modify": modify_properties,
734
               "Delete": delete_properties,
735
               "Exclude": exclude_tasks}
736
    while 1:
737
        (code, choice) = d.menu(
738
            text="Choose one of the following or press <Back> to exit.",
739
            width=MENU_WIDTH, choices=choices, cancel="Back", height=13,
740
            menu_height=len(choices), default_item=choices[default_item][0],
741
            title="Image Customization Menu")
742

    
743
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
744
            break
745
        elif choice in actions:
746
            default_item = [entry[0] for entry in choices].index(choice)
747
            if actions[choice](session):
748
                default_item = (default_item + 1) % len(choices)
749

    
750

    
751
def main_menu(session):
752
    d = session['dialog']
753
    dev = session['device']
754

    
755
    update_background_title(session)
756

    
757
    choices = [("Customize", "Customize image & ~okeanos deployment options"),
758
               ("Register", "Register image to ~okeanos"),
759
               ("Extract", "Dump image to local file system"),
760
               ("Reset", "Reset everything and start over again"),
761
               ("Help", "Get help for using snf-image-creator")]
762

    
763
    default_item = "Customize"
764

    
765
    actions = {"Customize": customization_menu, "Register": kamaki_menu,
766
               "Extract": extract_image}
767
    while 1:
768
        (code, choice) = d.menu(
769
            text="Choose one of the following or press <Exit> to exit.",
770
            width=MENU_WIDTH, choices=choices, cancel="Exit", height=13,
771
            default_item=default_item, menu_height=len(choices),
772
            title="Image Creator for ~okeanos (snf-image-creator version %s)" %
773
                  version)
774

    
775
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
776
            if confirm_exit(d):
777
                break
778
        elif choice == "Reset":
779
            if confirm_reset(d):
780
                d.infobox("Resetting snf-image-creator. Please wait...",
781
                          width=INFOBOX_WIDTH)
782
                raise Reset
783
        elif choice in actions:
784
            actions[choice](session)
785

    
786

    
787
def select_file(d, media):
788
    root = os.sep
789
    while 1:
790
        if media is not None:
791
            if not os.path.exists(media):
792
                d.msgbox("The file `%s' you choose does not exist." % media,
793
                         width=MSGBOX_WIDTH)
794
            else:
795
                break
796

    
797
        (code, media) = d.fselect(root, 10, 50,
798
                                  title="Please select input media")
799
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
800
            if confirm_exit(d, "You canceled the media selection dialog box."):
801
                sys.exit(0)
802
            else:
803
                media = None
804
                continue
805

    
806
    return media
807

    
808

    
809
def image_creator(d):
810

    
811
    usage = "Usage: %prog [options] [<input_media>]"
812
    parser = optparse.OptionParser(version=version, usage=usage)
813

    
814
    options, args = parser.parse_args(sys.argv[1:])
815

    
816
    if len(args) > 1:
817
        parser.error("Wrong numver of arguments")
818

    
819
    d.setBackgroundTitle('snf-image-creator')
820

    
821
    if os.geteuid() != 0:
822
        raise FatalError("You must run %s as root" % parser.get_prog_name())
823

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

    
826
    out = GaugeOutput(d, "Initialization", "Initializing...")
827
    disk = Disk(media, out)
828

    
829
    def signal_handler(signum, frame):
830
        out.cleanup()
831
        disk.cleanup()
832

    
833
    signal.signal(signal.SIGINT, signal_handler)
834
    try:
835
        snapshot = disk.snapshot()
836
        dev = disk.get_device(snapshot)
837

    
838
        metadata = {}
839
        for (key, value) in dev.meta.items():
840
            metadata[str(key)] = str(value)
841

    
842
        dev.mount(readonly=True)
843
        out.output("Collecting image metadata...")
844
        cls = os_cls(dev.distro, dev.ostype)
845
        image_os = cls(dev.root, dev.g, out)
846
        dev.umount()
847

    
848
        for (key, value) in image_os.meta.items():
849
            metadata[str(key)] = str(value)
850

    
851
        out.success("done")
852
        out.cleanup()
853

    
854
        # Make sure the signal handler does not call out.cleanup again
855
        def dummy(self):
856
            pass
857
        out.cleanup = type(GaugeOutput.cleanup)(dummy, out, GaugeOutput)
858

    
859
        session = {"dialog": d,
860
                   "disk": disk,
861
                   "snapshot": snapshot,
862
                   "device": dev,
863
                   "image_os": image_os,
864
                   "metadata": metadata}
865

    
866
        msg = "snf-image-creator detected a %s system on the input media. " \
867
              "Would you like to run a wizards to assists you through the " \
868
              "image creation process?\n\nChoose <Yes> to run the wizard, " \
869
              "<No> to run the snf-image-creator in expert mode or press " \
870
              "ESC to quit the program." \
871
              % (dev.ostype if dev.ostype == dev.distro else "%s (%s)" %
872
                 (dev.ostype, dev.distro))
873

    
874
        update_background_title(session)
875

    
876
        while True:
877
            code = d.yesno(msg, width=YESNO_WIDTH, height=12)
878
            if code == d.DIALOG_OK:
879
                if wizard(session):
880
                    break
881
            elif code == d.DIALOG_CANCEL:
882
                main_menu(session)
883
                break
884

    
885
            if confirm_exit(d):
886
                break
887

    
888
        d.infobox("Thank you for using snf-image-creator. Bye", width=53)
889
    finally:
890
        disk.cleanup()
891

    
892
    return 0
893

    
894

    
895
def main():
896

    
897
    d = dialog.Dialog(dialog="dialog")
898

    
899
    # Add extra button in dialog library
900
    dialog._common_args_syntax["extra_button"] = \
901
        lambda enable: dialog._simple_option("--extra-button", enable)
902

    
903
    dialog._common_args_syntax["extra_label"] = \
904
        lambda string: ("--extra-label", string)
905

    
906
    while 1:
907
        try:
908
            try:
909
                ret = image_creator(d)
910
                sys.exit(ret)
911
            except FatalError as e:
912
                msg = textwrap.fill(str(e), width=70)
913
                d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
914
                sys.exit(1)
915
        except Reset:
916
            continue
917

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