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 += "\nContinue with the image creation process?"
83 msg, width=PAGE_WIDTH, height=8 + len(self.pages),
84 ok_label="Yes", cancel="Back", extra_button=1,
85 extra_label="Quit", title="Confirmation")
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 validate = kargs['validate'] if 'validate' in kargs else lambda x: x
104 setattr(self, "validate", validate)
106 display = kargs['display'] if 'display' in kargs else lambda x: x
107 setattr(self, "display", display)
109 def run(self, session, index, total):
110 raise NotImplementedError
113 class WizardRadioListPage(WizardPage):
115 def __init__(self, name, printable, message, choices, **kargs):
116 super(WizardRadioListPage, self).__init__(**kargs)
118 self.printable = printable
119 self.message = message
120 self.choices = choices
121 self.title = kargs['title'] if 'title' in kargs else ''
122 self.default = kargs['default'] if 'default' in kargs else ""
124 def run(self, session, index, total):
125 d = session['dialog']
126 w = session['wizard']
129 for i in range(len(self.choices)):
130 default = 1 if self.choices[i][0] == self.default else 0
131 choices.append((self.choices[i][0], self.choices[i][1], default))
133 (code, answer) = d.radiolist(
134 self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
135 cancel="Back", choices=choices,
136 title="(%d/%d) %s" % (index + 1, total, self.title))
138 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
141 w[self.name] = self.validate(answer)
142 self.default = answer
143 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
148 class WizardInputPage(WizardPage):
150 def __init__(self, name, printable, message, **kargs):
151 super(WizardInputPage, self).__init__(**kargs)
153 self.printable = printable
154 self.message = message
155 self.title = kargs['title'] if 'title' in kargs else ''
156 self.init = kargs['init'] if 'init' in kargs else ''
158 def run(self, session, index, total):
159 d = session['dialog']
160 w = session['wizard']
162 (code, answer) = d.inputbox(
163 self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
164 cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
166 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
169 value = answer.strip()
171 w[self.name] = self.validate(value)
172 self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
179 init_token = Kamaki.get_token()
180 if init_token is None:
183 name = WizardInputPage(
184 "ImageName", "Image Name", "Please provide a name for the image:",
185 title="Image Name", init=session['device'].distro)
187 descr = WizardInputPage(
188 "ImageDescription", "Image Description",
189 "Please provide a description for the image:",
190 title="Image Description", init=session['metadata']['DESCRIPTION'] if
191 'DESCRIPTION' in session['metadata'] else '')
193 registration = WizardRadioListPage(
194 "ImageRegistration", "Registration Type",
195 "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", "Account",
215 "Please provide your ~okeanos authentication token:",
216 title="~okeanos account", init=init_token, validate=validate_account,
217 display=lambda account: account['username'])
223 w.add_page(registration)
227 create_image(session)
234 def create_image(session):
235 d = session['dialog']
236 disk = session['disk']
237 device = session['device']
238 snapshot = session['snapshot']
239 image_os = session['image_os']
240 wizard = session['wizard']
242 # Save Kamaki credentials
243 Kamaki.save_token(wizard['Account']['auth_token'])
245 with_progress = OutputWthProgress(True)
247 out.add(with_progress)
253 image_os.do_sysprep()
254 metadata = image_os.meta
258 size = device.shrink()
259 session['shrinked'] = True
260 update_background_title(session)
262 metadata.update(device.meta)
263 metadata['DESCRIPTION'] = wizard['ImageDescription']
267 session['checksum'] = md5.compute(snapshot, size)
270 metastring = '\n'.join(
271 ['%s=%s' % (key, value) for (key, value) in metadata.items()])
276 out.output("Uploading image to pithos:")
277 kamaki = Kamaki(wizard['Account'], out)
279 name = "%s-%s.diskdump" % (wizard['ImageName'],
280 time.strftime("%Y%m%d%H%M"))
282 with open(snapshot, 'rb') as f:
283 pithos_file = kamaki.upload(f, size, name,
284 "(1/4) Calculating block hashes",
285 "(2/4) Uploading missing blocks")
287 out.output("(3/4) Uploading metadata file ...", False)
288 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
289 remote_path="%s.%s" % (name, 'meta'))
291 out.output("(4/4) Uploading md5sum file ...", False)
292 md5sumstr = '%s %s\n' % (session['checksum'], name)
293 kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
294 remote_path="%s.%s" % (name, 'md5sum'))
298 is_public = True if wizard['ImageRegistration'] == "Public" else \
300 out.output('Registering %s image with ~okeanos ...' %
301 wizard['ImageRegistration'].lower(), False)
302 kamaki.register(wizard['ImageName'], pithos_file, metadata,
307 except ClientError as e:
308 raise FatalError("Pithos client: %d %s" % (e.status, e.message))
310 out.remove(with_progress)
312 msg = "The %s image was successfully uploaded and registered with " \
313 "~okeanos. Would you like to keep a local copy of the image?" \
314 % wizard['ImageRegistration'].lower()
315 if not d.yesno(msg, width=PAGE_WIDTH):
316 extract_image(session)
318 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :