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, \
53 class WizardExit(Exception):
54 """Exception used to exit the wizard"""
58 class WizardInvalidData(Exception):
59 """Exception triggered when the user provided data are invalid"""
64 """Represents a dialog-based wizard
66 The wizard is a collection of pages that have a "Next" and a "Back" button
67 on them. The pages are used to collect user data.
70 def __init__(self, session):
71 self.session = session
73 self.session['wizard'] = {}
74 self.d = session['dialog']
76 def add_page(self, page):
77 """Add a new page to the wizard"""
78 self.pages.append(page)
85 idx += self.pages[idx].run(self.session, idx, len(self.pages))
88 except WizardInvalidData:
91 if idx >= len(self.pages):
92 msg = "All necessary information has been gathered:\n\n"
93 for page in self.pages:
94 msg += " * %s\n" % page.info
95 msg += "\nContinue with the image creation process?"
98 msg, width=PAGE_WIDTH, height=8 + len(self.pages),
99 ok_label="Yes", cancel="Back", extra_button=1,
100 extra_label="Quit", title="Confirmation")
102 if ret == self.d.DIALOG_CANCEL:
104 elif ret == self.d.DIALOG_EXTRA:
106 elif ret == self.d.DIALOG_OK:
113 class WizardPage(object):
114 """Represents a page in a wizard"""
118 def __init__(self, **kargs):
119 validate = kargs['validate'] if 'validate' in kargs else lambda x: x
120 setattr(self, "validate", validate)
122 display = kargs['display'] if 'display' in kargs else lambda x: x
123 setattr(self, "display", display)
125 def run(self, session, index, total):
126 """Display this wizard page
128 This function is used by the wizard program when accessing a page.
130 raise NotImplementedError
133 class WizardRadioListPage(WizardPage):
134 """Represent a Radio List in a wizard"""
135 def __init__(self, name, printable, message, choices, **kargs):
136 super(WizardRadioListPage, self).__init__(**kargs)
138 self.printable = printable
139 self.message = message
140 self.choices = choices
141 self.title = kargs['title'] if 'title' in kargs else ''
142 self.default = kargs['default'] if 'default' in kargs else ""
144 def run(self, session, index, total):
145 d = session['dialog']
146 w = session['wizard']
149 for i in range(len(self.choices)):
150 default = 1 if self.choices[i][0] == self.default else 0
151 choices.append((self.choices[i][0], self.choices[i][1], default))
153 (code, answer) = d.radiolist(
154 self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
155 cancel="Back", choices=choices,
156 title="(%d/%d) %s" % (index + 1, total, self.title))
158 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
161 w[self.name] = self.validate(answer)
162 self.default = answer
163 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
168 class WizardInputPage(WizardPage):
169 """Represents an input field in a wizard"""
170 def __init__(self, name, printable, message, **kargs):
171 super(WizardInputPage, self).__init__(**kargs)
173 self.printable = printable
174 self.message = message
175 self.info = "%s: <none>" % self.printable
176 self.title = kargs['title'] if 'title' in kargs else ''
177 self.init = kargs['init'] if 'init' in kargs else ''
179 def run(self, session, index, total):
180 d = session['dialog']
181 w = session['wizard']
183 (code, answer) = d.inputbox(
184 self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
185 cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
187 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
190 value = answer.strip()
192 w[self.name] = self.validate(value)
193 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
198 def start_wizard(session):
199 """Run the image creation wizard"""
201 d = session['dialog']
202 clouds = Kamaki.get_clouds()
204 if not add_cloud(session):
209 for (name, cloud) in clouds.items():
210 descr = cloud['description'] if 'description' in cloud else ''
211 choices.append((name, descr))
213 (code, choice) = d.menu(
214 "In this menu you can select existing cloud account to use "
215 " or add new ones. Press <Select> to select an existing "
216 "account or <Add> to add a new one.", height=18,
217 width=PAGE_WIDTH, choices=choices, menu_height=10,
218 ok_label="Select", extra_button=1, extra_label="Add",
221 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
223 elif code == d.DIALOG_OK: # Select button
224 account = Kamaki.get_account(choice)
226 if not d.yesno("Then cloud you have selected is not "
227 "valid! Would you like to edit it?",
228 width=PAGE_WIDTH, defaultno=0):
229 edit_cloud(session, choice)
232 elif code == d.DIALOG_EXTRA: # Add button
235 distro = session['image'].distro
236 ostype = session['image'].ostype
237 name = WizardInputPage(
238 "ImageName", "Image Name", "Please provide a name for the image:",
239 title="Image Name", init=ostype if distro == "unknown" else distro)
241 descr = WizardInputPage(
242 "ImageDescription", "Image Description",
243 "Please provide a description for the image:",
244 title="Image Description", init=session['metadata']['DESCRIPTION'] if
245 'DESCRIPTION' in session['metadata'] else '')
247 registration = WizardRadioListPage(
248 "ImageRegistration", "Registration Type",
249 "Please provide a registration type:",
250 [("Private", "Image is accessible only by this user"),
251 ("Public", "Everyone can create VMs from this image")],
252 title="Registration Type", default="Private")
258 w.add_page(registration)
261 create_image(session, account)
268 def create_image(session, account):
269 """Create an image using the information collected by the wizard"""
270 d = session['dialog']
271 image = session['image']
272 wizard = session['wizard']
274 with_progress = OutputWthProgress(True)
276 out.add(with_progress)
281 image.os.do_sysprep()
282 metadata = image.os.meta
285 size = image.shrink()
286 session['shrinked'] = True
287 update_background_title(session)
289 metadata.update(image.meta)
290 metadata['DESCRIPTION'] = wizard['ImageDescription']
294 session['checksum'] = md5.compute(image.device, size)
298 out.output("Uploading image to pithos:")
299 kamaki = Kamaki(account, out)
301 name = "%s-%s.diskdump" % (wizard['ImageName'],
302 time.strftime("%Y%m%d%H%M"))
304 with open(image.device, 'rb') as f:
305 pithos_file = kamaki.upload(f, size, name,
306 "(1/3) Calculating block hashes",
307 "(2/3) Uploading missing blocks")
309 out.output("(3/3) Uploading md5sum file ...", False)
310 md5sumstr = '%s %s\n' % (session['checksum'], name)
311 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
312 remote_path="%s.%s" % (name, 'md5sum'))
316 is_public = True if wizard['ImageRegistration'] == "Public" else \
318 out.output('Registering %s image with cyclades ...' %
319 wizard['ImageRegistration'].lower(), False)
320 result = kamaki.register(wizard['ImageName'], pithos_file,
323 out.output("Uploading metadata file ...", False)
324 metastring = unicode(json.dumps(result, ensure_ascii=False))
325 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
326 remote_path="%s.%s" % (name, 'meta'))
330 out.output("Sharing md5sum file ...", False)
331 kamaki.share("%s.md5sum" % name)
333 out.output("Sharing metadata file ...", False)
334 kamaki.share("%s.meta" % name)
339 except ClientError as e:
340 raise FatalError("Pithos client: %d %s" % (e.status, e.message))
342 out.remove(with_progress)
344 msg = "The %s image was successfully uploaded to Pithos and registered " \
345 "with Cyclades. Would you like to keep a local copy of the image?" \
346 % wizard['ImageRegistration'].lower()
347 if not d.yesno(msg, width=PAGE_WIDTH):
348 extract_image(session)
350 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :