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):
51 class WizardInvalidData(Exception):
56 def __init__(self, session):
57 self.session = session
59 self.session['wizard'] = {}
60 self.d = session['dialog']
62 def add_page(self, page):
63 self.pages.append(page)
69 idx += self.pages[idx].run(self.session, idx, len(self.pages))
72 except WizardInvalidData:
75 if idx >= len(self.pages):
76 msg = "All necessary information has been gathered:\n\n"
77 for page in self.pages:
78 msg += " * %s\n" % page.info
79 msg += "\nContinue with the image creation process?"
82 msg, width=PAGE_WIDTH, height=8 + len(self.pages),
83 ok_label="Yes", cancel="Back", extra_button=1,
84 extra_label="Quit", title="Confirmation")
86 if ret == self.d.DIALOG_CANCEL:
88 elif ret == self.d.DIALOG_EXTRA:
90 elif ret == self.d.DIALOG_OK:
97 class WizardPage(object):
101 def __init__(self, **kargs):
102 validate = kargs['validate'] if 'validate' in kargs else lambda x: x
103 setattr(self, "validate", validate)
105 display = kargs['display'] if 'display' in kargs else lambda x: x
106 setattr(self, "display", display)
108 def run(self, session, index, total):
109 raise NotImplementedError
112 class WizardRadioListPage(WizardPage):
114 def __init__(self, name, printable, message, choices, **kargs):
115 super(WizardRadioListPage, self).__init__(**kargs)
117 self.printable = printable
118 self.message = message
119 self.choices = choices
120 self.title = kargs['title'] if 'title' in kargs else ''
121 self.default = kargs['default'] if 'default' in kargs else ""
123 def run(self, session, index, total):
124 d = session['dialog']
125 w = session['wizard']
128 for i in range(len(self.choices)):
129 default = 1 if self.choices[i][0] == self.default else 0
130 choices.append((self.choices[i][0], self.choices[i][1], default))
132 (code, answer) = d.radiolist(
133 self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
134 cancel="Back", choices=choices,
135 title="(%d/%d) %s" % (index + 1, total, self.title))
137 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
140 w[self.name] = self.validate(answer)
141 self.default = answer
142 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
147 class WizardInputPage(WizardPage):
149 def __init__(self, name, printable, message, **kargs):
150 super(WizardInputPage, self).__init__(**kargs)
152 self.printable = printable
153 self.message = message
154 self.title = kargs['title'] if 'title' in kargs else ''
155 self.init = kargs['init'] if 'init' in kargs else ''
157 def run(self, session, index, total):
158 d = session['dialog']
159 w = session['wizard']
161 (code, answer) = d.inputbox(
162 self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
163 cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
165 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
168 value = answer.strip()
170 w[self.name] = self.validate(value)
171 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
177 init_token = Kamaki.get_token()
178 if init_token is None:
181 name = WizardInputPage(
182 "ImageName", "Image Name", "Please provide a name for the image:",
183 title="Image Name", init=session['image'].distro)
185 descr = WizardInputPage(
186 "ImageDescription", "Image Description",
187 "Please provide a description for the image:",
188 title="Image Description", init=session['metadata']['DESCRIPTION'] if
189 'DESCRIPTION' in session['metadata'] else '')
191 registration = WizardRadioListPage(
192 "ImageRegistration", "Registration Type",
193 "Please provide a registration type:",
194 [("Private", "Image is accessible only by this user"),
195 ("Public", "Everyone can create VMs from this image")],
196 title="Registration Type", default="Private")
198 def validate_account(token):
199 d = session['dialog']
202 d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
203 raise WizardInvalidData
205 account = Kamaki.get_account(token)
207 d.msgbox("The token you provided in not valid!", width=PAGE_WIDTH)
208 raise WizardInvalidData
212 account = WizardInputPage(
213 "Account", "Account",
214 "Please provide your ~okeanos authentication token:",
215 title="~okeanos account", init=init_token, validate=validate_account,
216 display=lambda account: account['username'])
222 w.add_page(registration)
226 create_image(session)
233 def create_image(session):
234 d = session['dialog']
235 image = session['image']
236 wizard = session['wizard']
238 # Save Kamaki credentials
239 Kamaki.save_token(wizard['Account']['auth_token'])
241 with_progress = OutputWthProgress(True)
243 out.add(with_progress)
249 image.os.do_sysprep()
250 metadata = image.os.meta
254 size = image.shrink()
255 session['shrinked'] = True
256 update_background_title(session)
258 metadata.update(image.meta)
259 metadata['DESCRIPTION'] = wizard['ImageDescription']
263 session['checksum'] = md5.compute(image.device, size)
266 metastring = '\n'.join(
267 ['%s=%s' % (key, value) for (key, value) in metadata.items()])
272 out.output("Uploading image to pithos:")
273 kamaki = Kamaki(wizard['Account'], out)
275 name = "%s-%s.diskdump" % (wizard['ImageName'],
276 time.strftime("%Y%m%d%H%M"))
278 with open(image.device, 'rb') as f:
279 pithos_file = kamaki.upload(f, size, name,
280 "(1/4) Calculating block hashes",
281 "(2/4) Uploading missing blocks")
283 out.output("(3/4) Uploading metadata file ...", False)
284 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
285 remote_path="%s.%s" % (name, 'meta'))
287 out.output("(4/4) Uploading md5sum file ...", False)
288 md5sumstr = '%s %s\n' % (session['checksum'], name)
289 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
290 remote_path="%s.%s" % (name, 'md5sum'))
294 is_public = True if wizard['ImageRegistration'] == "Public" else \
296 out.output('Registering %s image with ~okeanos ...' %
297 wizard['ImageRegistration'].lower(), False)
298 kamaki.register(wizard['ImageName'], pithos_file, metadata,
303 except ClientError as e:
304 raise FatalError("Pithos client: %d %s" % (e.status, e.message))
306 out.remove(with_progress)
308 msg = "The %s image was successfully uploaded and registered with " \
309 "~okeanos. Would you like to keep a local copy of the image?" \
310 % wizard['ImageRegistration'].lower()
311 if not d.yesno(msg, width=PAGE_WIDTH):
312 extract_image(session)
314 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :