Fix minor typos
[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
62     def add_page(self, page):
63         self.pages.append(page)
64
65     def run(self):
66         idx = 0
67         while True:
68             try:
69                 idx += self.pages[idx].run(self.session, idx, len(self.pages))
70             except WizardExit:
71                 return False
72             except WizardInvalidData:
73                 continue
74
75             if idx >= len(self.pages):
76                 break
77
78             if idx < 0:
79                 return False
80         return True
81
82
83 class WizardPage:
84     NEXT = 1
85     PREV = -1
86
87     def run(self, session, index, total):
88         raise NotImplementedError
89
90
91 class WizardRadioListPage(WizardPage):
92
93     def __init__(self, name, message, choices, **kargs):
94         self.name = name
95         self.message = message
96         self.choices = choices
97         self.title = kargs['title'] if 'title' in kargs else ''
98         self.default = kargs['default'] if 'default' in kargs else 0
99
100     def run(self, session, index, total):
101         d = session['dialog']
102         w = session['wizard']
103
104         choices = []
105         for i in range(len(self.choices)):
106             default = 1 if i == self.default else 0
107             choices.append((self.choices[i][0], self.choices[i][1], default))
108
109         while True:
110             (code, answer) = \
111                 d.radiolist(self.message, width=PAGE_WIDTH,
112                             ok_label="Next", cancel="Back", choices=choices,
113                             title="(%d/%d) %s" % (index + 1, total, self.title)
114                             )
115
116             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
117                 return self.PREV
118
119             for i in range(len(choices)):
120                 if self.choices[i] == answer:
121                     self.default = i
122                     w[name] = i
123                     break
124
125             return self.NEXT
126
127
128 class WizardInputPage(WizardPage):
129
130     def __init__(self, name, message, **kargs):
131         self.name = name
132         self.message = message
133         self.title = kargs['title'] if 'title' in kargs else ''
134         self.init = kargs['init'] if 'init' in kargs else ''
135         if 'validate' in kargs:
136             validate = kargs['validate']
137         else:
138             validate = lambda x: x
139
140         setattr(self, "validate", validate)
141
142     def run(self, session, index, total):
143         d = session['dialog']
144         w = session['wizard']
145
146         while True:
147             (code, answer) = \
148                 d.inputbox(self.message, init=self.init,
149                            width=PAGE_WIDTH, ok_label="Next", cancel="Back",
150                            title="(%d/%d) %s" % (index + 1, total, self.title))
151
152             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
153                 return self.PREV
154
155             value = answer.strip()
156             self.init = value
157             w[self.name] = self.validate(value)
158             break
159
160         return self.NEXT
161
162
163 class WizardYesNoPage(WizardPage):
164
165     def __init__(self, message, **kargs):
166         self.message = message
167         self.title = kargs['title'] if 'title' in kargs else ''
168
169     def run(self, session, index, total):
170         d = session['dialog']
171
172         while True:
173             ret = d.yesno(self.message, width=PAGE_WIDTH, ok_label="Yes",
174                           cancel="Back", extra_button=1, extra_label="Quit",
175                           title="(%d/%d) %s" % (index + 1, total, self.title))
176
177             if ret == d.DIALOG_CANCEL:
178                 return self.PREV
179             elif ret == d.DIALOG_EXTRA:
180                 raise WizardExit
181             elif ret == d.DIALOG_OK:
182                 return self.NEXT
183
184
185 def wizard(session):
186
187     init_token = Kamaki.get_token()
188     if init_token is None:
189         init_token = ""
190
191     name = WizardInputPage("ImageName", "Please provide a name for the image:",
192                            title="Image Name", init=session['device'].distro)
193     descr = WizardInputPage("ImageDescription",
194                             "Please provide a description for the image:",
195                             title="Image Description",
196                             init=session['metadata']['DESCRIPTION'] if
197                             'DESCRIPTION' in session['metadata'] else '')
198
199     def validate_account(token):
200         if len(token) == 0:
201             d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
202             raise WizardInvalidData
203
204         account = Kamaki.get_account(token)
205         if account is None:
206             session['dialog'].msgbox("The token you provided in not valid!",
207                 width=PAGE_WIDTH)
208             raise WizardInvalidData
209
210         return account
211
212     account = WizardInputPage("account",
213         "Please provide your ~okeanos authentication token:",
214         title="~okeanos account token", init=init_token,
215         validate=validate_account)
216
217     msg = "All necessary information has been gathered. Confirm and Proceed."
218     proceed = WizardYesNoPage(msg, title="Confirmation")
219
220     w = Wizard(session)
221
222     w.add_page(name)
223     w.add_page(descr)
224     w.add_page(account)
225     w.add_page(proceed)
226
227     if w.run():
228         create_image(session)
229     else:
230         return False
231
232     return True
233
234
235 def create_image(session):
236     d = session['dialog']
237     disk = session['disk']
238     device = session['device']
239     snapshot = session['snapshot']
240     image_os = session['image_os']
241     wizard = session['wizard']
242
243     # Save Kamaki credentials
244     Kamaki.save_token(wizard['account']['auth_token'])
245
246     with_progress = OutputWthProgress(True)
247     out = disk.out
248     out.add(with_progress)
249     try:
250         out.clear()
251
252         #Sysprep
253         device.mount(False)
254         image_os.do_sysprep()
255         metadata = image_os.meta
256         device.umount()
257
258         #Shrink
259         size = device.shrink()
260         session['shrinked'] = True
261         update_background_title(session)
262
263         metadata.update(device.meta)
264         metadata['DESCRIPTION'] = wizard['ImageDescription']
265
266         #MD5
267         md5 = MD5(out)
268         session['checksum'] = md5.compute(snapshot, size)
269
270         #Metadata
271         metastring = '\n'.join(
272             ['%s=%s' % (key, value) for (key, value) in metadata.items()])
273         metastring += '\n'
274
275         out.output()
276         try:
277             out.output("Uploading image to pithos:")
278             kamaki = Kamaki(wizard['account'], out)
279
280             name = "%s-%s.diskdump" % (wizard['ImageName'],
281                                        time.strftime("%Y%m%d%H%M"))
282             pithos_file = ""
283             with open(snapshot, 'rb') as f:
284                 pithos_file = kamaki.upload(f, size, name,
285                                             "(1/4)  Calculating block hashes",
286                                             "(2/4)  Uploading missing blocks")
287
288             out.output("(3/4)  Uploading metadata file ...", False)
289             kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
290                           remote_path="%s.%s" % (name, 'meta'))
291             out.success('done')
292             out.output("(4/4)  Uploading md5sum file ...", False)
293             md5sumstr = '%s %s\n' % (session['checksum'], name)
294             kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
295                           remote_path="%s.%s" % (name, 'md5sum'))
296             out.success('done')
297             out.output()
298
299             out.output('Registering image with ~okeanos ...', False)
300             kamaki.register(wizard['ImageName'], pithos_file, metadata)
301             out.success('done')
302             out.output()
303
304         except ClientError as e:
305             raise FatalError("Pithos client: %d %s" % (e.status, e.message))
306     finally:
307         out.remove(with_progress)
308
309     msg = "The image was successfully uploaded and registered with " \
310           "~okeanos. Would you like to keep a local copy of the image?"
311     if not d.yesno(msg, width=PAGE_WIDTH):
312         extract_image(session)
313
314 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :