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'] = {}
61 self.d = session['dialog']
63 def add_page(self, page):
64 self.pages.append(page)
70 idx += self.pages[idx].run(self.session, idx, len(self.pages))
73 except WizardInvalidData:
76 if idx >= len(self.pages):
77 msg = "All necessary information has been gathered:\n\n"
78 for page in self.pages:
79 msg += " * %s\n" % page.info
80 msg += "\nConfirm and Proceed."
83 msg, width=PAGE_WIDTH, height=12, ok_label="Yes",
84 cancel="Back", extra_button=1, extra_label="Quit",
87 if ret == self.d.DIALOG_CANCEL:
89 elif ret == self.d.DIALOG_EXTRA:
91 elif ret == self.d.DIALOG_OK:
98 class WizardPage(object):
102 def __init__(self, **kargs):
103 if 'validate' in kargs:
104 validate = kargs['validate']
106 validate = lambda x: x
107 setattr(self, "validate", validate)
109 if 'display' in kargs:
110 display = kargs['display']
112 display = lambda x: x
113 setattr(self, "display", display)
115 def run(self, session, index, total):
116 raise NotImplementedError
119 class WizardRadioListPage(WizardPage):
121 def __init__(self, name, printable, message, choices, **kargs):
122 super(WizardRadioListPage, self).__init__(**kargs)
124 self.printable = printable
125 self.message = message
126 self.choices = choices
127 self.title = kargs['title'] if 'title' in kargs else ''
128 self.default = kargs['default'] if 'default' in kargs else ""
130 def run(self, session, index, total):
131 d = session['dialog']
132 w = session['wizard']
135 for i in range(len(self.choices)):
136 default = 1 if self.choices[i][0] == self.default else 0
137 choices.append((self.choices[i][0], self.choices[i][1], default))
139 (code, answer) = d.radiolist(
140 self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
141 cancel="Back", choices=choices,
142 title="(%d/%d) %s" % (index + 1, total, self.title))
144 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
147 w[self.name] = self.validate(answer)
148 self.default = answer
149 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
154 class WizardInputPage(WizardPage):
156 def __init__(self, name, printable, message, **kargs):
157 super(WizardInputPage, self).__init__(**kargs)
159 self.printable = printable
160 self.message = message
161 self.title = kargs['title'] if 'title' in kargs else ''
162 self.init = kargs['init'] if 'init' in kargs else ''
164 def run(self, session, index, total):
165 d = session['dialog']
166 w = session['wizard']
168 (code, answer) = d.inputbox(
169 self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
170 cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
172 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
175 value = answer.strip()
177 w[self.name] = self.validate(value)
178 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
185 init_token = Kamaki.get_token()
186 if init_token is None:
189 name = WizardInputPage(
190 "ImageName", "Image Name", "Please provide a name for the image:",
191 title="Image Name", init=session['device'].distro)
193 descr = WizardInputPage(
194 "ImageDescription", "Image Description",
195 "Please provide a description for the image:",
196 title="Image Description", init=session['metadata']['DESCRIPTION'] if
197 'DESCRIPTION' in session['metadata'] else '')
199 registration = WizardRadioListPage(
200 "ImageRegistration", "Registration Type",
201 "Please provide a registration type:",
202 [("Private", "Image is accessible only by this user"),
203 ("Public", "Everyone can create VMs from this image")],
204 title="Registration Type", default="Private")
206 def validate_account(token):
208 d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
209 raise WizardInvalidData
211 account = Kamaki.get_account(token)
213 session['dialog'].msgbox("The token you provided in not valid!",
215 raise WizardInvalidData
219 account = WizardInputPage(
220 "Account", "Account",
221 "Please provide your ~okeanos authentication token:",
222 title="~okeanos account", init=init_token, validate=validate_account,
223 display=lambda account: account['username'])
229 w.add_page(registration)
233 create_image(session)
240 def create_image(session):
241 d = session['dialog']
242 disk = session['disk']
243 device = session['device']
244 snapshot = session['snapshot']
245 image_os = session['image_os']
246 wizard = session['wizard']
248 # Save Kamaki credentials
249 Kamaki.save_token(wizard['Account']['auth_token'])
251 with_progress = OutputWthProgress(True)
253 out.add(with_progress)
259 image_os.do_sysprep()
260 metadata = image_os.meta
264 size = device.shrink()
265 session['shrinked'] = True
266 update_background_title(session)
268 metadata.update(device.meta)
269 metadata['DESCRIPTION'] = wizard['ImageDescription']
273 session['checksum'] = md5.compute(snapshot, size)
276 metastring = '\n'.join(
277 ['%s=%s' % (key, value) for (key, value) in metadata.items()])
282 out.output("Uploading image to pithos:")
283 kamaki = Kamaki(wizard['Account'], out)
285 name = "%s-%s.diskdump" % (wizard['ImageName'],
286 time.strftime("%Y%m%d%H%M"))
288 with open(snapshot, 'rb') as f:
289 pithos_file = kamaki.upload(f, size, name,
290 "(1/4) Calculating block hashes",
291 "(2/4) Uploading missing blocks")
293 out.output("(3/4) Uploading metadata file ...", False)
294 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
295 remote_path="%s.%s" % (name, 'meta'))
297 out.output("(4/4) Uploading md5sum file ...", False)
298 md5sumstr = '%s %s\n' % (session['checksum'], name)
299 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
300 remote_path="%s.%s" % (name, 'md5sum'))
304 is_public = True if w['ImageRegistration'] == "Public" else False
305 out.output('Registering %s image with ~okeanos ...' %
306 w['ImageRegistration'].lower(), False)
307 kamaki.register(wizard['ImageName'], pithos_file, metadata,
312 except ClientError as e:
313 raise FatalError("Pithos client: %d %s" % (e.status, e.message))
315 out.remove(with_progress)
317 msg = "The %s image was successfully uploaded and registered with " \
318 "~okeanos. Would you like to keep a local copy of the image?" \
319 % w['ImageRegistration'].lower()
320 if not d.yesno(msg, width=PAGE_WIDTH):
321 extract_image(session)
323 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :