b79d2b164989aae60bc5b11566e1ec74b7b32059
[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 import json
43
44 from image_creator.kamaki_wrapper import Kamaki, ClientError
45 from image_creator.util import MD5, FatalError
46 from image_creator.output.cli import OutputWthProgress
47 from image_creator.dialog_util import extract_image, update_background_title, \
48     add_cloud, edit_cloud
49
50 PAGE_WIDTH = 70
51 PAGE_HEIGHT = 10
52
53
54 class WizardExit(Exception):
55     """Exception used to exit the wizard"""
56     pass
57
58
59 class WizardReloadPage(Exception):
60     """Exception that reloads the last WizardPage"""
61     pass
62
63
64 class Wizard:
65     """Represents a dialog-based wizard
66
67     The wizard is a collection of pages that have a "Next" and a "Back" button
68     on them. The pages are used to collect user data.
69     """
70
71     def __init__(self, session):
72         self.session = session
73         self.pages = []
74         self.session['wizard'] = {}
75         self.d = session['dialog']
76
77     def add_page(self, page):
78         """Add a new page to the wizard"""
79         self.pages.append(page)
80
81     def run(self):
82         """Run the wizard"""
83         idx = 0
84         while True:
85             try:
86                 total = len(self.pages)
87                 title = "(%d/%d) %s" % (idx + 1, total, self.pages[idx].title)
88                 idx += self.pages[idx].run(self.session, title)
89             except WizardExit:
90                 return False
91             except WizardReloadPage:
92                 continue
93
94             if idx >= len(self.pages):
95                 text = "All necessary information has been gathered:\n\n"
96                 for page in self.pages:
97                     text += " * %s\n" % page.info
98                 text += "\nContinue with the image creation process?"
99
100                 ret = self.d.yesno(
101                     text, width=PAGE_WIDTH, height=8 + len(self.pages),
102                     ok_label="Yes", cancel="Back", extra_button=1,
103                     extra_label="Quit", title="Confirmation")
104
105                 if ret == self.d.DIALOG_CANCEL:
106                     idx -= 1
107                 elif ret == self.d.DIALOG_EXTRA:
108                     return False
109                 elif ret == self.d.DIALOG_OK:
110                     return True
111
112             if idx < 0:
113                 return False
114
115
116 class WizardPage(object):
117     """Represents a page in a wizard"""
118     NEXT = 1
119     PREV = -1
120
121     def __init__(self, name, display_name, text, **kargs):
122         self.name = name
123         self.display_name = display_name
124         self.text = text
125
126         self.title = kargs['title'] if 'title' in kargs else ""
127         self.default = kargs['default'] if 'default' in kargs else ""
128         self.extra = kargs['extra'] if 'extra' in kargs else None
129         self.extra_label = \
130             kargs['extra_label'] if 'extra_label' in kargs else 'Extra'
131
132         self.info = "%s: <none>" % self.display_name
133
134         validate = kargs['validate'] if 'validate' in kargs else lambda x: x
135         setattr(self, "validate", validate)
136
137         display = kargs['display'] if 'display' in kargs else lambda x: x
138         setattr(self, "display", display)
139
140     def run(self, session, title):
141         """Display this wizard page
142
143         This function is used by the wizard program when accessing a page.
144         """
145         raise NotImplementedError
146
147
148 class WizardPageWthChoices(WizardPage):
149     """Represents a Wizard Page that allows the user to select something from
150     a list of choices.
151
152     The available choices are created by a function passed to the class through
153     the choices variable. If the choices function returns an empty list, a
154     fallback funtion is executed if available.
155     """
156     def __init__(self, name, display_name, text, choices, **kargs):
157         super(WizardPageWthChoices, self).__init__(name, display_name, text,
158                                                    **kargs)
159         self.choices = choices
160         self.fallback = kargs['fallback'] if 'fallback' in kargs else None
161
162
163 class WizardRadioListPage(WizardPageWthChoices):
164     """Represent a Radio List in a wizard"""
165
166     def run(self, session, title):
167         d = session['dialog']
168         w = session['wizard']
169
170         choices = []
171         for choice in self.choices():
172             default = 1 if choice[0] == self.default else 0
173             choices.append((choice[0], choice[1], default))
174
175         (code, answer) = d.radiolist(
176             self.text, width=PAGE_WIDTH, ok_label="Next", cancel="Back",
177             choices=choices, height=PAGE_HEIGHT, title=title)
178
179         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
180             return self.PREV
181
182         w[self.name] = self.validate(answer)
183         self.default = answer
184         self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
185
186         return self.NEXT
187
188
189 class WizardInputPage(WizardPage):
190     """Represents an input field in a wizard"""
191
192     def run(self, session, title):
193         d = session['dialog']
194         w = session['wizard']
195
196         (code, answer) = d.inputbox(
197             self.text, init=self.default, width=PAGE_WIDTH, ok_label="Next",
198             cancel="Back", height=PAGE_HEIGHT, title=title)
199
200         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
201             return self.PREV
202
203         value = answer.strip()
204         self.default = value
205         w[self.name] = self.validate(value)
206         self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
207
208         return self.NEXT
209
210
211 class WizardFormPage(WizardPage):
212     """Represents a Form in a wizard"""
213
214     def __init__(self, name, display_name, text, fields, **kargs):
215         super(WizardFormPage, self).__init__(name, display_name, text, **kargs)
216         self.fields = fields
217
218     def run(self, session, title):
219         d = session['dialog']
220         w = session['wizard']
221
222         field_lenght = len(self.fields())
223         form_height = field_lenght if field_lenght < PAGE_HEIGHT - 4 \
224             else PAGET_HEIGHT - 4
225
226         (code, output) = d.form(
227             self.text, width=PAGE_WIDTH, height=PAGE_HEIGHT,
228             form_height=form_height, ok_label="Next", cancel="Back",
229             fields=self.fields(), title=title)
230
231         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
232             return self.PREV
233
234         w[self.name] = self.validate(output)
235         self.default = output
236         self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
237
238         return self.NEXT
239
240
241 class WizardMenuPage(WizardPageWthChoices):
242     """Represents a menu dialog with available choices in a wizard"""
243
244     def run(self, session, title):
245         d = session['dialog']
246         w = session['wizard']
247
248         extra_button = 1 if self.extra else 0
249
250         choices = self.choices()
251
252         if len(choices) == 0:
253             assert self.fallback, "Zero choices and no fallback"
254             if self.fallback():
255                 raise WizardReloadPage
256             else:
257                 return self.PREV
258
259         default_item = self.default if self.default else choices[0][0]
260
261         (code, choice) = d.menu(
262             self.text, width=PAGE_WIDTH, ok_label="Next", cancel="Back",
263             title=title, choices=choices, height=PAGE_HEIGHT,
264             default_item=default_item, extra_label=self.extra_label,
265             extra_button=extra_button)
266
267         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
268             return self.PREV
269         elif code == d.DIALOG_EXTRA:
270             self.extra()
271             raise WizardReloadPage
272
273         self.default = choice
274         w[self.name] = self.validate(choice)
275         self.info = "%s: %s" % (self.display_name, self.display(w[self.name]))
276
277         return self.NEXT
278
279
280 def start_wizard(session):
281     """Run the image creation wizard"""
282
283     image = session['image']
284     distro = image.distro
285     ostype = image.ostype
286
287     # Create Cloud Wizard Page
288     def cloud_choices():
289         choices = []
290         for (name, cloud) in Kamaki.get_clouds().items():
291             descr = cloud['description'] if 'description' in cloud else ''
292             choices.append((name, descr))
293
294         return choices
295
296     def cloud_add():
297         return add_cloud(session)
298
299     def cloud_none_available():
300         if not session['dialog'].yesno(
301                 "No available clouds found. Would you like to add one now?",
302                 width=PAGE_WIDTH, defaultno=0):
303             return add_cloud(session)
304         return False
305
306     def cloud_validate(cloud):
307         if not Kamaki.get_account(cloud):
308             if not session['dialog'].yesno(
309                     "The cloud you have selected is not valid! Would you "
310                     "like to edit it now?", width=PAGE_WIDTH, defaultno=0):
311                 if edit_cloud(session, cloud):
312                     return cloud
313
314             raise WizardReloadPage
315
316         return cloud
317
318     cloud = WizardMenuPage(
319         "Cloud", "Cloud",
320         "Please select a cloud account or press <Add> to add a new one:",
321         choices=cloud_choices, extra_label="Add", extra=cloud_add,
322         title="Clouds", validate=cloud_validate, fallback=cloud_none_available)
323
324     # Create Image Name Wizard Page
325     name = WizardInputPage(
326         "ImageName", "Image Name", "Please provide a name for the image:",
327         title="Image Name", default=ostype if distro == "unknown" else distro)
328
329     # Create Image Description Wizard Page
330     descr = WizardInputPage(
331         "ImageDescription", "Image Description",
332         "Please provide a description for the image:",
333         title="Image Description", default=session['metadata']['DESCRIPTION']
334         if 'DESCRIPTION' in session['metadata'] else '')
335
336     # Create Sysprep Params Wizard Page
337     needed = image.os.needed_sysprep_params
338     param_names = needed.keys()
339
340     def sysprep_params_fields():
341         fields = []
342         available = image.os.sysprep_params
343         for name in param_names:
344             text = needed[name].description
345             default = available[name] if name in available else ""
346             fields.append(("%s: " % text, default, needed[name].maxlen))
347         return fields
348
349     def sysprep_params_validate(answer):
350         params = {}
351         for i in range(len(answer)):
352             if needed[param_names[i]].validator(answer):
353                 params[param_names[i]] = answer[i]
354             else:
355                 session['dialog'].msgbox("Invalid value for parameter `%s'" %
356                                          param_names[i])
357                 raise WizardReloadPage
358         return params
359
360     def sysprep_params_display(params):
361         return ",".join(["%s=%s" % (key, val) for key, val in params.items()])
362
363     sysprep_params = WizardFormPage(
364         "SysprepParams", "Sysprep Parameters",
365         "Prease fill in the following system preparation parameters:",
366         title="System Preparation Parameters", fields=sysprep_params_fields,
367         display=sysprep_params_display, validate=sysprep_params_validate
368     ) if len(needed) != 0 else None
369
370     # Create Image Registration Wizard Page
371     def registration_choices():
372         return [("Private", "Image is accessible only by this user"),
373                 ("Public", "Everyone can create VMs from this image")]
374
375     registration = WizardRadioListPage(
376         "ImageRegistration", "Registration Type",
377         "Please provide a registration type:", registration_choices,
378         title="Registration Type", default="Private")
379
380     w = Wizard(session)
381
382     w.add_page(cloud)
383     w.add_page(name)
384     w.add_page(descr)
385     if sysprep_params is not None:
386         w.add_page(sysprep_params)
387     w.add_page(registration)
388
389     if w.run():
390         create_image(session)
391     else:
392         return False
393
394     return True
395
396
397 def create_image(session):
398     """Create an image using the information collected by the wizard"""
399     d = session['dialog']
400     image = session['image']
401     wizard = session['wizard']
402
403     with_progress = OutputWthProgress(True)
404     out = image.out
405     out.add(with_progress)
406     try:
407         out.clear()
408
409         #Sysprep
410         image.os.sysprep_params.update(wizard['SysprepParams'])
411         image.os.do_sysprep()
412         metadata = image.os.meta
413
414         #Shrink
415         size = image.shrink()
416         session['shrinked'] = True
417         update_background_title(session)
418
419         metadata.update(image.meta)
420         metadata['DESCRIPTION'] = wizard['ImageDescription']
421
422         #MD5
423         md5 = MD5(out)
424         session['checksum'] = md5.compute(image.device, size)
425
426         out.output()
427         try:
428             out.output("Uploading image to the cloud:")
429             account = Kamaki.get_account(wizard['Cloud'])
430             assert account, "Cloud: %s is not valid" % wizard['Cloud']
431             kamaki = Kamaki(account, out)
432
433             name = "%s-%s.diskdump" % (wizard['ImageName'],
434                                        time.strftime("%Y%m%d%H%M"))
435             pithos_file = ""
436             with open(image.device, 'rb') as f:
437                 pithos_file = kamaki.upload(f, size, name,
438                                             "(1/3)  Calculating block hashes",
439                                             "(2/3)  Uploading missing blocks")
440
441             out.output("(3/3)  Uploading md5sum file ...", False)
442             md5sumstr = '%s %s\n' % (session['checksum'], name)
443             kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
444                           remote_path="%s.%s" % (name, 'md5sum'))
445             out.success('done')
446             out.output()
447
448             is_public = True if wizard['ImageRegistration'] == "Public" else \
449                 False
450             out.output('Registering %s image with the cloud ...' %
451                        wizard['ImageRegistration'].lower(), False)
452             result = kamaki.register(wizard['ImageName'], pithos_file,
453                                      metadata, is_public)
454             out.success('done')
455             out.output("Uploading metadata file ...", False)
456             metastring = unicode(json.dumps(result, ensure_ascii=False))
457             kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
458                           remote_path="%s.%s" % (name, 'meta'))
459             out.success('done')
460
461             if is_public:
462                 out.output("Sharing md5sum file ...", False)
463                 kamaki.share("%s.md5sum" % name)
464                 out.success('done')
465                 out.output("Sharing metadata file ...", False)
466                 kamaki.share("%s.meta" % name)
467                 out.success('done')
468
469             out.output()
470
471         except ClientError as e:
472             raise FatalError("Storage service client: %d %s" %
473                              (e.status, e.message))
474     finally:
475         out.remove(with_progress)
476
477     text = "The %s image was successfully uploaded to the storage service " \
478            "and registered with the compute service of %s. Would you like " \
479            "to keep a local copy?" % \
480            (wizard['Cloud'], wizard['ImageRegistration'].lower())
481
482     if not d.yesno(text, width=PAGE_WIDTH):
483         extract_image(session)
484
485 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :