3 # Copyright 2012 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
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.
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.
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.
43 from image_creator import __version__ as version
44 from image_creator.util import FatalError, MD5
45 from image_creator.output.dialog import InitializationOutput, GaugeOutput
46 from image_creator.disk import Disk
47 from image_creator.os_type import os_cls
48 from image_creator.kamaki_wrapper import Kamaki, ClientError
56 class Reset(Exception):
60 def confirm_exit(d, msg=''):
61 return not d.yesno("%s Do you want to exit?" % msg, width=YESNO_WIDTH)
66 "Are you sure you want to reset everything?",
69 def extract_image(session):
73 if dir and dir[-1] != os.sep:
76 (code, path) = d.fselect(dir, 10, 50, title="Save image as...")
77 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
80 if os.path.isdir(path):
84 if os.path.isdir("%s.meta" % path):
85 d.msgbox("Can't overwrite directory `%s.meta'" % path,
89 if os.path.isdir("%s.md5sum" % path):
90 d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
94 basedir = os.path.dirname(path)
95 name = os.path.basename(path)
96 if not os.path.exists(basedir):
97 d.msgbox("Directory `%s' does not exist" % basedir,
105 files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
106 overwrite = filter(os.path.exists, files)
108 if len(overwrite) > 0:
109 if d.yesno("The following file(s) exist:\n"
110 "%s\nDo you want to overwrite them?" %
111 "\n".join(overwrite), width=YESNO_WIDTH):
114 out = GaugeOutput(d, "Image Extraction", "Extracting image...")
116 dev = session['device']
117 if "checksum" not in session:
118 size = dev.meta['SIZE']
120 session['checksum'] = md5.compute(session['snapshot'], size)
126 # Extract metadata file
127 out.output("Extracting metadata file...")
128 metastring = '\n'.join(
129 ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
131 with open('%s.meta' % path, 'w') as f:
135 # Extract md5sum file
136 out.output("Extracting md5sum file...")
137 md5str = "%s %s\n" % (session['checksum'], name)
138 with open('%s.md5sum' % path, 'w') as f:
144 d.msgbox("Image file `%s' was successfully extracted!" % path,
151 def upload_image(session):
152 d = session["dialog"]
153 size = session['device'].meta['SIZE']
155 if "account" not in session:
156 d.msgbox("You need to provide your ~okeanos login username before you "
157 "can upload images to pithos+", width=MSGBOX_WIDTH)
160 if "token" not in session:
161 d.msgbox("You need to provide your ~okeanos account authentication "
162 "token before you can upload images to pithos+",
167 init=session["upload"] if "upload" in session else ''
168 (code, answer) = d.inputbox("Please provide a filename:", init=init,
169 width=INPUTBOX_WIDTH)
171 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
174 filename = answer.strip()
175 if len(filename) == 0:
176 d.msgbox("Filename cannot be empty", width=MSGBOX_WIDTH)
181 out = GaugeOutput(d, "Image Upload", "Uploading...")
182 if 'checksum' not in session:
184 session['checksum'] = md5.compute(session['snapshot'], size)
186 kamaki = Kamaki(session['account'], session['token'], out)
189 with open(session['snapshot'], 'rb') as f:
190 session["upload"] = kamaki.upload(f, size, filename,
191 "Calculating block hashes",
192 "Uploading missing blocks")
193 # Upload metadata file
194 out.output("Uploading metadata file...")
195 metastring = '\n'.join(
196 ['%s=%s' % (k, v) for (k, v) in session['metadata'].items()])
198 kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
199 remote_path="%s.meta" % filename)
203 out.output("Uploading md5sum file...")
204 md5str = "%s %s\n" % (session['checksum'], filename)
205 kamaki.upload(StringIO.StringIO(md5str), size=len(md5str),
206 remote_path="%s.md5sum" % filename)
209 except ClientError as e:
210 d.msgbox("Error in pithos+ client: %s" % e.message,
211 title="Pithos+ Client Error", width=MSGBOX_WIDTH)
212 if 'upload' in session:
213 del session['upload']
218 d.msgbox("Image file `%s' was successfully uploaded to pithos+" % filename,
223 def register_image(session):
224 d = session["dialog"]
226 if "account" not in session:
227 d.msgbox("You need to provide your ~okeanos login username before you "
228 "can register an images to cyclades",
232 if "token" not in session:
233 d.msgbox("You need to provide your ~okeanos account authentication "
234 "token before you can register an images to cyclades",
238 if "upload" not in session:
239 d.msgbox("You need to have an image uploaded to pithos+ before you "
240 "can register it to cyclades",
245 (code, answer) = d.inputbox("Please provide a registration name:"
246 " be registered:", width=INPUTBOX_WIDTH)
247 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
250 name = answer.strip()
252 d.msgbox("Registration name cannot be empty", width=MSGBOX_WIDTH)
256 out = GaugeOutput(d, "Image Registration", "Registrating image...")
258 out.output("Registring image to cyclades...")
260 kamaki = Kamaki(session['account'], session['token'], out)
261 kamaki.register(name, session['upload'], session['metadata'])
263 except ClientError as e:
264 d.msgbox("Error in pithos+ client: %s" % e.message)
269 d.msgbox("Image `%s' was successfully registered to cyclades as `%s'" %
270 (session['upload'], name), width=MSGBOX_WIDTH)
274 def kamaki_menu(session):
275 d = session['dialog']
276 default_item = "Account"
278 account = session["account"] if "account" in session else "<none>"
279 token = session["token"] if "token" in session else "<none>"
280 upload = session["upload"] if "upload" in session else "<none>"
281 (code, choice) = d.menu(
282 "Choose one of the following or press <Back> to go back.",
284 choices=[("Account", "Change your ~okeanos username: %s" %
286 ("Token", "Change your ~okeanos token: %s" % token),
287 ("Upload", "Upload image to pithos+"),
288 ("Register", "Register image to cyclades: %s" % upload)],
290 default_item=default_item,
291 title="Image Registration Menu")
293 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
296 if choice == "Account":
297 default_item = "Account"
298 (code, answer) = d.inputbox(
299 "Please provide your ~okeanos account e-mail address:",
300 init=session["account"] if "account" in session else '',
302 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
304 if len(answer) == 0 and "account" in session:
305 del session["account"]
307 session["account"] = answer.strip()
308 default_item = "Token"
309 elif choice == "Token":
310 default_item = "Token"
311 (code, answer) = d.inputbox(
312 "Please provide your ~okeanos account authetication token:",
313 init=session["token"] if "token" in session else '',
315 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
317 if len(answer) == 0 and "token" in session:
320 session["token"] = answer.strip()
321 default_item = "Upload"
322 elif choice == "Upload":
323 if upload_image(session):
324 default_item = "Register"
326 default_item = "Upload"
327 elif choice == "Register":
328 if register_image(session):
331 default_item = "Register"
334 def main_menu(session):
335 d = session['dialog']
336 dev = session['device']
337 d.setBackgroundTitle("OS: %s, Distro: %s" % (dev.ostype, dev.distro))
338 actions = {"Register": kamaki_menu, "Extract": extract_image}
339 default_item = "Customize"
342 (code, choice) = d.menu(
343 "Choose one of the following or press <Exit> to exit.",
345 choices=[("Customize", "Run various image customization tasks"),
346 ("Deploy", "Configure ~okeanos image deployment options"),
347 ("Register", "Register image to ~okeanos"),
348 ("Extract", "Dump image to local file system"),
349 ("Reset", "Reset everything and start over again"),
350 ("Help", "Get help for using snf-image-creator")],
352 default_item=default_item,
353 title="Image Creator for ~okeanos (snf-image-creator version %s)" %
356 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
362 if choice == "Reset":
364 d.infobox("Resetting snf-image-creator. Please wait...")
368 elif choice in actions:
369 actions[choice](session)
375 (code, path) = d.fselect(root, 10, 50,
376 title="Please select input media")
377 if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
378 if confirm_exit(d, "You canceled the media selection dialog box."):
383 if not os.path.exists(path):
384 d.msgbox("The file you choose does not exist", width=MSGBOX_WIDTH)
392 def collect_metadata(dev, out):
394 out.output("Collecting image metadata...")
396 dev.mount(readonly=True)
397 cls = os_cls(dev.distro, dev.ostype)
398 image_os = cls(dev.root, dev.g, out)
400 metadata.update(image_os.meta)
406 def image_creator(d):
407 basename = os.path.basename(sys.argv[0])
408 usage = "Usage: %s [input_media]" % basename
409 if len(sys.argv) > 2:
410 sys.stderr.write("%s\n" % usage)
413 if os.geteuid() != 0:
414 raise FatalError("You must run %s as root" % basename)
416 media = sys.argv[1] if len(sys.argv) == 2 else select_file(d)
418 out = InitializationOutput(d)
419 disk = Disk(media, out)
421 def signal_handler(signum, fram):
425 signal.signal(signal.SIGINT, signal_handler)
427 snapshot = disk.snapshot()
428 dev = disk.get_device(snapshot)
430 metadata = collect_metadata(dev, out)
433 # Make sure the signal handler does not call out.cleanup again
436 instancemethod = type(InitializationOutput.cleanup)
437 out.cleanup = instancemethod(dummy, out, InitializationOutput)
439 session = {"dialog": d,
441 "snapshot": snapshot,
443 "metadata": metadata}
446 d.infobox("Thank you for using snf-image-creator. Bye", width=53)
455 d = dialog.Dialog(dialog="dialog")
460 ret = image_creator(d)
462 except FatalError as e:
463 msg = textwrap.fill(str(e), width=70)
464 d.infobox(msg, width=70, title="Fatal Error")
469 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :