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
44 from image_creator.kamaki_wrapper import Kamaki, ClientError
45 from image_creator.util import MD5, FatalError
46 from image_creator.output.cli import OutputWthProgress
47 from image_creator.dialog_util import extract_image, update_background_title, \
54 class WizardExit(Exception):
55 """Exception used to exit the wizard"""
59 class WizardReloadPage(Exception):
60 """Exception that reloads the last WizardPage"""
65 """Represents a dialog-based wizard
67 The wizard is a collection of pages that have a "Next" and a "Back" button
68 on them. The pages are used to collect user data.
71 def __init__(self, session):
72 self.session = session
74 self.session['wizard'] = {}
75 self.d = session['dialog']
77 def add_page(self, page):
78 """Add a new page to the wizard"""
79 self.pages.append(page)
86 total = len(self.pages)
87 title = "(%d/%d) %s" % (idx + 1, total, self.pages[idx].title)
88 idx += self.pages[idx].run(self.session, title)
91 except WizardReloadPage:
94 if idx >= len(self.pages):
95 text = "All necessary information has been gathered:\n\n"
96 for page in self.pages:
97 text += " * %s\n" % page.info
98 text += "\nContinue with the image creation process?"
101 text, width=PAGE_WIDTH, height=8 + len(self.pages),
102 ok_label="Yes", cancel="Back", extra_button=1,
103 extra_label="Quit", title="Confirmation")
105 if ret == self.d.DIALOG_CANCEL:
107 elif ret == self.d.DIALOG_EXTRA:
109 elif ret == self.d.DIALOG_OK:
116 class WizardPage(object):
117 """Represents a page in a wizard"""
121 def __init__(self, name, display_name, text, **kargs):
123 self.display_name = display_name
126 self.title = kargs['title'] if 'title' in kargs else ""
127 self.default = kargs['default'] if 'default' in kargs else ""
128 self.extra = kargs['extra'] if 'extra' in kargs else None
130 kargs['extra_label'] if 'extra_label' in kargs else 'Extra'
132 self.info = "%s: <none>" % self.display_name
134 validate = kargs['validate'] if 'validate' in kargs else lambda x: x
135 setattr(self, "validate", validate)
137 display = kargs['display'] if 'display' in kargs else lambda x: x
138 setattr(self, "display", display)
140 def run(self, session, title):
141 """Display this wizard page
143 This function is used by the wizard program when accessing a page.
145 raise NotImplementedError
148 class WizardPageWthChoices(WizardPage):
149 """Represents a Wizard Page that allows the user to select something from
152 The available choices are created by a function passed to the class through
153 the choices variable. If the choices function returns an empty list, a
154 fallback funtion is executed if available.
156 def __init__(self, name, display_name, text, choices, **kargs):
157 super(WizardPageWthChoices, self).__init__(name, display_name, text,
159 self.choices = choices
160 self.fallback = kargs['fallback'] if 'fallback' in kargs else None
163 class WizardRadioListPage(WizardPageWthChoices):
164 """Represent a Radio List in a wizard"""
166 def run(self, session, title):
167 d = session['dialog']
168 w = session['wizard']
171 for choice in self.choices():
172 default = 1 if choice[0] == self.default else 0
173 choices.append((choice[0], choice[1], default))
175 (code, answer) = d.radiolist(
176 self.text, width=PAGE_WIDTH, ok_label="Next", cancel="Back",
177 choices=choices, height=PAGE_HEIGHT, title=title)
179 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
182 w[self.name] = self.validate(answer)
183 self.default = answer
184 self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
189 class WizardInputPage(WizardPage):
190 """Represents an input field in a wizard"""
192 def run(self, session, title):
193 d = session['dialog']
194 w = session['wizard']
196 (code, answer) = d.inputbox(
197 self.text, init=self.default, width=PAGE_WIDTH, ok_label="Next",
198 cancel="Back", height=PAGE_HEIGHT, title=title)
200 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
203 value = answer.strip()
205 w[self.name] = self.validate(value)
206 self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
211 class WizardMenuPage(WizardPageWthChoices):
212 """Represents a menu dialog with available choices in a wizard"""
214 def run(self, session, title):
215 d = session['dialog']
216 w = session['wizard']
218 extra_button = 1 if self.extra else 0
220 choices = self.choices()
222 if len(choices) == 0:
223 assert self.fallback, "Zero choices and no fallback"
225 raise WizardReloadPage
229 default_item = self.default if self.default else choices[0][0]
231 (code, choice) = d.menu(
232 self.text, width=PAGE_WIDTH, ok_label="Next", cancel="Back",
233 title=title, choices=choices, height=PAGE_HEIGHT,
234 default_item=default_item, extra_label=self.extra_label,
235 extra_button=extra_button)
237 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
239 elif code == d.DIALOG_EXTRA:
241 raise WizardReloadPage
243 self.default = choice
244 w[self.name] = self.validate(choice)
245 self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
250 def start_wizard(session):
251 """Run the image creation wizard"""
253 distro = session['image'].distro
254 ostype = session['image'].ostype
258 for (name, cloud) in Kamaki.get_clouds().items():
259 descr = cloud['description'] if 'description' in cloud else ''
260 choices.append((name, descr))
265 return add_cloud(session)
267 def cloud_none_available():
268 if not session['dialog'].yesno(
269 "No available clouds found. Would you like to add one now?",
270 width=PAGE_WIDTH, defaultno=0):
271 return add_cloud(session)
274 def cloud_validate(cloud):
275 if not Kamaki.get_account(cloud):
276 if not session['dialog'].yesno(
277 "The cloud you have selected is not valid! Would you "
278 "like to edit it now?", width=PAGE_WIDTH, defaultno=0):
279 if edit_cloud(session, cloud):
282 raise WizardInvalidData
286 cloud = WizardMenuPage(
288 "Please select a cloud account or press <Add> to add a new one:",
289 choices=cloud_choices, extra_label="Add", extra=cloud_add,
290 title="Clouds", validate=cloud_validate, fallback=cloud_none_available)
292 name = WizardInputPage(
293 "ImageName", "Image Name", "Please provide a name for the image:",
294 title="Image Name", default=ostype if distro == "unknown" else distro)
296 descr = WizardInputPage(
297 "ImageDescription", "Image Description",
298 "Please provide a description for the image:",
299 title="Image Description", default=session['metadata']['DESCRIPTION']
300 if 'DESCRIPTION' in session['metadata'] else '')
302 def registration_choices():
303 return [("Private", "Image is accessible only by this user"),
304 ("Public", "Everyone can create VMs from this image")]
306 registration = WizardRadioListPage(
307 "ImageRegistration", "Registration Type",
308 "Please provide a registration type:", registration_choices,
309 title="Registration Type", default="Private")
316 w.add_page(registration)
319 create_image(session)
326 def create_image(session):
327 """Create an image using the information collected by the wizard"""
328 d = session['dialog']
329 image = session['image']
330 wizard = session['wizard']
332 with_progress = OutputWthProgress(True)
334 out.add(with_progress)
339 image.os.do_sysprep()
340 metadata = image.os.meta
343 size = image.shrink()
344 session['shrinked'] = True
345 update_background_title(session)
347 metadata.update(image.meta)
348 metadata['DESCRIPTION'] = wizard['ImageDescription']
352 session['checksum'] = md5.compute(image.device, size)
356 out.output("Uploading image to the cloud:")
357 account = Kamaki.get_account(wizard['Cloud'])
358 assert account, "Cloud: %s is not valid" % wizard['Cloud']
359 kamaki = Kamaki(account, out)
361 name = "%s-%s.diskdump" % (wizard['ImageName'],
362 time.strftime("%Y%m%d%H%M"))
364 with open(image.device, 'rb') as f:
365 pithos_file = kamaki.upload(f, size, name,
366 "(1/3) Calculating block hashes",
367 "(2/3) Uploading missing blocks")
369 out.output("(3/3) Uploading md5sum file ...", False)
370 md5sumstr = '%s %s\n' % (session['checksum'], name)
371 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
372 remote_path="%s.%s" % (name, 'md5sum'))
376 is_public = True if wizard['ImageRegistration'] == "Public" else \
378 out.output('Registering %s image with the cloud ...' %
379 wizard['ImageRegistration'].lower(), False)
380 result = kamaki.register(wizard['ImageName'], pithos_file,
383 out.output("Uploading metadata file ...", False)
384 metastring = unicode(json.dumps(result, ensure_ascii=False))
385 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
386 remote_path="%s.%s" % (name, 'meta'))
390 out.output("Sharing md5sum file ...", False)
391 kamaki.share("%s.md5sum" % name)
393 out.output("Sharing metadata file ...", False)
394 kamaki.share("%s.meta" % name)
399 except ClientError as e:
400 raise FatalError("Storage service client: %d %s" %
401 (e.status, e.message))
403 out.remove(with_progress)
405 text = "The %s image was successfully uploaded to the storage service " \
406 "and registered with the compute service of %s. Would you like " \
407 "to keep a local copy?" % \
408 (wizard['Cloud'], wizard['ImageRegistration'].lower())
410 if not d.yesno(text, width=PAGE_WIDTH):
411 extract_image(session)
413 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :