Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_main.py @ 835171dc

History | View | Annotate | Download (29.8 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 GaugeOutput, InfoBoxOutput
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
HELP_WIDTH = 70
57
INFOBOX_WIDTH = 70
58

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

    
76

    
77
class Reset(Exception):
78
    pass
79

    
80

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

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

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

    
94
        altered = {}
95
        added = {}
96

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

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

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

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

    
122

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

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

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

    
131

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

    
135

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

    
140

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

    
145
    MB = 2 ** 20
146

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

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

    
154
    d.setBackgroundTitle(title)
155

    
156

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
233
    return True
234

    
235

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

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

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

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

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

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

    
264
        break
265

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

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

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

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

    
304
    return True
305

    
306

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

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

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

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

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

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

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

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

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

    
362

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

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

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

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

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

    
422

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

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

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

    
437
        break
438

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

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

    
450
        break
451

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

    
454
    return True
455

    
456

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

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

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

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

    
498

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

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

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

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

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

    
520

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

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

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

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

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

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

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

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

    
582
    return True
583

    
584

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
673

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

    
678
    shrinked = 'shrinked' in session and session['shrinked']
679

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

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

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

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

    
703
    return True
704

    
705

    
706
def customization_menu(session):
707
    d = session['dialog']
708

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

    
715
    default_item = 0
716

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

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

    
736

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

    
741
    update_background_title(session)
742

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

    
749
    default_item = "Customize"
750

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

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

    
772

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

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

    
792
    return media
793

    
794

    
795
def image_creator(d):
796
    basename = os.path.basename(sys.argv[0])
797
    usage = "Usage: %s [input_media]" % basename
798
    if len(sys.argv) > 2:
799
        sys.stderr.write("%s\n" % usage)
800
        return 1
801

    
802
    d.setBackgroundTitle('snf-image-creator')
803

    
804
    if os.geteuid() != 0:
805
        raise FatalError("You must run %s as root" % basename)
806

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

    
809
    out = GaugeOutput(d, "Initialization", "Initializing...")
810
    disk = Disk(media, out)
811

    
812
    def signal_handler(signum, frame):
813
        out.cleanup()
814
        disk.cleanup()
815

    
816
    signal.signal(signal.SIGINT, signal_handler)
817
    try:
818
        snapshot = disk.snapshot()
819
        dev = disk.get_device(snapshot)
820

    
821
        metadata = {}
822
        for (key, value) in dev.meta.items():
823
            metadata[str(key)] = str(value)
824

    
825
        dev.mount(readonly=True)
826
        out.output("Collecting image metadata...")
827
        cls = os_cls(dev.distro, dev.ostype)
828
        image_os = cls(dev.root, dev.g, out)
829
        dev.umount()
830

    
831
        for (key, value) in image_os.meta.items():
832
            metadata[str(key)] = str(value)
833

    
834
        out.success("done")
835
        out.cleanup()
836

    
837
        # Make sure the signal handler does not call out.cleanup again
838
        def dummy(self):
839
            pass
840
        out.cleanup = type(GaugeOutput.cleanup)(dummy, out, GaugeOutput)
841

    
842
        session = {"dialog": d,
843
                   "disk": disk,
844
                   "snapshot": snapshot,
845
                   "device": dev,
846
                   "image_os": image_os,
847
                   "metadata": metadata}
848

    
849
        main_menu(session)
850
        d.infobox("Thank you for using snf-image-creator. Bye", width=53)
851
    finally:
852
        disk.cleanup()
853

    
854
    return 0
855

    
856

    
857
def main():
858

    
859
    d = dialog.Dialog(dialog="dialog")
860

    
861
    # Add extra button in dialog library
862
    dialog._common_args_syntax["extra_button"] = \
863
        lambda enable: dialog._simple_option("--extra-button", enable)
864

    
865
    dialog._common_args_syntax["extra_label"] = \
866
        lambda string: ("--extra-label", string)
867

    
868
    while 1:
869
        try:
870
            try:
871
                ret = image_creator(d)
872
                sys.exit(ret)
873
            except FatalError as e:
874
                msg = textwrap.fill(str(e), width=70)
875
                d.infobox(msg, width=INFOBOX_WIDTH, title="Fatal Error")
876
                sys.exit(1)
877
        except Reset:
878
            continue
879

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