Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_wizard.py @ 71b0ab28

History | View | Annotate | Download (11.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
    """Exception used to exit the wizard"""
49
    pass
50

    
51

    
52
class WizardInvalidData(Exception):
53
    """Exception triggered when the user provided data are invalid"""
54
    pass
55

    
56

    
57
class Wizard:
58
    """Represents a dialog-based wizard
59

60
    The wizard is a collection of pages that have a "Next" and a "Back" button
61
    on them. The pages are used to collect user data.
62
    """
63

    
64
    def __init__(self, session):
65
        self.session = session
66
        self.pages = []
67
        self.session['wizard'] = {}
68
        self.d = session['dialog']
69

    
70
    def add_page(self, page):
71
        """Add a new page to the wizard"""
72
        self.pages.append(page)
73

    
74
    def run(self):
75
        """Run the wizard"""
76
        idx = 0
77
        while True:
78
            try:
79
                idx += self.pages[idx].run(self.session, idx, len(self.pages))
80
            except WizardExit:
81
                return False
82
            except WizardInvalidData:
83
                continue
84

    
85
            if idx >= len(self.pages):
86
                msg = "All necessary information has been gathered:\n\n"
87
                for page in self.pages:
88
                    msg += " * %s\n" % page.info
89
                msg += "\nContinue with the image creation process?"
90

    
91
                ret = self.d.yesno(
92
                    msg, width=PAGE_WIDTH, height=8 + len(self.pages),
93
                    ok_label="Yes", cancel="Back", extra_button=1,
94
                    extra_label="Quit", title="Confirmation")
95

    
96
                if ret == self.d.DIALOG_CANCEL:
97
                    idx -= 1
98
                elif ret == self.d.DIALOG_EXTRA:
99
                    return False
100
                elif ret == self.d.DIALOG_OK:
101
                    return True
102

    
103
            if idx < 0:
104
                return False
105

    
106

    
107
class WizardPage(object):
108
    """Represents a page in a wizard"""
109
    NEXT = 1
110
    PREV = -1
111

    
112
    def __init__(self, **kargs):
113
        validate = kargs['validate'] if 'validate' in kargs else lambda x: x
114
        setattr(self, "validate", validate)
115

    
116
        display = kargs['display'] if 'display' in kargs else lambda x: x
117
        setattr(self, "display", display)
118

    
119
    def run(self, session, index, total):
120
        """Display this wizard page
121

122
        This function is used by the wizard program when accessing a page.
123
        """
124
        raise NotImplementedError
125

    
126

    
127
class WizardRadioListPage(WizardPage):
128
    """Represent a Radio List in a wizard"""
129
    def __init__(self, name, printable, message, choices, **kargs):
130
        super(WizardRadioListPage, self).__init__(**kargs)
131
        self.name = name
132
        self.printable = printable
133
        self.message = message
134
        self.choices = choices
135
        self.title = kargs['title'] if 'title' in kargs else ''
136
        self.default = kargs['default'] if 'default' in kargs else ""
137

    
138
    def run(self, session, index, total):
139
        d = session['dialog']
140
        w = session['wizard']
141

    
142
        choices = []
143
        for i in range(len(self.choices)):
144
            default = 1 if self.choices[i][0] == self.default else 0
145
            choices.append((self.choices[i][0], self.choices[i][1], default))
146

    
147
        (code, answer) = d.radiolist(
148
            self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
149
            cancel="Back", choices=choices,
150
            title="(%d/%d) %s" % (index + 1, total, self.title))
151

    
152
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
153
            return self.PREV
154

    
155
        w[self.name] = self.validate(answer)
156
        self.default = answer
157
        self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
158

    
159
        return self.NEXT
160

    
161

    
162
class WizardInputPage(WizardPage):
163
    """Represents an input field in a wizard"""
164
    def __init__(self, name, printable, message, **kargs):
165
        super(WizardInputPage, self).__init__(**kargs)
166
        self.name = name
167
        self.printable = printable
168
        self.message = message
169
        self.info = "%s: <none>" % self.printable
170
        self.title = kargs['title'] if 'title' in kargs else ''
171
        self.init = kargs['init'] if 'init' in kargs else ''
172

    
173
    def run(self, session, index, total):
174
        d = session['dialog']
175
        w = session['wizard']
176

    
177
        (code, answer) = d.inputbox(
178
            self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
179
            cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
180

    
181
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
182
            return self.PREV
183

    
184
        value = answer.strip()
185
        self.init = value
186
        w[self.name] = self.validate(value)
187
        self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
188

    
189
        return self.NEXT
190

    
191

    
192
def start_wizard(session):
193
    """Run the image creation wizard"""
194
    init_token = Kamaki.get_token()
195
    if init_token is None:
196
        init_token = ""
197

    
198
    distro = session['image'].distro
199
    ostype = session['image'].ostype
200
    name = WizardInputPage(
201
        "ImageName", "Image Name", "Please provide a name for the image:",
202
        title="Image Name", init=ostype if distro == "unknown" else distro)
203

    
204
    descr = WizardInputPage(
205
        "ImageDescription", "Image Description",
206
        "Please provide a description for the image:",
207
        title="Image Description", init=session['metadata']['DESCRIPTION'] if
208
        'DESCRIPTION' in session['metadata'] else '')
209

    
210
    registration = WizardRadioListPage(
211
        "ImageRegistration", "Registration Type",
212
        "Please provide a registration type:",
213
        [("Private", "Image is accessible only by this user"),
214
         ("Public", "Everyone can create VMs from this image")],
215
        title="Registration Type", default="Private")
216

    
217
    def validate_account(token):
218
        """Check if a token is valid"""
219
        d = session['dialog']
220

    
221
        if len(token) == 0:
222
            d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
223
            raise WizardInvalidData
224

    
225
        account = Kamaki.get_account(token)
226
        if account is None:
227
            d.msgbox("The token you provided in not valid!", width=PAGE_WIDTH)
228
            raise WizardInvalidData
229

    
230
        return account
231

    
232
    account = WizardInputPage(
233
        "Account", "Account",
234
        "Please provide your ~okeanos authentication token:",
235
        title="~okeanos account", init=init_token, validate=validate_account,
236
        display=lambda account: account['username'])
237

    
238
    w = Wizard(session)
239

    
240
    w.add_page(name)
241
    w.add_page(descr)
242
    w.add_page(registration)
243
    w.add_page(account)
244

    
245
    if w.run():
246
        create_image(session)
247
    else:
248
        return False
249

    
250
    return True
251

    
252

    
253
def create_image(session):
254
    """Create an image using the information collected by the wizard"""
255
    d = session['dialog']
256
    image = session['image']
257
    wizard = session['wizard']
258

    
259
    # Save Kamaki credentials
260
    Kamaki.save_token(wizard['Account']['auth_token'])
261

    
262
    with_progress = OutputWthProgress(True)
263
    out = image.out
264
    out.add(with_progress)
265
    try:
266
        out.clear()
267

    
268
        #Sysprep
269
        image.os.do_sysprep()
270
        metadata = image.os.meta
271

    
272
        #Shrink
273
        size = image.shrink()
274
        session['shrinked'] = True
275
        update_background_title(session)
276

    
277
        metadata.update(image.meta)
278
        metadata['DESCRIPTION'] = wizard['ImageDescription']
279

    
280
        #MD5
281
        md5 = MD5(out)
282
        session['checksum'] = md5.compute(image.device, size)
283

    
284
        #Metadata
285
        metastring = '\n'.join(
286
            ['%s=%s' % (key, value) for (key, value) in metadata.items()])
287
        metastring += '\n'
288

    
289
        out.output()
290
        try:
291
            out.output("Uploading image to pithos:")
292
            kamaki = Kamaki(wizard['Account'], out)
293

    
294
            name = "%s-%s.diskdump" % (wizard['ImageName'],
295
                                       time.strftime("%Y%m%d%H%M"))
296
            pithos_file = ""
297
            with open(image.device, 'rb') as f:
298
                pithos_file = kamaki.upload(f, size, name,
299
                                            "(1/4)  Calculating block hashes",
300
                                            "(2/4)  Uploading missing blocks")
301

    
302
            out.output("(3/4)  Uploading metadata file ...", False)
303
            kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
304
                          remote_path="%s.%s" % (name, 'meta'))
305
            out.success('done')
306
            out.output("(4/4)  Uploading md5sum file ...", False)
307
            md5sumstr = '%s %s\n' % (session['checksum'], name)
308
            kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
309
                          remote_path="%s.%s" % (name, 'md5sum'))
310
            out.success('done')
311
            out.output()
312

    
313
            is_public = True if wizard['ImageRegistration'] == "Public" else \
314
                False
315
            out.output('Registering %s image with ~okeanos ...' %
316
                       wizard['ImageRegistration'].lower(), False)
317
            kamaki.register(wizard['ImageName'], pithos_file, metadata,
318
                            is_public)
319
            out.success('done')
320
            if is_public:
321
                out.output("Sharing md5sum file ...", False)
322
                kamaki.share("%s.md5sum" % name)
323
                out.success('done')
324
                out.output("Sharing metadata file ...", False)
325
                kamaki.share("%s.meta" % name)
326
                out.success('done')
327

    
328
            out.output()
329

    
330
        except ClientError as e:
331
            raise FatalError("Pithos client: %d %s" % (e.status, e.message))
332
    finally:
333
        out.remove(with_progress)
334

    
335
    msg = "The %s image was successfully uploaded and registered with " \
336
          "~okeanos. Would you like to keep a local copy of the image?" \
337
          % wizard['ImageRegistration'].lower()
338
    if not d.yesno(msg, width=PAGE_WIDTH):
339
        extract_image(session)
340

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