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.
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
47 class WizardExit(Exception):
48 """Exception used to exit the wizard"""
52 class WizardInvalidData(Exception):
53 """Exception triggered when the user provided data are invalid"""
58 """Represents a dialog-based wizard
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.
64 def __init__(self, session):
65 self.session = session
67 self.session['wizard'] = {}
68 self.d = session['dialog']
70 def add_page(self, page):
71 """Add a new page to the wizard"""
72 self.pages.append(page)
79 idx += self.pages[idx].run(self.session, idx, len(self.pages))
82 except WizardInvalidData:
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?"
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")
96 if ret == self.d.DIALOG_CANCEL:
98 elif ret == self.d.DIALOG_EXTRA:
100 elif ret == self.d.DIALOG_OK:
107 class WizardPage(object):
108 """Represents a page in a wizard"""
112 def __init__(self, **kargs):
113 validate = kargs['validate'] if 'validate' in kargs else lambda x: x
114 setattr(self, "validate", validate)
116 display = kargs['display'] if 'display' in kargs else lambda x: x
117 setattr(self, "display", display)
119 def run(self, session, index, total):
120 """Display this wizard page
122 This function is used by the wizard program when accessing a page.
124 raise NotImplementedError
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)
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 ""
138 def run(self, session, index, total):
139 d = session['dialog']
140 w = session['wizard']
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))
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))
152 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
155 w[self.name] = self.validate(answer)
156 self.default = answer
157 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
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)
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 ''
173 def run(self, session, index, total):
174 d = session['dialog']
175 w = session['wizard']
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))
181 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
184 value = answer.strip()
186 w[self.name] = self.validate(value)
187 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
192 def start_wizard(session):
193 """Run the image creation wizard"""
194 init_token = Kamaki.get_token()
195 if init_token is None:
198 name = WizardInputPage(
199 "ImageName", "Image Name", "Please provide a name for the image:",
200 title="Image Name", init=session['image'].distro)
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 '')
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")
215 def validate_account(token):
216 """Check if a token is valid"""
217 d = session['dialog']
220 d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
221 raise WizardInvalidData
223 account = Kamaki.get_account(token)
225 d.msgbox("The token you provided in not valid!", width=PAGE_WIDTH)
226 raise WizardInvalidData
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'])
240 w.add_page(registration)
244 create_image(session)
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']
257 # Save Kamaki credentials
258 Kamaki.save_token(wizard['Account']['auth_token'])
260 with_progress = OutputWthProgress(True)
262 out.add(with_progress)
268 image.os.do_sysprep()
269 metadata = image.os.meta
273 size = image.shrink()
274 session['shrinked'] = True
275 update_background_title(session)
277 metadata.update(image.meta)
278 metadata['DESCRIPTION'] = wizard['ImageDescription']
282 session['checksum'] = md5.compute(image.device, size)
285 metastring = '\n'.join(
286 ['%s=%s' % (key, value) for (key, value) in metadata.items()])
291 out.output("Uploading image to pithos:")
292 kamaki = Kamaki(wizard['Account'], out)
294 name = "%s-%s.diskdump" % (wizard['ImageName'],
295 time.strftime("%Y%m%d%H%M"))
297 with open(image.device, 'rb') as f:
298 pithos_file = kamaki.upload(f, size, name,
299 "(1/4) Calculating block hashes",
300 "(2/4) Uploading missing blocks")
302 out.output("(3/4) Uploading metadata file ...", False)
303 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
304 remote_path="%s.%s" % (name, 'meta'))
306 out.output("(4/4) Uploading md5sum file ...", False)
307 md5sumstr = '%s %s\n' % (session['checksum'], name)
308 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
309 remote_path="%s.%s" % (name, 'md5sum'))
313 is_public = True if wizard['ImageRegistration'] == "Public" else \
315 out.output('Registering %s image with ~okeanos ...' %
316 wizard['ImageRegistration'].lower(), False)
317 kamaki.register(wizard['ImageName'], pithos_file, metadata,
322 except ClientError as e:
323 raise FatalError("Pithos client: %d %s" % (e.status, e.message))
325 out.remove(with_progress)
327 msg = "The %s image was successfully uploaded and registered with " \
328 "~okeanos. Would you like to keep a local copy of the image?" \
329 % wizard['ImageRegistration'].lower()
330 if not d.yesno(msg, width=PAGE_WIDTH):
331 extract_image(session)
333 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :