Support private images
[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 self.choices[i][0] == 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, height=10, 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             w[self.name] = answer
120             self.default = answer
121
122             return self.NEXT
123
124
125 class WizardInputPage(WizardPage):
126
127     def __init__(self, name, message, **kargs):
128         self.name = name
129         self.message = message
130         self.title = kargs['title'] if 'title' in kargs else ''
131         self.init = kargs['init'] if 'init' in kargs else ''
132         if 'validate' in kargs:
133             validate = kargs['validate']
134         else:
135             validate = lambda x: x
136
137         setattr(self, "validate", validate)
138
139     def run(self, session, index, total):
140         d = session['dialog']
141         w = session['wizard']
142
143         while True:
144             (code, answer) = \
145                 d.inputbox(self.message, init=self.init,
146                            width=PAGE_WIDTH, ok_label="Next", cancel="Back",
147                            title="(%d/%d) %s" % (index + 1, total, self.title))
148
149             if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
150                 return self.PREV
151
152             value = answer.strip()
153             self.init = value
154             w[self.name] = self.validate(value)
155             break
156
157         return self.NEXT
158
159
160 class WizardYesNoPage(WizardPage):
161
162     def __init__(self, message, **kargs):
163         self.message = message
164         self.title = kargs['title'] if 'title' in kargs else ''
165
166     def run(self, session, index, total):
167         d = session['dialog']
168
169         while True:
170             ret = d.yesno(self.message, width=PAGE_WIDTH, ok_label="Yes",
171                           cancel="Back", extra_button=1, extra_label="Quit",
172                           title="(%d/%d) %s" % (index + 1, total, self.title))
173
174             if ret == d.DIALOG_CANCEL:
175                 return self.PREV
176             elif ret == d.DIALOG_EXTRA:
177                 raise WizardExit
178             elif ret == d.DIALOG_OK:
179                 return self.NEXT
180
181
182 def wizard(session):
183
184     init_token = Kamaki.get_token()
185     if init_token is None:
186         init_token = ""
187
188     name = WizardInputPage("ImageName", "Please provide a name for the image:",
189                            title="Image Name", init=session['device'].distro)
190     descr = WizardInputPage(
191         "ImageDescription", "Please provide a description for the image:",
192         title="Image Description", init=session['metadata']['DESCRIPTION'] if
193         'DESCRIPTION' in session['metadata'] else '')
194     registration = WizardRadioListPage(
195         "ImageRegistration", "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")
199
200     def validate_account(token):
201         if len(token) == 0:
202             d.msgbox("The token cannot be empty", width=PAGE_WIDTH)
203             raise WizardInvalidData
204
205         account = Kamaki.get_account(token)
206         if account is None:
207             session['dialog'].msgbox("The token you provided in not valid!",
208                                      width=PAGE_WIDTH)
209             raise WizardInvalidData
210
211         return account
212
213     account = WizardInputPage(
214         "account", "Please provide your ~okeanos authentication token:",
215         title="~okeanos account", init=init_token, 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(registration)
225     w.add_page(account)
226     w.add_page(proceed)
227
228     if w.run():
229         create_image(session)
230     else:
231         return False
232
233     return True
234
235
236 def create_image(session):
237     d = session['dialog']
238     disk = session['disk']
239     device = session['device']
240     snapshot = session['snapshot']
241     image_os = session['image_os']
242     wizard = session['wizard']
243
244     # Save Kamaki credentials
245     Kamaki.save_token(wizard['account']['auth_token'])
246
247     with_progress = OutputWthProgress(True)
248     out = disk.out
249     out.add(with_progress)
250     try:
251         out.clear()
252
253         #Sysprep
254         device.mount(False)
255         image_os.do_sysprep()
256         metadata = image_os.meta
257         device.umount()
258
259         #Shrink
260         size = device.shrink()
261         session['shrinked'] = True
262         update_background_title(session)
263
264         metadata.update(device.meta)
265         metadata['DESCRIPTION'] = wizard['ImageDescription']
266
267         #MD5
268         md5 = MD5(out)
269         session['checksum'] = md5.compute(snapshot, size)
270
271         #Metadata
272         metastring = '\n'.join(
273             ['%s=%s' % (key, value) for (key, value) in metadata.items()])
274         metastring += '\n'
275
276         out.output()
277         try:
278             out.output("Uploading image to pithos:")
279             kamaki = Kamaki(wizard['account'], out)
280
281             name = "%s-%s.diskdump" % (wizard['ImageName'],
282                                        time.strftime("%Y%m%d%H%M"))
283             pithos_file = ""
284             with open(snapshot, 'rb') as f:
285                 pithos_file = kamaki.upload(f, size, name,
286                                             "(1/4)  Calculating block hashes",
287                                             "(2/4)  Uploading missing blocks")
288
289             out.output("(3/4)  Uploading metadata file ...", False)
290             kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
291                           remote_path="%s.%s" % (name, 'meta'))
292             out.success('done')
293             out.output("(4/4)  Uploading md5sum file ...", False)
294             md5sumstr = '%s %s\n' % (session['checksum'], name)
295             kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr),
296                           remote_path="%s.%s" % (name, 'md5sum'))
297             out.success('done')
298             out.output()
299
300             is_public = True if w['ImageRegistration'] == "Public" else False
301             out.output('Registering %s image with ~okeanos ...' %
302                        w['ImageRegistration'].lower(), False)
303             kamaki.register(wizard['ImageName'], pithos_file, metadata,
304                             is_public)
305             out.success('done')
306             out.output()
307
308         except ClientError as e:
309             raise FatalError("Pithos client: %d %s" % (e.status, e.message))
310     finally:
311         out.remove(with_progress)
312
313     msg = "The %s image was successfully uploaded and registered with " \
314           "~okeanos. Would you like to keep a local copy of the image?" \
315           % w['ImageRegistration'].lower()
316     if not d.yesno(msg, width=PAGE_WIDTH):
317         extract_image(session)
318
319 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :