Statistics
| Branch: | Tag: | Revision:

root / image_creator / dialog_wizard.py @ fbdf1d8f

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

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

    
44
PAGE_WIDTH = 70
45

    
46

    
47
class Wizard:
48
    def __init__(self, session):
49
        self.session = session
50
        self.pages = []
51
        self.session['wizard'] = {}
52

    
53
    def add_page(self, page):
54
        self.pages.append(page)
55

    
56
    def run(self):
57
        idx = 0
58
        while True:
59
            idx += self.pages[idx].run(self.session, idx, len(self.pages))
60

    
61
            if idx >= len(self.pages):
62
                break
63

    
64
            if idx < 0:
65
                return False
66
        return True
67

    
68

    
69
class WizardPage:
70
    NEXT = 1
71
    PREV = -1
72
    EXIT = -255
73

    
74
    def run(self, session, index, total):
75
        raise NotImplementedError
76

    
77

    
78
class WizardInputPage(WizardPage):
79

    
80
    def __init__(self, name, message, **kargs):
81
        self.name = name
82
        self.message = message
83
        self.title = kargs['title'] if 'title' in kargs else ''
84
        self.init_value = kargs['init'] if 'init' in kargs else ''
85
        self.allow_empty = kargs['empty'] if 'empty' in kargs else False
86

    
87
    def run(self, session, index, total):
88
        d = session['dialog']
89
        w = session['wizard']
90

    
91
        init = w[self.name] if self.name in w else self.init_value
92
        while True:
93
            (code, answer) = d.inputbox(self.message, init=init,
94
                width=PAGE_WIDTH, ok_label="Next", cancel="Back",
95
                title="(%d/%d) %s" % (index + 1, total, self.title))
96

    
97
            if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
98
                return self.PREV
99

    
100
            value = answer.strip()
101
            if len(value) == 0 and self.allow_empty is False:
102
                d.msgbox("The value cannot be empty!", width=PAGE_WIDTH)
103
                continue
104
            w[self.name] = value
105
            break
106

    
107
        return self.NEXT
108

    
109

    
110
class WizardYesNoPage(WizardPage):
111

    
112
    def __init__(self, message, **kargs):
113
        self.message = message
114
        self.title = kargs['title'] if 'title' in kargs else ''
115

    
116
    def run(self, session, index, total):
117
        d = session['dialog']
118

    
119
        while True:
120
            ret = d.yesno(self.message, width=PAGE_WIDTH, ok_label="Yes",
121
                    cancel="Back", extra_button=1, extra_label="Quit",
122
                    title="(%d/%d) %s" % (index + 1, total, self.title))
123

    
124
            if ret == d.DIALOG_CANCEL:
125
                return self.PREV
126
            elif ret == d.DIALOG_EXTRA:
127
                return self.EXIT
128
            elif ret == d.DIALOG_OK:
129
                return self.NEXT
130

    
131

    
132
def wizard(session):
133

    
134
    name = WizardInputPage("ImageName", "Please provide a name for the image:",
135
                      title="Image Name", init=session['device'].distro)
136
    descr = WizardInputPage("ImageDescription",
137
        "Please provide a description for the image:",
138
        title="Image Description", empty=True,
139
        init=session['metadata']['DESCRIPTION'] if 'DESCRIPTION' in
140
        session['metadata'] else '')
141
    account = WizardInputPage("account",
142
        "Please provide your ~okeanos account e-mail:",
143
        title="~okeanos account information", init=Kamaki.get_account())
144
    token = WizardInputPage("token",
145
        "Please provide your ~okeanos account token:",
146
        title="~okeanos account token", init=Kamaki.get_token())
147

    
148
    msg = "Do you wish to continue with the image extraction process?"
149
    proceed = WizardYesNoPage(msg, title="Confirmation")
150

    
151
    w = Wizard(session)
152

    
153
    w.add_page(name)
154
    w.add_page(descr)
155
    w.add_page(account)
156
    w.add_page(token)
157
    w.add_page(proceed)
158

    
159
    if w.run():
160
        extract_image(session)
161
    else:
162
        return False
163

    
164
    return True
165

    
166

    
167
def extract_image(session):
168
    disk = session['disk']
169
    device = session['device']
170
    snapshot = session['snapshot']
171
    image_os = session['image_os']
172
    wizard = session['wizard']
173

    
174
    out = OutputWthProgress(True)
175
    #Initialize the output
176
    disk.out = out
177
    device.out = out
178
    image_os.out = out
179

    
180
    out.output()
181

    
182
    #Sysprep
183
    device.mount(False)
184
    image_os.do_sysprep()
185
    metadata = image_os.meta
186
    device.umount()
187

    
188
    #Shrink
189
    size = device.shrink()
190

    
191
    #MD5
192
    md5 = MD5(out)
193
    checksum = md5.compute(snapshot, size)
194

    
195
    #Metadata
196
    metastring = '\n'.join(
197
        ['%s=%s' % (key, value) for (key, value) in metadata.items()])
198
    metastring += '\n'
199

    
200
    out.output()
201
    try:
202
        out.output("Uploading image to pithos:")
203
        kamaki = Kamaki(wizard['account'], wizard['token'], out)
204

    
205
        name = "%s-%s.diskdump" % (wizard['ImageName'],
206
                                   time.strftime("%Y%m%d%H%M"))
207
        pithos_file = ""
208
        with open(snapshot, 'rb') as f:
209
            pithos_file = kamaki.upload(f, size, name,
210
                                         "(1/4)  Calculating block hashes",
211
                                         "(2/4)  Uploading missing blocks")
212

    
213
        out.output("(3/4)  Uploading metadata file...", False)
214
        kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
215
                      remote_path="%s.%s" % (name, 'meta'))
216
        out.success('done')
217
        out.output("(4/4)  Uploading md5sum file...", False)
218
        md5sumstr = '%s %s\n' % (checksum, name)
219
        kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
220
                      remote_path="%s.%s" % (name, 'md5sum'))
221
        out.success('done')
222
        out.output()
223

    
224
        out.output('Registring image to ~okeanos...', False)
225
        kamaki.register(wizard['ImageName'], pithos_file, metadata)
226
        out.success('done')
227
        out.output()
228
    except ClientError as e:
229
        raise FatalError("Pithos client: %d %s" % (e.status, e.message))
230

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