Commit 023e1217 authored by Nikos Skalkotos's avatar Nikos Skalkotos
Browse files

Code cleanup and refactoring

Create a new dialog_menu module to host all the "expert mode" code.
Check the code with a new version of pep8
parent dcf9274b
This diff is collapsed.
This diff is collapsed.
#!/usr/bin/env python
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
import os
SMALL_WIDTH = 60
WIDTH = 70
def update_background_title(session):
d = session['dialog']
dev = session['device']
MB = 2 ** 20
size = (dev.size + MB - 1) // MB
shrinked = 'shrinked' in session and session['shrinked']
postfix = " (shrinked)" if shrinked else ''
title = "OS: %s, Distro: %s, Size: %dMB%s" % \
(dev.ostype, dev.distro, size, postfix)
d.setBackgroundTitle(title)
def confirm_exit(d, msg=''):
return not d.yesno("%s Do you want to exit?" % msg, width=SMALL_WIDTH)
def confirm_reset(d):
return not d.yesno("Are you sure you want to reset everything?",
width=SMALL_WIDTH, defaultno=1)
class Reset(Exception):
pass
def extract_image(session):
d = session['dialog']
dir = os.getcwd()
while 1:
if dir and dir[-1] != os.sep:
dir = dir + os.sep
(code, path) = d.fselect(dir, 10, 50, title="Save image as...")
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
return False
if os.path.isdir(path):
dir = path
continue
if os.path.isdir("%s.meta" % path):
d.msgbox("Can't overwrite directory `%s.meta'" % path,
width=SMALL_WIDTH)
continue
if os.path.isdir("%s.md5sum" % path):
d.msgbox("Can't overwrite directory `%s.md5sum'" % path,
width=SMALL_WIDTH)
continue
basedir = os.path.dirname(path)
name = os.path.basename(path)
if not os.path.exists(basedir):
d.msgbox("Directory `%s' does not exist" % basedir,
width=SMALL_WIDTH)
continue
dir = basedir
if len(name) == 0:
continue
files = ["%s%s" % (path, ext) for ext in ('', '.meta', '.md5sum')]
overwrite = filter(os.path.exists, files)
if len(overwrite) > 0:
if d.yesno("The following file(s) exist:\n"
"%s\nDo you want to overwrite them?" %
"\n".join(overwrite), width=SMALL_WIDTH):
continue
gauge = GaugeOutput(d, "Image Extraction", "Extracting image...")
try:
dev = session['device']
out = dev.out
out.add(gauge)
try:
if "checksum" not in session:
size = dev.size
md5 = MD5(out)
session['checksum'] = md5.compute(session['snapshot'],
size)
# Extract image file
dev.dump(path)
# Extract metadata file
out.output("Extracting metadata file...")
with open('%s.meta' % path, 'w') as f:
f.write(extract_metadata_string(session))
out.success('done')
# Extract md5sum file
out.output("Extracting md5sum file...")
md5str = "%s %s\n" % (session['checksum'], name)
with open('%s.md5sum' % path, 'w') as f:
f.write(md5str)
out.success("done")
finally:
out.remove(gauge)
finally:
gauge.cleanup()
d.msgbox("Image file `%s' was successfully extracted!" % path,
width=SMALL_WIDTH)
break
return True
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
......@@ -40,6 +40,7 @@ import StringIO
from image_creator.kamaki_wrapper import Kamaki, ClientError
from image_creator.util import MD5, FatalError
from image_creator.output.cli import OutputWthProgress
from image_creator.dialog_util import extract_image, update_background_title
PAGE_WIDTH = 70
......@@ -100,9 +101,11 @@ class WizardRadioListPage(WizardPage):
choices.append((self.choices[i][0], self.choices[i][1], default))
while True:
(code, answer) = d.radiolist(self.message, width=PAGE_WIDTH,
ok_label="Next", cancel="Back", choices=choices,
title="(%d/%d) %s" % (index + 1, total, self.title))
(code, answer) = \
d.radiolist(self.message, width=PAGE_WIDTH,
ok_label="Next", cancel="Back", choices=choices,
title="(%d/%d) %s" % (index + 1, total, self.title)
)
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
return self.PREV
......@@ -131,9 +134,10 @@ class WizardInputPage(WizardPage):
init = w[self.name] if self.name in w else self.init_value
while True:
(code, answer) = d.inputbox(self.message, init=init,
width=PAGE_WIDTH, ok_label="Next", cancel="Back",
title="(%d/%d) %s" % (index + 1, total, self.title))
(code, answer) = \
d.inputbox(self.message, init=init,
width=PAGE_WIDTH, ok_label="Next", cancel="Back",
title="(%d/%d) %s" % (index + 1, total, self.title))
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
return self.PREV
......@@ -159,8 +163,8 @@ class WizardYesNoPage(WizardPage):
while True:
ret = d.yesno(self.message, width=PAGE_WIDTH, ok_label="Yes",
cancel="Back", extra_button=1, extra_label="Quit",
title="(%d/%d) %s" % (index + 1, total, self.title))
cancel="Back", extra_button=1, extra_label="Quit",
title="(%d/%d) %s" % (index + 1, total, self.title))
if ret == d.DIALOG_CANCEL:
return self.PREV
......@@ -173,18 +177,20 @@ class WizardYesNoPage(WizardPage):
def wizard(session):
name = WizardInputPage("ImageName", "Please provide a name for the image:",
title="Image Name", init=session['device'].distro)
title="Image Name", init=session['device'].distro)
descr = WizardInputPage("ImageDescription",
"Please provide a description for the image:",
title="Image Description", empty=True,
init=session['metadata']['DESCRIPTION'] if 'DESCRIPTION' in
session['metadata'] else '')
"Please provide a description for the image:",
title="Image Description", empty=True,
init=session['metadata']['DESCRIPTION'] if
'DESCRIPTION' in session['metadata'] else '')
account = WizardInputPage("account",
"Please provide your ~okeanos account e-mail:",
title="~okeanos account information", init=Kamaki.get_account())
"Please provide your ~okeanos account e-mail:",
title="~okeanos account information",
init=Kamaki.get_account())
token = WizardInputPage("token",
"Please provide your ~okeanos account token:",
title="~okeanos account token", init=Kamaki.get_token())
"Please provide your ~okeanos account token:",
title="~okeanos account token",
init=Kamaki.get_token())
msg = "All necessary information has been gathered. Confirm and Proceed."
proceed = WizardYesNoPage(msg, title="Confirmation")
......@@ -198,14 +204,14 @@ def wizard(session):
w.add_page(proceed)
if w.run():
extract_image(session)
create_image(session)
else:
return False
return True
def extract_image(session):
def create_image(session):
d = session['dialog']
disk = session['disk']
device = session['device']
......@@ -228,9 +234,7 @@ def extract_image(session):
#Shrink
size = device.shrink()
session['shrinked'] = True
getattr(__import__("image_creator.dialog_main",
fromlist=['image_creator']),
"update_background_title")(session)
update_background_title(session)
metadata.update(device.meta)
metadata['DESCRIPTION'] = wizard['ImageDescription']
......@@ -254,8 +258,8 @@ def extract_image(session):
pithos_file = ""
with open(snapshot, 'rb') as f:
pithos_file = kamaki.upload(f, size, name,
"(1/4) Calculating block hashes",
"(2/4) Uploading missing blocks")
"(1/4) Calculating block hashes",
"(2/4) Uploading missing blocks")
out.output("(3/4) Uploading metadata file...", False)
kamaki.upload(StringIO.StringIO(metastring), size=len(metastring),
......@@ -281,8 +285,6 @@ def extract_image(session):
msg = "The image was successfully uploaded and registered with " \
"~okeanos. Would you like to keep a local copy of the image?"
if not d.yesno(msg, width=PAGE_WIDTH):
getattr(__import__("image_creator.dialog_main",
fromlist=['image_creator']), "extract_image")(session)
extract_image(session)
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
......@@ -41,10 +41,10 @@ setup(
name='snf_image_creator',
version=image_creator.__version__,
description='Command line tool for creating images',
# long_description=open('README.rst').read(),
# long_description=open('README.rst').read(),
url='https://code.grnet.gr/projects/snf-image-creator',
license='BSD',
packages = find_packages(),
packages=find_packages(),
include_package_data=True,
install_requires=['pbs', 'ansicolors', 'progress', 'pysendfile'],
entry_points={
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment