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.
40 from image_creator.kamaki_wrapper import Kamaki, ClientError
41 from image_creator.util import MD5, FatalError
42 from image_creator.output.cli import OutputWthProgress
43 from image_creator.dialog_util import extract_image, update_background_title
48 class WizardExit(Exception):
52 class WizardInvalidData(Exception):
57 def __init__(self, session):
58 self.session = session
60 self.session['wizard'] = {}
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):
87 def run(self, session, index, total):
88 raise NotImplementedError
91 class WizardRadioListPage(WizardPage):
93 def __init__(self, name, message, choices, **kargs):
95 self.message = message
96 self.choices = choices
97 self.title = kargs['title'] if 'title' in kargs else ''
98 self.default = kargs['default'] if 'default' in kargs else 0
100 def run(self, session, index, total):
101 d = session['dialog']
102 w = session['wizard']
105 for i in range(len(self.choices)):
106 default = 1 if self.choices[i][0] == self.default else 0
107 choices.append((self.choices[i][0], self.choices[i][1], default))
111 d.radiolist(self.message, height=10, width=PAGE_WIDTH,
112 ok_label="Next", cancel="Back", choices=choices,
113 title="(%d/%d) %s" % (index + 1, total, self.title)
116 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
119 w[self.name] = answer
120 self.default = answer
125 class WizardInputPage(WizardPage):
127 def __init__(self, name, message, **kargs):
129 self.message = message
130 self.title = kargs['title'] if 'title' in kargs else ''
131 self.init = kargs['init'] if 'init' in kargs else ''
132 if 'validate' in kargs:
133 validate = kargs['validate']
135 validate = lambda x: x
137 setattr(self, "validate", validate)
139 def run(self, session, index, total):
140 d = session['dialog']
141 w = session['wizard']
145 d.inputbox(self.message, init=self.init,
146 width=PAGE_WIDTH, ok_label="Next", cancel="Back",
147 title="(%d/%d) %s" % (index + 1, total, self.title))
149 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
152 value = answer.strip()
154 w[self.name] = self.validate(value)
160 class WizardYesNoPage(WizardPage):
162 def __init__(self, message, **kargs):
163 self.message = message
164 self.title = kargs['title'] if 'title' in kargs else ''
166 def run(self, session, index, total):
167 d = session['dialog']
170 ret = d.yesno(self.message, width=PAGE_WIDTH, ok_label="Yes",
171 cancel="Back", extra_button=1, extra_label="Quit",
172 title="(%d/%d) %s" % (index + 1, total, self.title))
174 if ret == d.DIALOG_CANCEL:
176 elif ret == d.DIALOG_EXTRA:
178 elif ret == d.DIALOG_OK:
184 init_token = Kamaki.get_token()
185 if init_token is None:
188 name = WizardInputPage("ImageName", "Please provide a name for the image:",
189 title="Image Name", init=session['device'].distro)
190 descr = WizardInputPage(
191 "ImageDescription", "Please provide a description for the image:",
192 title="Image Description", init=session['metadata']['DESCRIPTION'] if
193 'DESCRIPTION' in session['metadata'] else '')
194 registration = WizardRadioListPage(
195 "ImageRegistration", "Please provide a registration type:",
196 [("Private", "Image is accessible only by this user"),
197 ("Public", "Everyone can create VMs from this image")],
198 title="Registration Type", default="Private")
200 def validate_account(token):
202 d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
203 raise WizardInvalidData
205 account = Kamaki.get_account(token)
207 session['dialog'].msgbox("The token you provided in not valid!",
209 raise WizardInvalidData
213 account = WizardInputPage(
214 "account", "Please provide your ~okeanos authentication token:",
215 title="~okeanos account", init=init_token, validate=validate_account)
217 msg = "All necessary information has been gathered. Confirm and Proceed."
218 proceed = WizardYesNoPage(msg, title="Confirmation")
224 w.add_page(registration)
229 create_image(session)
236 def create_image(session):
237 d = session['dialog']
238 disk = session['disk']
239 device = session['device']
240 snapshot = session['snapshot']
241 image_os = session['image_os']
242 wizard = session['wizard']
244 # Save Kamaki credentials
245 Kamaki.save_token(wizard['account']['auth_token'])
247 with_progress = OutputWthProgress(True)
249 out.add(with_progress)
255 image_os.do_sysprep()
256 metadata = image_os.meta
260 size = device.shrink()
261 session['shrinked'] = True
262 update_background_title(session)
264 metadata.update(device.meta)
265 metadata['DESCRIPTION'] = wizard['ImageDescription']
269 session['checksum'] = md5.compute(snapshot, size)
272 metastring = '\n'.join(
273 ['%s=%s' % (key, value) for (key, value) in metadata.items()])
278 out.output("Uploading image to pithos:")
279 kamaki = Kamaki(wizard['account'], out)
281 name = "%s-%s.diskdump" % (wizard['ImageName'],
282 time.strftime("%Y%m%d%H%M"))
284 with open(snapshot, 'rb') as f:
285 pithos_file = kamaki.upload(f, size, name,
286 "(1/4) Calculating block hashes",
287 "(2/4) Uploading missing blocks")
289 out.output("(3/4) Uploading metadata file ...", False)
290 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
291 remote_path="%s.%s" % (name, 'meta'))
293 out.output("(4/4) Uploading md5sum file ...", False)
294 md5sumstr = '%s %s\n' % (session['checksum'], name)
295 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
296 remote_path="%s.%s" % (name, 'md5sum'))
300 is_public = True if w['ImageRegistration'] == "Public" else False
301 out.output('Registering %s image with ~okeanos ...' %
302 w['ImageRegistration'].lower(), False)
303 kamaki.register(wizard['ImageName'], pithos_file, metadata,
308 except ClientError as e:
309 raise FatalError("Pithos client: %d %s" % (e.status, e.message))
311 out.remove(with_progress)
313 msg = "The %s image was successfully uploaded and registered with " \
314 "~okeanos. Would you like to keep a local copy of the image?" \
315 % w['ImageRegistration'].lower()
316 if not d.yesno(msg, width=PAGE_WIDTH):
317 extract_image(session)
319 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :