Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_wizard.py @ bf3a282c

History | View | Annotate | Download (11.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 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.mount(False)
270
        err_msg = "Unable to execute the system preparation tasks."
271
        if not image.mounted:
272
            raise FatalError("%s Couldn't mount the media." % err_msg)
273
        elif image.mounted_ro:
274
            raise FatalError("%s Couldn't mount the media read-write."
275
                             % err_msg)
276
        image.os.do_sysprep()
277
        metadata = image.os.meta
278
        image.umount()
279

    
280
        #Shrink
281
        size = image.shrink()
282
        session['shrinked'] = True
283
        update_background_title(session)
284

    
285
        metadata.update(image.meta)
286
        metadata['DESCRIPTION'] = wizard['ImageDescription']
287

    
288
        #MD5
289
        md5 = MD5(out)
290
        session['checksum'] = md5.compute(image.device, size)
291

    
292
        #Metadata
293
        metastring = '\n'.join(
294
            ['%s=%s' % (key, value) for (key, value) in metadata.items()])
295
        metastring += '\n'
296

    
297
        out.output()
298
        try:
299
            out.output("Uploading image to pithos:")
300
            kamaki = Kamaki(wizard['Account'], out)
301

    
302
            name = "%s-%s.diskdump" % (wizard['ImageName'],
303
                                       time.strftime("%Y%m%d%H%M"))
304
            pithos_file = ""
305
            with open(image.device, 'rb') as f:
306
                pithos_file = kamaki.upload(f, size, name,
307
                                            "(1/4)  Calculating block hashes",
308
                                            "(2/4)  Uploading missing blocks")
309

    
310
            out.output("(3/4)  Uploading metadata file ...", False)
311
            kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
312
                          remote_path="%s.%s" % (name, 'meta'))
313
            out.success('done')
314
            out.output("(4/4)  Uploading md5sum file ...", False)
315
            md5sumstr = '%s %s\n' % (session['checksum'], name)
316
            kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
317
                          remote_path="%s.%s" % (name, 'md5sum'))
318
            out.success('done')
319
            out.output()
320

    
321
            is_public = True if wizard['ImageRegistration'] == "Public" else \
322
                False
323
            out.output('Registering %s image with ~okeanos ...' %
324
                       wizard['ImageRegistration'].lower(), False)
325
            kamaki.register(wizard['ImageName'], pithos_file, metadata,
326
                            is_public)
327
            out.success('done')
328
            if is_public:
329
                out.output("Sharing md5sum file ...", False)
330
                kamaki.share("%s.md5sum" % name)
331
                out.success('done')
332
                out.output("Sharing metadata file ...", False)
333
                kamaki.share("%s.meta" % name)
334
                out.success('done')
335

    
336
            out.output()
337

    
338
        except ClientError as e:
339
            raise FatalError("Pithos client: %d %s" % (e.status, e.message))
340
    finally:
341
        out.remove(with_progress)
342

    
343
    msg = "The %s image was successfully uploaded and registered with " \
344
          "~okeanos. Would you like to keep a local copy of the image?" \
345
          % wizard['ImageRegistration'].lower()
346
    if not d.yesno(msg, width=PAGE_WIDTH):
347
        extract_image(session)
348

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