pep8 fixes

Change-Id: Ieeed0824e754cb572c7430531900164e9478e120
This commit is contained in:
Matthew Mosesohn 2013-10-10 15:08:43 +04:00
parent 4352298986
commit 5048eec7d1
11 changed files with 168 additions and 161 deletions

View File

@ -21,4 +21,3 @@ def replaceInFile(filename, orig, new):
lines[lineno] = re.sub(orig, new, line)
with open(filename, 'w') as f:
f.write("".join(lines))

View File

@ -1,8 +1,10 @@
import time
class TimeoutError(Exception):
pass
def wait_for_true(check, args=[], kwargs={},
timeout=60, error_message='Timeout error'):
start_time = time.time()
@ -13,4 +15,3 @@ def wait_for_true(check, args=[], kwargs={},
if time.time() - start_time > timeout:
raise TimeoutError(error_message)
time.sleep(0.1)

View File

@ -26,7 +26,7 @@ def TextField(keyword, label, width, default_value=None, tooltip=None,
mask = None
if not tooltip:
edit_obj = urwid.Edit(('important', label.ljust(width)), default_value,
mask=mask)
mask=mask)
else:
edit_obj = TextWithTip(('important', label.ljust(width)),
default_value, tooltip, toolbar, mask=mask)
@ -90,6 +90,7 @@ class TextWithTip(urwid.Edit):
mask=mask)
self.tip = tooltip
self.toolbar = toolbar
def render(self, size, focus=False):
if focus:
self.toolbar.set_text(self.tip)

View File

@ -1 +0,0 @@
nameserver 8.8.8.8

View File

@ -26,6 +26,7 @@ import urwid.web_display
logging.basicConfig(filename='/var/log/fuelmenu.log', level=logging.DEBUG)
log = logging.getLogger('fuelmenu.loader')
class Loader(object):
def __init__(self, parent):
@ -55,7 +56,6 @@ class Loader(object):
clsobj = getattr(imported, module, None)
modobj = clsobj(self.parent)
# add the module to the list
if modobj.visible:
self.modlist.append(modobj)
@ -117,14 +117,15 @@ class FuelSetup(object):
self.childpage = child.screen
self.childfill = urwid.Filler(self.childpage, 'top', 40)
self.childbox = urwid.BoxAdapter(self.childfill, 40)
self.cols = urwid.Columns([
('fixed', 20, urwid.Pile([
urwid.AttrMap(self.menubox, 'bright'),
urwid.Divider(" ")])),
('weight', 3, urwid.Pile([
urwid.Divider(" "),
self.childbox,
urwid.Divider(" ")]))
self.cols = urwid.Columns(
[
('fixed', 20, urwid.Pile([
urwid.AttrMap(self.menubox, 'bright'),
urwid.Divider(" ")])),
('weight', 3, urwid.Pile([
urwid.Divider(" "),
self.childbox,
urwid.Divider(" ")]))
], 1)
child.refresh()
self.listwalker[:] = [self.cols]
@ -142,14 +143,15 @@ class FuelSetup(object):
self.childpage = urwid.ListBox(child.listwalker)
self.childfill = urwid.Filler(self.childpage, 'middle', 22)
self.childbox = urwid.BoxAdapter(self.childfill, 22)
self.cols = urwid.Columns([
('fixed', 20, urwid.Pile([
urwid.AttrMap(self.menubox, 'bright'),
urwid.Divider(" ")])),
('weight', 3, urwid.Pile([
urwid.Divider(" "),
self.childbox,
urwid.Divider(" ")]))
self.cols = urwid.Columns(
[
('fixed', 20, urwid.Pile([
urwid.AttrMap(self.menubox, 'bright'),
urwid.Divider(" ")])),
('weight', 3, urwid.Pile([
urwid.Divider(" "),
self.childbox,
urwid.Divider(" ")]))
], 1)
#Refresh top level listwalker
#self.listwalker[:] = [self.cols]
@ -158,8 +160,8 @@ class FuelSetup(object):
#Disable kernel print messages. They make our UI ugly
noout = open('/dev/null', 'w')
retcode = subprocess.call(["sysctl", "-w", "kernel.printk=4 1 1 7"],
stdout=noout,
stderr=noout)
stdout=noout,
stderr=noout)
text_header = (u"Fuel %s setup "
u"Use Up/Down/Left/Right to navigate. F8 exits."
@ -189,14 +191,15 @@ class FuelSetup(object):
self.childpage = child.screenUI()
self.childfill = urwid.Filler(self.childpage, 'top', 22)
self.childbox = urwid.BoxAdapter(self.childfill, 22)
self.cols = urwid.Columns([
('fixed', 20, urwid.Pile([
urwid.AttrMap(self.menubox, 'bright'),
urwid.Divider(" ")])),
('weight', 3, urwid.Pile([
urwid.Divider(" "),
self.childbox,
urwid.Divider(" ")]))
self.cols = urwid.Columns(
[
('fixed', 20, urwid.Pile([
urwid.AttrMap(self.menubox, 'bright'),
urwid.Divider(" ")])),
('weight', 3, urwid.Pile([
urwid.Divider(" "),
self.childbox,
urwid.Divider(" ")]))
], 1)
self.listwalker = urwid.SimpleListWalker([self.cols])
#self.listwalker = urwid.TreeWalker([self.cols])
@ -206,21 +209,22 @@ class FuelSetup(object):
self.frame = urwid.Frame(urwid.AttrWrap(self.listbox, 'body'),
header=self.header, footer=self.footer)
palette = [
('body', 'black', 'light gray', 'standout'),
('reverse', 'light gray', 'black'),
('header', 'white', 'dark red', 'bold'),
('important', 'dark blue', 'light gray',
('standout', 'underline')),
('editfc', 'white', 'dark blue', 'bold'),
('editbx', 'light gray', 'dark blue'),
('editcp', 'black', 'light gray', 'standout'),
('bright', 'dark gray', 'light gray', ('bold', 'standout')),
('buttn', 'black', 'dark cyan'),
('buttnf', 'white', 'dark blue', 'bold'),
('light gray', 'white', 'light gray', 'bold'),
('red', 'dark red', 'light gray', 'bold'),
('black', 'black', 'black', 'bold'),
palette = \
[
('body', 'black', 'light gray', 'standout'),
('reverse', 'light gray', 'black'),
('header', 'white', 'dark red', 'bold'),
('important', 'dark blue', 'light gray',
('standout', 'underline')),
('editfc', 'white', 'dark blue', 'bold'),
('editbx', 'light gray', 'dark blue'),
('editcp', 'black', 'light gray', 'standout'),
('bright', 'dark gray', 'light gray', ('bold', 'standout')),
('buttn', 'black', 'dark cyan'),
('buttnf', 'white', 'dark blue', 'bold'),
('light gray', 'white', 'light gray', 'bold'),
('red', 'dark red', 'light gray', 'bold'),
('black', 'black', 'black', 'bold'),
]
# use appropriate Screen class
@ -237,18 +241,16 @@ class FuelSetup(object):
unhandled_input=unhandled)
#Initialize each module completely before any events are handled
for child in reversed(self.choices):
self.setChildScreen(name=child)
self.setChildScreen(name=child)
self.mainloop.run()
def exit_program(self, button):
#return kernel logging to normal
noout = open('/dev/null', 'w')
retcode = subprocess.call(["sysctl", "-w", "kernel.printk=7 4 1 7"],
stdout=noout,
stderr=noout)
stdout=noout,
stderr=noout)
#Fix /etc/hosts and /etc/resolv.conf before quitting
dnsobj = self.children[int(self.choices.index("DNS & Hostname"))]
dnsobj.fixEtcHosts()
@ -258,14 +260,14 @@ class FuelSetup(object):
def global_save(self):
#Runs save function for every module
for module, modulename in zip(self.children,self.choices):
for module, modulename in zip(self.children, self.choices):
if not module.visible:
continue
else:
try:
log.info("Checking and applying module: %s"
% modulename)
self.footer.set_text("Checking and applying module: %s"
log.info("Checking and applying module: %s"
% modulename)
self.footer.set_text("Checking and applying module: %s"
% modulename)
self.refreshScreen()
@ -275,7 +277,7 @@ class FuelSetup(object):
return False, modulename
except AttributeError as e:
log.debug("Module %s does not have save function: %s"
% (modulename, e))
% (modulename, e))
return True, None
@ -286,20 +288,22 @@ def setup():
return
fm = FuelSetup()
def save_only(iface):
import common.network as network
from common import nailyfactersettings
from settings import Settings
import netifaces
#Naily.facts translation map from astute.yaml format
facter_translate = {
"ADMIN_NETWORK/interface": "internal_interface",
"ADMIN_NETWORK/ipaddress": "internal_ipaddress",
"ADMIN_NETWORK/netmask": "internal_netmask",
"ADMIN_NETWORK/dhcp_pool_start": "dhcp_pool_start",
"ADMIN_NETWORK/dhcp_pool_end": "dhcp_pool_end",
"ADMIN_NETWORK/static_pool_start": "static_pool_start",
"ADMIN_NETWORK/static_pool_end": "static_pool_end",
facter_translate = \
{
"ADMIN_NETWORK/interface": "internal_interface",
"ADMIN_NETWORK/ipaddress": "internal_ipaddress",
"ADMIN_NETWORK/netmask": "internal_netmask",
"ADMIN_NETWORK/dhcp_pool_start": "dhcp_pool_start",
"ADMIN_NETWORK/dhcp_pool_end": "dhcp_pool_end",
"ADMIN_NETWORK/static_pool_start": "static_pool_start",
"ADMIN_NETWORK/static_pool_end": "static_pool_end",
}
#Calculate and set Static/DHCP pool fields
#Max IPs = net size - 2 (master node + bcast)
@ -321,18 +325,19 @@ def save_only(iface):
dynamic_start = str(dhcp_pool[0])
dynamic_end = str(dhcp_pool[-1])
except:
print "Unable to define DHCP pools"
print "Unable to define DHCP pools"
sys.exit(1)
settings={
"ADMIN_NETWORK/interface": iface,
"ADMIN_NETWORK/ipaddress": ip,
"ADMIN_NETWORK/netmask": netmask,
"ADMIN_NETWORK/dhcp_pool_start": dynamic_start,
"ADMIN_NETWORK/dhcp_pool_end": dynamic_end,
"ADMIN_NETWORK/static_pool_start": static_start,
"ADMIN_NETWORK/static_pool_end": static_end,
settings = \
{
"ADMIN_NETWORK/interface": iface,
"ADMIN_NETWORK/ipaddress": ip,
"ADMIN_NETWORK/netmask": netmask,
"ADMIN_NETWORK/dhcp_pool_start": dynamic_start,
"ADMIN_NETWORK/dhcp_pool_end": dynamic_end,
"ADMIN_NETWORK/static_pool_start": static_start,
"ADMIN_NETWORK/static_pool_end": static_end,
}
newsettings=dict()
newsettings = dict()
for setting in settings.keys():
if "/" in setting:
part1, part2 = setting.split("/")
@ -351,13 +356,15 @@ def save_only(iface):
n = nailyfactersettings.NailyFacterSettings()
n.write(factsettings)
def main(*args, **kwargs):
if urwid.VERSION < (1, 1, 0):
print "This program requires urwid 1.1.0 or greater."
parser = OptionParser()
parser.add_option("-s", "--save-only", dest="save_only",
action="store_true", help="Save default values and exit.")
parser.add_option("-s", "--save-only", dest="save_only",
action="store_true",
help="Save default values and exit.")
parser.add_option("-i", "--iface", dest="iface", metavar="IFACE",
default="eth0", help="Set IFACE as primary.")

View File

@ -23,7 +23,8 @@ import copy
import socket
import struct
import netaddr
import dhcp_checker.api, dhcp_checker.utils
import dhcp_checker.api
import dhcp_checker.utils
import netifaces
import subprocess
from fuelmenu.settings import *
@ -141,13 +142,13 @@ Please wait...")
# 'gateway': '0.0.0.0'}]
try:
with dhcp_checker.utils.IfaceState(self.activeiface) as iface:
dhcptimeout=5
dhcptimeout = 5
dhcp_server_data = timeout.wait_for_true(
dhcp_checker.api.check_dhcp_on_eth,
[iface, dhcptimeout], timeout=dhcptimeout)
except timeout.TimeoutError:
log.debug("DHCP scan timed out")
dhcp_server_data=[]
dhcp_server_data = []
num_dhcp = len(dhcp_server_data)
if num_dhcp == 0:
@ -186,9 +187,8 @@ interface first.")
else:
#Ensure ADMIN_NETWORK/interface is not running DHCP
if self.netsettings[responses[
"ADMIN_NETWORK/interface"]]["bootproto"]\
== "dhcp":
errors.append("%s is running DHCP.Change it to static "
"ADMIN_NETWORK/interface"]]["bootproto"] == "dhcp":
errors.append("%s is running DHCP.Change it to static "
"first." % self.activeiface)
#Ensure Static Pool Start and Static Pool are valid IPs
@ -215,8 +215,8 @@ interface first.")
responses["ADMIN_NETWORK/static_pool_end"])
#Ensure DHCP Pool Start and DHCP Pool are valid IPs
try:
if netaddr.valid_ipv4(
responses["ADMIN_NETWORK/dhcp_pool_start"]):
if netaddr.valid_ipv4(responses[
"ADMIN_NETWORK/dhcp_pool_start"]):
dhcp_start = netaddr.IPAddress(
responses["ADMIN_NETWORK/dhcp_pool_start"])
else:
@ -236,7 +236,8 @@ interface first.")
% responses["ADMIN_NETWORK/dhcp_pool_end"])
#Ensure pool start and end are in the same subnet of each other
netmask = self.netsettings[responses["ADMIN_NETWORK/interface"
netmask = self.netsettings[responses[
"ADMIN_NETWORK/interface"
]]["netmask"]
if not network.inSameSubnet(
responses["ADMIN_NETWORK/dhcp_pool_start"],
@ -281,16 +282,17 @@ interface first.")
return True
def updateCobbler(self, params):
patterns = {
'cblr_server': '^server: .*',
'cblr_next_server': '^next_server: .*',
'mgmt_if': '^interface=.*',
'domain': '^domain=.*',
'server': '^server=.*',
'dhcp-range': '^dhcp-range=',
'dhcp-option': '^dhcp-option=',
'pxe-service': '^pxe-service=(^,)',
'dhcp-boot': '^dhcp-boot=([^,],{3}),'
patterns = \
{
'cblr_server': '^server: .*',
'cblr_next_server': '^next_server: .*',
'mgmt_if': '^interface=.*',
'domain': '^domain=.*',
'server': '^server=.*',
'dhcp-range': '^dhcp-range=',
'dhcp-option': '^dhcp-option=',
'pxe-service': '^pxe-service=(^,)',
'dhcp-boot': '^dhcp-boot=([^,],{3}),'
}
def cancel(self, button):

View File

@ -38,25 +38,26 @@ blank = urwid.Divider()
fields = ["HOSTNAME", "DNS_DOMAIN", "DNS_SEARCH", "DNS_UPSTREAM", "blank",
"TEST_DNS"]
DEFAULTS = {
"HOSTNAME": {"label": "Hostname",
"tooltip": "Hostname to use for Fuel master node",
"value": socket.gethostname().split('.')[0]},
"DNS_UPSTREAM": {"label": "External DNS",
"tooltip": "DNS server(s) (comma separated) to handle DNS\
requests (example 8.8.8.8)",
"value": "8.8.8.8"},
"DNS_DOMAIN": {"label": "Domain",
"tooltip": "Domain suffix to user for all nodes in your\
DEFAULTS = \
{
"HOSTNAME": {"label": "Hostname",
"tooltip": "Hostname to use for Fuel master node",
"value": socket.gethostname().split('.')[0]},
"DNS_UPSTREAM": {"label": "External DNS",
"tooltip": "DNS server(s) (comma separated) to handle\
DNS requests (example 8.8.8.8)",
"value": "8.8.8.8"},
"DNS_DOMAIN": {"label": "Domain",
"tooltip": "Domain suffix to user for all nodes in your\
cluster",
"value": "domain.tld"},
"DNS_SEARCH": {"label": "Search Domain",
"tooltip": "Domains to search when looking up DNS\
(space separated)",
"value": "domain.tld"},
"TEST_DNS": {"label": "Hostname to test DNS:",
"value": "www.google.com",
"tooltip": "DNS record to resolve to see if DNS is\
"value": "domain.tld"},
"DNS_SEARCH": {"label": "Search Domain",
"tooltip": "Domains to search when looking up DNS\
(space separated)",
"value": "domain.tld"},
"TEST_DNS": {"label": "Hostname to test DNS:",
"value": "www.google.com",
"tooltip": "DNS record to resolve to see if DNS is\
accessible"}
}
@ -277,6 +278,7 @@ class dnsandhostname(urwid.WidgetWrap):
# 'pxe-service' : '^pxe-service=(^,)',
# 'dhcp-boot' : '^dhcp-boot=([^,],{3}),'
# }
def cancel(self, button):
for index, fieldname in enumerate(fields):
if fieldname == "blank":
@ -324,7 +326,7 @@ class dnsandhostname(urwid.WidgetWrap):
## Generic settings end ##
#log.debug(str(newsettings))
Settings().write(newsettings,
Settings().write(newsettings,
defaultsfile=self.parent.defaultsettingsfile,
outfn=self.parent.settingsfile)
#Write naily.facts
@ -497,4 +499,3 @@ class dnsandhostname(urwid.WidgetWrap):
self.listwalker = urwid.SimpleListWalker(self.listbox_content)
screen = urwid.ListBox(self.listwalker)
return screen

View File

@ -36,29 +36,31 @@ blank = urwid.Divider()
fields = ["blank", "ifname", "onboot", "bootproto", "ipaddr", "netmask",
"gateway"]
DEFAULTS = {
"ifname": {"label": "Interface name:",
"tooltip": "Interface system identifier",
"value": "locked"},
"onboot": {"label": "Enabled on boot:",
"tooltip": "",
"value": "radio"},
"bootproto": {"label": "Configuration via DHCP:",
"tooltip": "",
"value": "radio",
"choices": ["DHCP", "Static"]},
"ipaddr": {"label": "IP address:",
"tooltip": "Manual IP address (example 192.168.1.2)",
"value": ""},
"netmask": {"label": "Netmask:",
"tooltip": "Manual netmask (example 255.255.255.0)",
"value": "255.255.255.0"},
"gateway": {"label": "Default Gateway:",
"tooltip": "Manual gateway to access Internet (example "
"192.168.1.1)",
"value": ""},
DEFAULTS = \
{
"ifname": {"label": "Interface name:",
"tooltip": "Interface system identifier",
"value": "locked"},
"onboot": {"label": "Enabled on boot:",
"tooltip": "",
"value": "radio"},
"bootproto": {"label": "Configuration via DHCP:",
"tooltip": "",
"value": "radio",
"choices": ["DHCP", "Static"]},
"ipaddr": {"label": "IP address:",
"tooltip": "Manual IP address (example 192.168.1.2)",
"value": ""},
"netmask": {"label": "Netmask:",
"tooltip": "Manual netmask (example 255.255.255.0)",
"value": "255.255.255.0"},
"gateway": {"label": "Default Gateway:",
"tooltip": "Manual gateway to access Internet (example "
"192.168.1.1)",
"value": ""},
}
class interfaces(urwid.WidgetWrap):
def __init__(self, parent):
self.name = "Network Setup"
@ -145,12 +147,12 @@ class interfaces(urwid.WidgetWrap):
self.parent.refreshScreen()
try:
with dhcp_checker.utils.IfaceState(self.activeiface) as iface:
dhcptimeout=5
dhcptimeout = 5
dhcp_server_data = timeout.wait_for_true(
dhcp_checker.api.check_dhcp_on_eth,
[iface, dhcptimeout], timeout=dhcptimeout)
except timeout.TimeoutError:
self.log.info("DHCP scan timed out")
self.log.info("DHCP scan timed out")
dhcp_server_data = []
except Exception:
self.log.warning("dhcp_checker failed to check on %s"
@ -158,10 +160,9 @@ class interfaces(urwid.WidgetWrap):
dhcp_server_data = []
responses["dhcp_nowait"] = False
if len(dhcp_server_data) < 1:
self.log.debug("No DHCP servers found. Warning user about "
"dhcp_nowait.")
"dhcp_nowait.")
#Build dialog elements
dhcp_info = []
dhcp_info.append(urwid.Padding(

View File

@ -30,13 +30,14 @@ blank = urwid.Divider()
fields = ["PASSWORD", "CONFIRM_PASSWORD"]
DEFAULTS = {
"PASSWORD": {"label": "Enter password",
"tooltip": "Use ASCII characters only",
"value": ""},
"CONFIRM_PASSWORD": {"label": "Confirm password",
"tooltip": "Use ASCII characters only",
"value": ""},
DEFAULTS = \
{
"PASSWORD": {"label": "Enter password",
"tooltip": "Use ASCII characters only",
"value": ""},
"CONFIRM_PASSWORD": {"label": "Confirm password",
"tooltip": "Use ASCII characters only",
"value": ""},
}
@ -107,7 +108,7 @@ class rootpw(urwid.WidgetWrap):
noout = open('/dev/null', 'w')
noop = subprocess.call(["rm", "-f", "/etc/passwd.lock",
"/etc/shadow.lock"], stdout=noout,
stderr=noout)
stderr=noout)
retcode = subprocess.call(["usermod", "-p", hashed, "root"],
stdout=noout,
stderr=noout)
@ -134,7 +135,6 @@ class rootpw(urwid.WidgetWrap):
else:
self.edits[index].set_edit_text(DEFAULTS[fieldname]['value'])
def refresh(self):
pass
@ -178,9 +178,7 @@ class rootpw(urwid.WidgetWrap):
self.listbox_content.append(blank)
self.listbox_content.append(check_col)
#Add everything into a ListBox and return it
self.listwalker = urwid.SimpleListWalker(self.listbox_content)
screen = urwid.ListBox(self.listwalker)
return screen

View File

@ -31,7 +31,6 @@ class saveandquit():
self.parent = parent
self.screen = None
def save_and_continue(self, args):
self.save()
@ -44,15 +43,15 @@ class saveandquit():
def save(self):
results, modulename = self.parent.global_save()
if results:
self.parent.footer.set_text("All changes saved successfully!")
return True
self.parent.footer.set_text("All changes saved successfully!")
return True
else:
#show pop up with more details
msg = "ERROR: Module %s failed to save. Go back" % (modulename)\
+ " and fix any mistakes or choose Quit without Saving."
diag = dialog.display_dialog(self, TextLabel(msg),
"Error saving changes!")
return False
#show pop up with more details
msg = "ERROR: Module %s failed to save. Go back" % (modulename)\
+ " and fix any mistakes or choose Quit without Saving."
diag = dialog.display_dialog(self, TextLabel(msg),
"Error saving changes!")
return False
def quit_without_saving(self, args):
self.parent.exit_program(None)

View File

@ -52,4 +52,3 @@ setuptools.setup(
],
},
)