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 WizardFormPage(WizardPage):
212 """Represents a Form in a wizard"""
214 def __init__(self, name, display_name, text, fields, **kargs):
215 super(WizardFormPage, self).__init__(name, display_name, text, **kargs)
218 def run(self, session, title):
219 d = session['dialog']
220 w = session['wizard']
222 field_lenght = len(self.fields())
223 form_height = field_lenght if field_lenght < PAGE_HEIGHT - 4 \
224 else PAGET_HEIGHT - 4
226 (code, output) = d.form(
227 self.text, width=PAGE_WIDTH, height=PAGE_HEIGHT,
228 form_height=form_height, ok_label="Next", cancel="Back",
229 fields=self.fields(), title=title)
231 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
234 w[self.name] = self.validate(output)
235 self.default = output
236 self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
241 class WizardMenuPage(WizardPageWthChoices):
242 """Represents a menu dialog with available choices in a wizard"""
244 def run(self, session, title):
245 d = session['dialog']
246 w = session['wizard']
248 extra_button = 1 if self.extra else 0
250 choices = self.choices()
252 if len(choices) == 0:
253 assert self.fallback, "Zero choices and no fallback"
255 raise WizardReloadPage
259 default_item = self.default if self.default else choices[0][0]
261 (code, choice) = d.menu(
262 self.text, width=PAGE_WIDTH, ok_label="Next", cancel="Back",
263 title=title, choices=choices, height=PAGE_HEIGHT,
264 default_item=default_item, extra_label=self.extra_label,
265 extra_button=extra_button)
267 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
269 elif code == d.DIALOG_EXTRA:
271 raise WizardReloadPage
273 self.default = choice
274 w[self.name] = self.validate(choice)
275 self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
280 def start_wizard(session):
281 """Run the image creation wizard"""
283 image = session['image']
284 distro = image.distro
285 ostype = image.ostype
287 # Create Cloud Wizard Page
290 for (name, cloud) in Kamaki.get_clouds().items():
291 descr = cloud['description'] if 'description' in cloud else ''
292 choices.append((name, descr))
297 return add_cloud(session)
299 def cloud_none_available():
300 if not session['dialog'].yesno(
301 "No available clouds found. Would you like to add one now?",
302 width=PAGE_WIDTH, defaultno=0):
303 return add_cloud(session)
306 def cloud_validate(cloud):
307 if not Kamaki.get_account(cloud):
308 if not session['dialog'].yesno(
309 "The cloud you have selected is not valid! Would you "
310 "like to edit it now?", width=PAGE_WIDTH, defaultno=0):
311 if edit_cloud(session, cloud):
314 raise WizardReloadPage
318 cloud = WizardMenuPage(
320 "Please select a cloud account or press <Add> to add a new one:",
321 choices=cloud_choices, extra_label="Add", extra=cloud_add,
322 title="Clouds", validate=cloud_validate, fallback=cloud_none_available)
324 # Create Image Name Wizard Page
325 name = WizardInputPage(
326 "ImageName", "Image Name", "Please provide a name for the image:",
327 title="Image Name", default=ostype if distro == "unknown" else distro)
329 # Create Image Description Wizard Page
330 descr = WizardInputPage(
331 "ImageDescription", "Image Description",
332 "Please provide a description for the image:",
333 title="Image Description", default=session['metadata']['DESCRIPTION']
334 if 'DESCRIPTION' in session['metadata'] else '')
336 # Create Sysprep Params Wizard Page
337 needed = image.os.needed_sysprep_params()
339 def sysprep_params_fields():
341 available = image.os.sysprep_params
343 text = param.description
344 default = available[param.name] if param.name in available else ""
345 fields.append(("%s: " % text, default, param.length))
348 def sysprep_params_validate(answer):
350 for i in range(len(answer)):
351 if needed[i].validator(answer):
352 params[needed[i].name] = answer[i]
354 session['dialog'].msgbox("Invalid value for parameter `%s'" %
356 raise WizardReloadPage
359 def sysprep_params_display(params):
360 return ",".join(["%s=%s" % (key, val) for key, val in params.items()])
362 sysprep_params = WizardFormPage(
363 "SysprepParams", "Sysprep Parameters",
364 "Prease fill in the following system preparation parameters:",
365 title="System Preparation Parameters", fields=sysprep_params_fields,
366 display=sysprep_params_display, validate=sysprep_params_validate
367 ) if len(needed) != 0 else None
369 # Create Image Registration Wizard Page
370 def registration_choices():
371 return [("Private", "Image is accessible only by this user"),
372 ("Public", "Everyone can create VMs from this image")]
374 registration = WizardRadioListPage(
375 "ImageRegistration", "Registration Type",
376 "Please provide a registration type:", registration_choices,
377 title="Registration Type", default="Private")
384 if sysprep_params is not None:
385 w.add_page(sysprep_params)
386 w.add_page(registration)
389 create_image(session)
396 def create_image(session):
397 """Create an image using the information collected by the wizard"""
398 d = session['dialog']
399 image = session['image']
400 wizard = session['wizard']
402 with_progress = OutputWthProgress(True)
404 out.add(with_progress)
409 image.os.sysprep_params.update(wizard['SysprepParams'])
410 image.os.do_sysprep()
411 metadata = image.os.meta
414 size = image.shrink()
415 session['shrinked'] = True
416 update_background_title(session)
418 metadata.update(image.meta)
419 metadata['DESCRIPTION'] = wizard['ImageDescription']
423 session['checksum'] = md5.compute(image.device, size)
427 out.output("Uploading image to the cloud:")
428 account = Kamaki.get_account(wizard['Cloud'])
429 assert account, "Cloud: %s is not valid" % wizard['Cloud']
430 kamaki = Kamaki(account, out)
432 name = "%s-%s.diskdump" % (wizard['ImageName'],
433 time.strftime("%Y%m%d%H%M"))
435 with open(image.device, 'rb') as f:
436 pithos_file = kamaki.upload(f, size, name,
437 "(1/3) Calculating block hashes",
438 "(2/3) Uploading missing blocks")
440 out.output("(3/3) Uploading md5sum file ...", False)
441 md5sumstr = '%s %s\n' % (session['checksum'], name)
442 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
443 remote_path="%s.%s" % (name, 'md5sum'))
447 is_public = True if wizard['ImageRegistration'] == "Public" else \
449 out.output('Registering %s image with the cloud ...' %
450 wizard['ImageRegistration'].lower(), False)
451 result = kamaki.register(wizard['ImageName'], pithos_file,
454 out.output("Uploading metadata file ...", False)
455 metastring = unicode(json.dumps(result, ensure_ascii=False))
456 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
457 remote_path="%s.%s" % (name, 'meta'))
461 out.output("Sharing md5sum file ...", False)
462 kamaki.share("%s.md5sum" % name)
464 out.output("Sharing metadata file ...", False)
465 kamaki.share("%s.meta" % name)
470 except ClientError as e:
471 raise FatalError("Storage service client: %d %s" %
472 (e.status, e.message))
474 out.remove(with_progress)
476 text = "The %s image was successfully uploaded to the storage service " \
477 "and registered with the compute service of %s. Would you like " \
478 "to keep a local copy?" % \
479 (wizard['Cloud'], wizard['ImageRegistration'].lower())
481 if not d.yesno(text, width=PAGE_WIDTH):
482 extract_image(session)
484 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :