1 # -*- coding: utf-8 -*-
3 # Copyright 2012 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
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.
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.
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.
36 """This module implements the "wizard" mode of the dialog-based version of
43 from image_creator.kamaki_wrapper import Kamaki, ClientError
44 from image_creator.util import MD5, FatalError
45 from image_creator.output.cli import OutputWthProgress
46 from image_creator.dialog_util import extract_image, update_background_title
51 class WizardExit(Exception):
52 """Exception used to exit the wizard"""
56 class WizardInvalidData(Exception):
57 """Exception triggered when the user provided data are invalid"""
62 """Represents a dialog-based wizard
64 The wizard is a collection of pages that have a "Next" and a "Back" button
65 on them. The pages are used to collect user data.
68 def __init__(self, session):
69 self.session = session
71 self.session['wizard'] = {}
72 self.d = session['dialog']
74 def add_page(self, page):
75 """Add a new page to the wizard"""
76 self.pages.append(page)
83 idx += self.pages[idx].run(self.session, idx, len(self.pages))
86 except WizardInvalidData:
89 if idx >= len(self.pages):
90 msg = "All necessary information has been gathered:\n\n"
91 for page in self.pages:
92 msg += " * %s\n" % page.info
93 msg += "\nContinue with the image creation process?"
96 msg, width=PAGE_WIDTH, height=8 + len(self.pages),
97 ok_label="Yes", cancel="Back", extra_button=1,
98 extra_label="Quit", title="Confirmation")
100 if ret == self.d.DIALOG_CANCEL:
102 elif ret == self.d.DIALOG_EXTRA:
104 elif ret == self.d.DIALOG_OK:
111 class WizardPage(object):
112 """Represents a page in a wizard"""
116 def __init__(self, **kargs):
117 validate = kargs['validate'] if 'validate' in kargs else lambda x: x
118 setattr(self, "validate", validate)
120 display = kargs['display'] if 'display' in kargs else lambda x: x
121 setattr(self, "display", display)
123 def run(self, session, index, total):
124 """Display this wizard page
126 This function is used by the wizard program when accessing a page.
128 raise NotImplementedError
131 class WizardRadioListPage(WizardPage):
132 """Represent a Radio List in a wizard"""
133 def __init__(self, name, printable, message, choices, **kargs):
134 super(WizardRadioListPage, self).__init__(**kargs)
136 self.printable = printable
137 self.message = message
138 self.choices = choices
139 self.title = kargs['title'] if 'title' in kargs else ''
140 self.default = kargs['default'] if 'default' in kargs else ""
142 def run(self, session, index, total):
143 d = session['dialog']
144 w = session['wizard']
147 for i in range(len(self.choices)):
148 default = 1 if self.choices[i][0] == self.default else 0
149 choices.append((self.choices[i][0], self.choices[i][1], default))
151 (code, answer) = d.radiolist(
152 self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
153 cancel="Back", choices=choices,
154 title="(%d/%d) %s" % (index + 1, total, self.title))
156 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
159 w[self.name] = self.validate(answer)
160 self.default = answer
161 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
166 class WizardInputPage(WizardPage):
167 """Represents an input field in a wizard"""
168 def __init__(self, name, printable, message, **kargs):
169 super(WizardInputPage, self).__init__(**kargs)
171 self.printable = printable
172 self.message = message
173 self.info = "%s: <none>" % self.printable
174 self.title = kargs['title'] if 'title' in kargs else ''
175 self.init = kargs['init'] if 'init' in kargs else ''
177 def run(self, session, index, total):
178 d = session['dialog']
179 w = session['wizard']
181 (code, answer) = d.inputbox(
182 self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
183 cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
185 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
188 value = answer.strip()
190 w[self.name] = self.validate(value)
191 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
196 def start_wizard(session):
197 """Run the image creation wizard"""
198 init_token = Kamaki.get_token()
199 if init_token is None:
202 distro = session['image'].distro
203 ostype = session['image'].ostype
204 name = WizardInputPage(
205 "ImageName", "Image Name", "Please provide a name for the image:",
206 title="Image Name", init=ostype if distro == "unknown" else distro)
208 descr = WizardInputPage(
209 "ImageDescription", "Image Description",
210 "Please provide a description for the image:",
211 title="Image Description", init=session['metadata']['DESCRIPTION'] if
212 'DESCRIPTION' in session['metadata'] else '')
214 registration = WizardRadioListPage(
215 "ImageRegistration", "Registration Type",
216 "Please provide a registration type:",
217 [("Private", "Image is accessible only by this user"),
218 ("Public", "Everyone can create VMs from this image")],
219 title="Registration Type", default="Private")
221 def validate_account(token):
222 """Check if a token is valid"""
223 d = session['dialog']
226 d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
227 raise WizardInvalidData
229 account = Kamaki.get_account(token)
231 d.msgbox("The token you provided in not valid!", width=PAGE_WIDTH)
232 raise WizardInvalidData
236 account = WizardInputPage(
237 "Account", "Account",
238 "Please provide your ~okeanos authentication token:",
239 title="~okeanos account", init=init_token, validate=validate_account,
240 display=lambda account: account['username'])
246 w.add_page(registration)
250 create_image(session)
257 def create_image(session):
258 """Create an image using the information collected by the wizard"""
259 d = session['dialog']
260 image = session['image']
261 wizard = session['wizard']
263 # Save Kamaki credentials
264 Kamaki.save_token(wizard['Account']['auth_token'])
266 with_progress = OutputWthProgress(True)
268 out.add(with_progress)
273 image.os.do_sysprep()
274 metadata = image.os.meta
277 size = image.shrink()
278 session['shrinked'] = True
279 update_background_title(session)
281 metadata.update(image.meta)
282 metadata['DESCRIPTION'] = wizard['ImageDescription']
286 session['checksum'] = md5.compute(image.device, size)
289 metastring = '\n'.join(
290 ['%s=%s' % (key, value) for (key, value) in metadata.items()])
295 out.output("Uploading image to pithos:")
296 kamaki = Kamaki(wizard['Account'], out)
298 name = "%s-%s.diskdump" % (wizard['ImageName'],
299 time.strftime("%Y%m%d%H%M"))
301 with open(image.device, 'rb') as f:
302 pithos_file = kamaki.upload(f, size, name,
303 "(1/4) Calculating block hashes",
304 "(2/4) Uploading missing blocks")
306 out.output("(3/4) Uploading metadata file ...", False)
307 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
308 remote_path="%s.%s" % (name, 'meta'))
310 out.output("(4/4) Uploading md5sum file ...", False)
311 md5sumstr = '%s %s\n' % (session['checksum'], name)
312 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
313 remote_path="%s.%s" % (name, 'md5sum'))
317 is_public = True if wizard['ImageRegistration'] == "Public" else \
319 out.output('Registering %s image with ~okeanos ...' %
320 wizard['ImageRegistration'].lower(), False)
321 kamaki.register(wizard['ImageName'], pithos_file, metadata,
325 out.output("Sharing md5sum file ...", False)
326 kamaki.share("%s.md5sum" % name)
328 out.output("Sharing metadata file ...", False)
329 kamaki.share("%s.meta" % name)
334 except ClientError as e:
335 raise FatalError("Pithos client: %d %s" % (e.status, e.message))
337 out.remove(with_progress)
339 msg = "The %s image was successfully uploaded and registered with " \
340 "~okeanos. Would you like to keep a local copy of the image?" \
341 % wizard['ImageRegistration'].lower()
342 if not d.yesno(msg, width=PAGE_WIDTH):
343 extract_image(session)
345 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :