Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_wizard.py @ 61d14323

History | View | Annotate | Download (10.4 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 time
37
import StringIO
38

    
39
from image_creator.kamaki_wrapper import Kamaki, ClientError
40
from image_creator.util import MD5, FatalError
41
from image_creator.output.cli import OutputWthProgress
42
from image_creator.dialog_util import extract_image, update_background_title
43

    
44
PAGE_WIDTH = 70
45

    
46

    
47
class WizardExit(Exception):
48
    pass
49

    
50

    
51
class WizardInvalidData(Exception):
52
    pass
53

    
54

    
55
class Wizard:
56
    def __init__(self, session):
57
        self.session = session
58
        self.pages = []
59
        self.session['wizard'] = {}
60
        self.d = session['dialog']
61

    
62
    def add_page(self, page):
63
        self.pages.append(page)
64

    
65
    def run(self):
66
        idx = 0
67
        while True:
68
            try:
69
                idx += self.pages[idx].run(self.session, idx, len(self.pages))
70
            except WizardExit:
71
                return False
72
            except WizardInvalidData:
73
                continue
74

    
75
            if idx >= len(self.pages):
76
                msg = "All necessary information has been gathered:\n\n"
77
                for page in self.pages:
78
                    msg += " * %s\n" % page.info
79
                msg += "\nContinue with the image creation process?"
80

    
81
                ret = self.d.yesno(
82
                    msg, width=PAGE_WIDTH, height=8 + len(self.pages),
83
                    ok_label="Yes", cancel="Back", extra_button=1,
84
                    extra_label="Quit", title="Confirmation")
85

    
86
                if ret == self.d.DIALOG_CANCEL:
87
                    idx -= 1
88
                elif ret == self.d.DIALOG_EXTRA:
89
                    return False
90
                elif ret == self.d.DIALOG_OK:
91
                    return True
92

    
93
            if idx < 0:
94
                return False
95

    
96

    
97
class WizardPage(object):
98
    NEXT = 1
99
    PREV = -1
100

    
101
    def __init__(self, **kargs):
102
        validate = kargs['validate'] if 'validate' in kargs else lambda x: x
103
        setattr(self, "validate", validate)
104

    
105
        display = kargs['display'] if 'display' in kargs else lambda x: x
106
        setattr(self, "display", display)
107

    
108
    def run(self, session, index, total):
109
        raise NotImplementedError
110

    
111

    
112
class WizardRadioListPage(WizardPage):
113

    
114
    def __init__(self, name, printable, message, choices, **kargs):
115
        super(WizardRadioListPage, self).__init__(**kargs)
116
        self.name = name
117
        self.printable = printable
118
        self.message = message
119
        self.choices = choices
120
        self.title = kargs['title'] if 'title' in kargs else ''
121
        self.default = kargs['default'] if 'default' in kargs else ""
122

    
123
    def run(self, session, index, total):
124
        d = session['dialog']
125
        w = session['wizard']
126

    
127
        choices = []
128
        for i in range(len(self.choices)):
129
            default = 1 if self.choices[i][0] == self.default else 0
130
            choices.append((self.choices[i][0], self.choices[i][1], default))
131

    
132
        (code, answer) = d.radiolist(
133
            self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
134
            cancel="Back", choices=choices,
135
            title="(%d/%d) %s" % (index + 1, total, self.title))
136

    
137
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
138
            return self.PREV
139

    
140
        w[self.name] = self.validate(answer)
141
        self.default = answer
142
        self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
143

    
144
        return self.NEXT
145

    
146

    
147
class WizardInputPage(WizardPage):
148

    
149
    def __init__(self, name, printable, message, **kargs):
150
        super(WizardInputPage, self).__init__(**kargs)
151
        self.name = name
152
        self.printable = printable
153
        self.message = message
154
        self.title = kargs['title'] if 'title' in kargs else ''
155
        self.init = kargs['init'] if 'init' in kargs else ''
156

    
157
    def run(self, session, index, total):
158
        d = session['dialog']
159
        w = session['wizard']
160

    
161
        (code, answer) = d.inputbox(
162
            self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
163
            cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
164

    
165
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
166
            return self.PREV
167

    
168
        value = answer.strip()
169
        self.init = value
170
        w[self.name] = self.validate(value)
171
        self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
172

    
173
        return self.NEXT
174

    
175

    
176
def wizard(session):
177
    init_token = Kamaki.get_token()
178
    if init_token is None:
179
        init_token = ""
180

    
181
    name = WizardInputPage(
182
        "ImageName", "Image Name", "Please provide a name for the image:",
183
        title="Image Name", init=session['device'].distro)
184

    
185
    descr = WizardInputPage(
186
        "ImageDescription", "Image Description",
187
        "Please provide a description for the image:",
188
        title="Image Description", init=session['metadata']['DESCRIPTION'] if
189
        'DESCRIPTION' in session['metadata'] else '')
190

    
191
    registration = WizardRadioListPage(
192
        "ImageRegistration", "Registration Type",
193
        "Please provide a registration type:",
194
        [("Private", "Image is accessible only by this user"),
195
         ("Public", "Everyone can create VMs from this image")],
196
        title="Registration Type", default="Private")
197

    
198
    def validate_account(token):
199
        d = session['dialog']
200

    
201
        if len(token) == 0:
202
            d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
203
            raise WizardInvalidData
204

    
205
        account = Kamaki.get_account(token)
206
        if account is None:
207
            d.msgbox("The token you provided in not valid!", width=PAGE_WIDTH)
208
            raise WizardInvalidData
209

    
210
        return account
211

    
212
    account = WizardInputPage(
213
        "Account", "Account",
214
        "Please provide your ~okeanos authentication token:",
215
        title="~okeanos account", init=init_token, validate=validate_account,
216
        display=lambda account: account['username'])
217

    
218
    w = Wizard(session)
219

    
220
    w.add_page(name)
221
    w.add_page(descr)
222
    w.add_page(registration)
223
    w.add_page(account)
224

    
225
    if w.run():
226
        create_image(session)
227
    else:
228
        return False
229

    
230
    return True
231

    
232

    
233
def create_image(session):
234
    d = session['dialog']
235
    disk = session['disk']
236
    device = session['device']
237
    snapshot = session['snapshot']
238
    image_os = session['image_os']
239
    wizard = session['wizard']
240

    
241
    # Save Kamaki credentials
242
    Kamaki.save_token(wizard['Account']['auth_token'])
243

    
244
    with_progress = OutputWthProgress(True)
245
    out = disk.out
246
    out.add(with_progress)
247
    try:
248
        out.clear()
249

    
250
        #Sysprep
251
        device.mount(False)
252
        image_os.do_sysprep()
253
        metadata = image_os.meta
254
        device.umount()
255

    
256
        #Shrink
257
        size = device.shrink()
258
        session['shrinked'] = True
259
        update_background_title(session)
260

    
261
        metadata.update(device.meta)
262
        metadata['DESCRIPTION'] = wizard['ImageDescription']
263

    
264
        #MD5
265
        md5 = MD5(out)
266
        session['checksum'] = md5.compute(snapshot, size)
267

    
268
        #Metadata
269
        metastring = '\n'.join(
270
            ['%s=%s' % (key, value) for (key, value) in metadata.items()])
271
        metastring += '\n'
272

    
273
        out.output()
274
        try:
275
            out.output("Uploading image to pithos:")
276
            kamaki = Kamaki(wizard['Account'], out)
277

    
278
            name = "%s-%s.diskdump" % (wizard['ImageName'],
279
                                       time.strftime("%Y%m%d%H%M"))
280
            pithos_file = ""
281
            with open(snapshot, 'rb') as f:
282
                pithos_file = kamaki.upload(f, size, name,
283
                                            "(1/4)  Calculating block hashes",
284
                                            "(2/4)  Uploading missing blocks")
285

    
286
            out.output("(3/4)  Uploading metadata file ...", False)
287
            kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
288
                          remote_path="%s.%s" % (name, 'meta'))
289
            out.success('done')
290
            out.output("(4/4)  Uploading md5sum file ...", False)
291
            md5sumstr = '%s %s\n' % (session['checksum'], name)
292
            kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
293
                          remote_path="%s.%s" % (name, 'md5sum'))
294
            out.success('done')
295
            out.output()
296

    
297
            is_public = True if wizard['ImageRegistration'] == "Public" else \
298
                False
299
            out.output('Registering %s image with ~okeanos ...' %
300
                       wizard['ImageRegistration'].lower(), False)
301
            kamaki.register(wizard['ImageName'], pithos_file, metadata,
302
                            is_public)
303
            out.success('done')
304
            out.output()
305

    
306
        except ClientError as e:
307
            raise FatalError("Pithos client: %d %s" % (e.status, e.message))
308
    finally:
309
        out.remove(with_progress)
310

    
311
    msg = "The %s image was successfully uploaded and registered with " \
312
          "~okeanos. Would you like to keep a local copy of the image?" \
313
          % wizard['ImageRegistration'].lower()
314
    if not d.yesno(msg, width=PAGE_WIDTH):
315
        extract_image(session)
316

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