Display gathered info in wizard's confirmation box
[snf-image-creator] / image_creator / dialog_wizard.py
1 #!/usr/bin/env python
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 import dialog
37 import time
38 import StringIO
39
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
44
45 PAGE_WIDTH = 70
46
47
48 class WizardExit(Exception):
49     pass
50
51
52 class WizardInvalidData(Exception):
53     pass
54
55
56 class Wizard:
57     def __init__(self, session):
58         self.session = session
59         self.pages = []
60         self.session['wizard'] = {}
61         self.d = session['dialog']
62
63     def add_page(self, page):
64         self.pages.append(page)
65
66     def run(self):
67         idx = 0
68         while True:
69             try:
70                 idx += self.pages[idx].run(self.session, idx, len(self.pages))
71             except WizardExit:
72                 return False
73             except WizardInvalidData:
74                 continue
75
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."
81
82                 ret = self.d.yesno(
83                     msg, width=PAGE_WIDTH, height=12, ok_label="Yes",
84                     cancel="Back", extra_button=1, extra_label="Quit",
85                     title="Confirmation")
86
87                 if ret == self.d.DIALOG_CANCEL:
88                     idx -= 1
89                 elif ret == self.d.DIALOG_EXTRA:
90                     return False
91                 elif ret == self.d.DIALOG_OK:
92                     return True
93
94             if idx < 0:
95                 return False
96
97
98 class WizardPage(object):
99     NEXT = 1
100     PREV = -1
101
102     def __init__(self, **kargs):
103         if 'validate' in kargs:
104             validate = kargs['validate']
105         else:
106             validate = lambda x: x
107         setattr(self, "validate", validate)
108
109         if 'display' in kargs:
110             display = kargs['display']
111         else:
112             display = lambda x: x
113         setattr(self, "display", display)
114
115     def run(self, session, index, total):
116         raise NotImplementedError
117
118
119 class WizardRadioListPage(WizardPage):
120
121     def __init__(self, name, printable, message, choices, **kargs):
122         super(WizardRadioListPage, self).__init__(**kargs)
123         self.name = name
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 ""
129
130     def run(self, session, index, total):
131         d = session['dialog']
132         w = session['wizard']
133
134         choices = []
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))
138
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))
143
144         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
145             return self.PREV
146
147         w[self.name] = self.validate(answer)
148         self.default = answer
149         self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
150
151         return self.NEXT
152
153
154 class WizardInputPage(WizardPage):
155
156     def __init__(self, name, printable, message, **kargs):
157         super(WizardInputPage, self).__init__(**kargs)
158         self.name = name
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 ''
163
164     def run(self, session, index, total):
165         d = session['dialog']
166         w = session['wizard']
167
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))
171
172         if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
173             return self.PREV
174
175         value = answer.strip()
176         self.init = value
177         w[self.name] = self.validate(value)
178         self.info = "%s: %s" % (self.printable, self.display(w[self.name]))
179
180         return self.NEXT
181
182
183 def wizard(session):
184
185     init_token = Kamaki.get_token()
186     if init_token is None:
187         init_token = ""
188
189     name = WizardInputPage(
190         "ImageName", "Image Name", "Please provide a name for the image:",
191         title="Image Name", init=session['device'].distro)
192
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 '')
198
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")
205
206     def validate_account(token):
207         if len(token) == 0:
208             d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
209             raise WizardInvalidData
210
211         account = Kamaki.get_account(token)
212         if account is None:
213             session['dialog'].msgbox("The token you provided in not valid!",
214                                      width=PAGE_WIDTH)
215             raise WizardInvalidData
216
217         return account
218
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'])
224
225     w = Wizard(session)
226
227     w.add_page(name)
228     w.add_page(descr)
229     w.add_page(registration)
230     w.add_page(account)
231
232     if w.run():
233         create_image(session)
234     else:
235         return False
236
237     return True
238
239
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']
247
248     # Save Kamaki credentials
249     Kamaki.save_token(wizard['Account']['auth_token'])
250
251     with_progress = OutputWthProgress(True)
252     out = disk.out
253     out.add(with_progress)
254     try:
255         out.clear()
256
257         #Sysprep
258         device.mount(False)
259         image_os.do_sysprep()
260         metadata = image_os.meta
261         device.umount()
262
263         #Shrink
264         size = device.shrink()
265         session['shrinked'] = True
266         update_background_title(session)
267
268         metadata.update(device.meta)
269         metadata['DESCRIPTION'] = wizard['ImageDescription']
270
271         #MD5
272         md5 = MD5(out)
273         session['checksum'] = md5.compute(snapshot, size)
274
275         #Metadata
276         metastring = '\n'.join(
277             ['%s=%s' % (key, value) for (key, value) in metadata.items()])
278         metastring += '\n'
279
280         out.output()
281         try:
282             out.output("Uploading image to pithos:")
283             kamaki = Kamaki(wizard['Account'], out)
284
285             name = "%s-%s.diskdump" % (wizard['ImageName'],
286                                        time.strftime("%Y%m%d%H%M"))
287             pithos_file = ""
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")
292
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'))
296             out.success('done')
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'))
301             out.success('done')
302             out.output()
303
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,
308                             is_public)
309             out.success('done')
310             out.output()
311
312         except ClientError as e:
313             raise FatalError("Pithos client: %d %s" % (e.status, e.message))
314     finally:
315         out.remove(with_progress)
316
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)
322
323 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :