root / image_creator / dialog_wizard.py @ 84bc469c
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 |
name = WizardInputPage( |
199 |
"ImageName", "Image Name", "Please provide a name for the image:", |
200 |
title="Image Name", init=session['image'].distro) |
201 |
|
202 |
descr = WizardInputPage( |
203 |
"ImageDescription", "Image Description", |
204 |
"Please provide a description for the image:",
|
205 |
title="Image Description", init=session['metadata']['DESCRIPTION'] if |
206 |
'DESCRIPTION' in session['metadata'] else '') |
207 |
|
208 |
registration = WizardRadioListPage( |
209 |
"ImageRegistration", "Registration Type", |
210 |
"Please provide a registration type:",
|
211 |
[("Private", "Image is accessible only by this user"), |
212 |
("Public", "Everyone can create VMs from this image")], |
213 |
title="Registration Type", default="Private") |
214 |
|
215 |
def validate_account(token): |
216 |
"""Check if a token is valid"""
|
217 |
d = session['dialog']
|
218 |
|
219 |
if len(token) == 0: |
220 |
d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
|
221 |
raise WizardInvalidData
|
222 |
|
223 |
account = Kamaki.get_account(token) |
224 |
if account is None: |
225 |
d.msgbox("The token you provided in not valid!", width=PAGE_WIDTH)
|
226 |
raise WizardInvalidData
|
227 |
|
228 |
return account
|
229 |
|
230 |
account = WizardInputPage( |
231 |
"Account", "Account", |
232 |
"Please provide your ~okeanos authentication token:",
|
233 |
title="~okeanos account", init=init_token, validate=validate_account,
|
234 |
display=lambda account: account['username']) |
235 |
|
236 |
w = Wizard(session) |
237 |
|
238 |
w.add_page(name) |
239 |
w.add_page(descr) |
240 |
w.add_page(registration) |
241 |
w.add_page(account) |
242 |
|
243 |
if w.run():
|
244 |
create_image(session) |
245 |
else:
|
246 |
return False |
247 |
|
248 |
return True |
249 |
|
250 |
|
251 |
def create_image(session): |
252 |
"""Create an image using the information collected by the wizard"""
|
253 |
d = session['dialog']
|
254 |
image = session['image']
|
255 |
wizard = session['wizard']
|
256 |
|
257 |
# Save Kamaki credentials
|
258 |
Kamaki.save_token(wizard['Account']['auth_token']) |
259 |
|
260 |
with_progress = OutputWthProgress(True)
|
261 |
out = image.out |
262 |
out.add(with_progress) |
263 |
try:
|
264 |
out.clear() |
265 |
|
266 |
#Sysprep
|
267 |
image.mount(False)
|
268 |
err_msg = "Unable to execute the system preparation tasks."
|
269 |
if not image.mounted: |
270 |
raise FatalError("%s Couldn't mount the media." % err_msg) |
271 |
elif image.mounted_ro:
|
272 |
raise FatalError("%s Couldn't mount the media read-write." |
273 |
% err_msg) |
274 |
image.os.do_sysprep() |
275 |
metadata = image.os.meta |
276 |
image.umount() |
277 |
|
278 |
#Shrink
|
279 |
size = image.shrink() |
280 |
session['shrinked'] = True |
281 |
update_background_title(session) |
282 |
|
283 |
metadata.update(image.meta) |
284 |
metadata['DESCRIPTION'] = wizard['ImageDescription'] |
285 |
|
286 |
#MD5
|
287 |
md5 = MD5(out) |
288 |
session['checksum'] = md5.compute(image.device, size)
|
289 |
|
290 |
#Metadata
|
291 |
metastring = '\n'.join(
|
292 |
['%s=%s' % (key, value) for (key, value) in metadata.items()]) |
293 |
metastring += '\n'
|
294 |
|
295 |
out.output() |
296 |
try:
|
297 |
out.output("Uploading image to pithos:")
|
298 |
kamaki = Kamaki(wizard['Account'], out)
|
299 |
|
300 |
name = "%s-%s.diskdump" % (wizard['ImageName'], |
301 |
time.strftime("%Y%m%d%H%M"))
|
302 |
pithos_file = ""
|
303 |
with open(image.device, 'rb') as f: |
304 |
pithos_file = kamaki.upload(f, size, name, |
305 |
"(1/4) Calculating block hashes",
|
306 |
"(2/4) Uploading missing blocks")
|
307 |
|
308 |
out.output("(3/4) Uploading metadata file ...", False) |
309 |
kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
|
310 |
remote_path="%s.%s" % (name, 'meta')) |
311 |
out.success('done')
|
312 |
out.output("(4/4) Uploading md5sum file ...", False) |
313 |
md5sumstr = '%s %s\n' % (session['checksum'], name) |
314 |
kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
|
315 |
remote_path="%s.%s" % (name, 'md5sum')) |
316 |
out.success('done')
|
317 |
out.output() |
318 |
|
319 |
is_public = True if wizard['ImageRegistration'] == "Public" else \ |
320 |
False
|
321 |
out.output('Registering %s image with ~okeanos ...' %
|
322 |
wizard['ImageRegistration'].lower(), False) |
323 |
kamaki.register(wizard['ImageName'], pithos_file, metadata,
|
324 |
is_public) |
325 |
out.success('done')
|
326 |
out.output() |
327 |
|
328 |
except ClientError as e: |
329 |
raise FatalError("Pithos client: %d %s" % (e.status, e.message)) |
330 |
finally:
|
331 |
out.remove(with_progress) |
332 |
|
333 |
msg = "The %s image was successfully uploaded and registered with " \
|
334 |
"~okeanos. Would you like to keep a local copy of the image?" \
|
335 |
% wizard['ImageRegistration'].lower()
|
336 |
if not d.yesno(msg, width=PAGE_WIDTH): |
337 |
extract_image(session) |
338 |
|
339 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|