Monkey-patch pythondialog to support form boxes
[snf-image-creator] / image_creator / dialog_wizard.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
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.
17 #
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.
30 #
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.
35
36 """This module implements the "wizard" mode of the dialog-based version of
37 snf-image-creator.
38 """
39
40 import time
41 import StringIO
42
43 from image_creator.kamaki_wrapper import Kamaki, ClientError
44 from image_creator.util import MD5, FatalError
45 from image_creator.output.cli import OutputWthProgress
46 from image_creator.dialog_util import extract_image, update_background_title
47
48 PAGE_WIDTH = 70
49
50
51 class WizardExit(Exception):
52     """Exception used to exit the wizard"""
53     pass
54
55
56 class WizardInvalidData(Exception):
57     """Exception triggered when the user provided data are invalid"""
58     pass
59
60
61 class Wizard:
62     """Represents a dialog-based wizard
63
64     The wizard is a collection of pages that have a "Next" and a "Back" button
65     on them. The pages are used to collect user data.
66     """
67
68     def __init__(self, session):
69         self.session = session
70         self.pages = []
71         self.session['wizard'] = {}
72         self.d = session['dialog']
73
74     def add_page(self, page):
75         """Add a new page to the wizard"""
76         self.pages.append(page)
77
78     def run(self):
79         """Run the wizard"""
80         idx = 0
81         while True:
82             try:
83                 idx += self.pages[idx].run(self.session, idx, len(self.pages))
84             except WizardExit:
85                 return False
86             except WizardInvalidData:
87                 continue
88
89             if idx >= len(self.pages):
90                 msg = "All necessary information has been gathered:\n\n"
91                 for page in self.pages:
92                     msg += " * %s\n" % page.info
93                 msg += "\nContinue with the image creation process?"
94
95                 ret = self.d.yesno(
96                     msg, width=PAGE_WIDTH, height=8 + len(self.pages),
97                     ok_label="Yes", cancel="Back", extra_button=1,
98                     extra_label="Quit", title="Confirmation")
99
100                 if ret == self.d.DIALOG_CANCEL:
101                     idx -= 1
102                 elif ret == self.d.DIALOG_EXTRA:
103                     return False
104                 elif ret == self.d.DIALOG_OK:
105                     return True
106
107             if idx < 0:
108                 return False
109
110
111 class WizardPage(object):
112     """Represents a page in a wizard"""
113     NEXT = 1
114     PREV = -1
115
116     def __init__(self, **kargs):
117         validate = kargs['validate'] if 'validate' in kargs else lambda x: x
118         setattr(self, "validate", validate)
119
120         display = kargs['display'] if 'display' in kargs else lambda x: x
121         setattr(self, "display", display)
122
123     def run(self, session, index, total):
124         """Display this wizard page
125
126         This function is used by the wizard program when accessing a page.
127         """
128         raise NotImplementedError
129
130
131 class WizardRadioListPage(WizardPage):
132     """Represent a Radio List in a wizard"""
133     def __init__(self, name, printable, message, choices, **kargs):
134         super(WizardRadioListPage, self).__init__(**kargs)
135         self.name = name
136         self.printable = printable
137         self.message = message
138         self.choices = choices
139         self.title = kargs['title'] if 'title' in kargs else ''
140         self.default = kargs['default'] if 'default' in kargs else ""
141
142     def run(self, session, index, total):
143         d = session['dialog']
144         w = session['wizard']
145
146         choices = []
147         for i in range(len(self.choices)):
148             default = 1 if self.choices[i][0] == self.default else 0
149             choices.append((self.choices[i][0], self.choices[i][1], default))
150
151         (code, answer) = d.radiolist(
152             self.message, height=10, width=PAGE_WIDTH, ok_label="Next",
153             cancel="Back", choices=choices,
154             title="(%d/%d) %s" % (index + 1, total, self.title))
155
156         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
157             return self.PREV
158
159         w[self.name] = self.validate(answer)
160         self.default = answer
161         self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
162
163         return self.NEXT
164
165
166 class WizardInputPage(WizardPage):
167     """Represents an input field in a wizard"""
168     def __init__(self, name, printable, message, **kargs):
169         super(WizardInputPage, self).__init__(**kargs)
170         self.name = name
171         self.printable = printable
172         self.message = message
173         self.info = "%s: <none>" % self.printable
174         self.title = kargs['title'] if 'title' in kargs else ''
175         self.init = kargs['init'] if 'init' in kargs else ''
176
177     def run(self, session, index, total):
178         d = session['dialog']
179         w = session['wizard']
180
181         (code, answer) = d.inputbox(
182             self.message, init=self.init, width=PAGE_WIDTH, ok_label="Next",
183             cancel="Back", title="(%d/%d) %s" % (index + 1, total, self.title))
184
185         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
186             return self.PREV
187
188         value = answer.strip()
189         self.init = value
190         w[self.name] = self.validate(value)
191         self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
192
193         return self.NEXT
194
195
196 def start_wizard(session):
197     """Run the image creation wizard"""
198     init_token = Kamaki.get_token()
199     if init_token is None:
200         init_token = ""
201
202     distro = session['image'].distro
203     ostype = session['image'].ostype
204     name = WizardInputPage(
205         "ImageName", "Image Name", "Please provide a name for the image:",
206         title="Image Name", init=ostype if distro == "unknown" else distro)
207
208     descr = WizardInputPage(
209         "ImageDescription", "Image Description",
210         "Please provide a description for the image:",
211         title="Image Description", init=session['metadata']['DESCRIPTION'] if
212         'DESCRIPTION' in session['metadata'] else '')
213
214     registration = WizardRadioListPage(
215         "ImageRegistration", "Registration Type",
216         "Please provide a registration type:",
217         [("Private", "Image is accessible only by this user"),
218          ("Public", "Everyone can create VMs from this image")],
219         title="Registration Type", default="Private")
220
221     def validate_account(token):
222         """Check if a token is valid"""
223         d = session['dialog']
224
225         if len(token) == 0:
226             d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
227             raise WizardInvalidData
228
229         account = Kamaki.get_account(token)
230         if account is None:
231             d.msgbox("The token you provided in not valid!", width=PAGE_WIDTH)
232             raise WizardInvalidData
233
234         return account
235
236     account = WizardInputPage(
237         "Account", "Account",
238         "Please provide your ~okeanos authentication token:",
239         title="~okeanos account", init=init_token, validate=validate_account,
240         display=lambda account: account['username'])
241
242     w = Wizard(session)
243
244     w.add_page(name)
245     w.add_page(descr)
246     w.add_page(registration)
247     w.add_page(account)
248
249     if w.run():
250         create_image(session)
251     else:
252         return False
253
254     return True
255
256
257 def create_image(session):
258     """Create an image using the information collected by the wizard"""
259     d = session['dialog']
260     image = session['image']
261     wizard = session['wizard']
262
263     # Save Kamaki credentials
264     Kamaki.save_token(wizard['Account']['auth_token'])
265
266     with_progress = OutputWthProgress(True)
267     out = image.out
268     out.add(with_progress)
269     try:
270         out.clear()
271
272         #Sysprep
273         image.os.do_sysprep()
274         metadata = image.os.meta
275
276         #Shrink
277         size = image.shrink()
278         session['shrinked'] = True
279         update_background_title(session)
280
281         metadata.update(image.meta)
282         metadata['DESCRIPTION'] = wizard['ImageDescription']
283
284         #MD5
285         md5 = MD5(out)
286         session['checksum'] = md5.compute(image.device, size)
287
288         #Metadata
289         metastring = '\n'.join(
290             ['%s=%s' % (key, value) for (key, value) in metadata.items()])
291         metastring += '\n'
292
293         out.output()
294         try:
295             out.output("Uploading image to pithos:")
296             kamaki = Kamaki(wizard['Account'], out)
297
298             name = "%s-%s.diskdump" % (wizard['ImageName'],
299                                        time.strftime("%Y%m%d%H%M"))
300             pithos_file = ""
301             with open(image.device, 'rb') as f:
302                 pithos_file = kamaki.upload(f, size, name,
303                                             "(1/4)  Calculating block hashes",
304                                             "(2/4)  Uploading missing blocks")
305
306             out.output("(3/4)  Uploading metadata file ...", False)
307             kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
308                           remote_path="%s.%s" % (name, 'meta'))
309             out.success('done')
310             out.output("(4/4)  Uploading md5sum file ...", False)
311             md5sumstr = '%s %s\n' % (session['checksum'], name)
312             kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
313                           remote_path="%s.%s" % (name, 'md5sum'))
314             out.success('done')
315             out.output()
316
317             is_public = True if wizard['ImageRegistration'] == "Public" else \
318                 False
319             out.output('Registering %s image with ~okeanos ...' %
320                        wizard['ImageRegistration'].lower(), False)
321             kamaki.register(wizard['ImageName'], pithos_file, metadata,
322                             is_public)
323             out.success('done')
324             if is_public:
325                 out.output("Sharing md5sum file ...", False)
326                 kamaki.share("%s.md5sum" % name)
327                 out.success('done')
328                 out.output("Sharing metadata file ...", False)
329                 kamaki.share("%s.meta" % name)
330                 out.success('done')
331
332             out.output()
333
334         except ClientError as e:
335             raise FatalError("Pithos client: %d %s" % (e.status, e.message))
336     finally:
337         out.remove(with_progress)
338
339     msg = "The %s image was successfully uploaded and registered with " \
340           "~okeanos. Would you like to keep a local copy of the image?" \
341           % wizard['ImageRegistration'].lower()
342     if not d.yesno(msg, width=PAGE_WIDTH):
343         extract_image(session)
344
345 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :