Commit e687ec01 authored by Michael Hanselmann's avatar Michael Hanselmann
Browse files

PEP8 style fixes



Identified using the “pep8” utility.
Signed-off-by: default avatarMichael Hanselmann <hansmi@google.com>
Reviewed-by: default avatarIustin Pop <iustin@google.com>
parent b7bf8b58
......@@ -128,7 +128,7 @@ class StatusFile:
@param port: TCP/UDP port
"""
assert isinstance(port, (int, long)) and 0 < port < 2**16
assert isinstance(port, (int, long)) and 0 < port < (2 ** 16)
self._data.listen_port = port
def GetListenPort(self):
......
......@@ -34,6 +34,7 @@ except ImportError:
from ganeti import daemon
from ganeti import errors
# We contributed the AsyncNotifier class back to python-pyinotify, and it's
# part of their codebase since version 0.8.7. This code can be removed once
# we'll be ready to depend on python-pyinotify >= 0.8.7
......
......@@ -730,7 +730,7 @@ def GetVolumeList(vg_names):
# we don't want to report such volumes as existing, since they
# don't really hold data
continue
lvs[vg_name+"/"+name] = (size, inactive, online)
lvs[vg_name + "/" + name] = (size, inactive, online)
return lvs
......@@ -2359,7 +2359,7 @@ def FinalizeExport(instance, snap_disks):
config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
"%s" % nic.nicparams.get(param, None))
# TODO: redundant: on load can read nics until it doesn't exist
config.set(constants.INISECT_INS, "nic_count" , "%d" % nic_total)
config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
disk_total = 0
for disk_count, disk in enumerate(snap_disks):
......@@ -2372,7 +2372,7 @@ def FinalizeExport(instance, snap_disks):
config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
("%d" % disk.size))
config.set(constants.INISECT_INS, "disk_count" , "%d" % disk_total)
config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
# New-style hypervisor/backend parameters
......@@ -3378,7 +3378,6 @@ class HooksRunner(object):
else:
_Fail("Unknown hooks phase '%s'", phase)
subdir = "%s-%s.d" % (hpath, suffix)
dir_name = utils.PathJoin(self._BASE_DIR, subdir)
......
......@@ -321,7 +321,6 @@ class BlockDev(object):
is_degraded=is_degraded,
ldisk_status=ldisk_status)
def SetInfo(self, text):
"""Update metadata with info text.
......@@ -408,12 +407,12 @@ class LogicalVolume(BlockDev):
pvs_info.sort()
pvs_info.reverse()
pvlist = [ pv[1] for pv in pvs_info ]
pvlist = [pv[1] for pv in pvs_info]
if compat.any(":" in v for v in pvlist):
_ThrowError("Some of your PVs have the invalid character ':' in their"
" name, this is not supported - please filter them out"
" in lvm.conf using either 'filter' or 'preferred_names'")
free_size = sum([ pv[0] for pv in pvs_info ])
free_size = sum([pv[0] for pv in pvs_info])
current_pvs = len(pvlist)
stripes = min(current_pvs, constants.LVM_STRIPECOUNT)
......@@ -1113,7 +1112,7 @@ class DRBD8(BaseDRBD):
super(DRBD8, self).__init__(unique_id, children, size)
self.major = self._DRBD_MAJOR
version = self._GetVersion(self._GetProcData())
if version["k_major"] != 8 :
if version["k_major"] != 8:
_ThrowError("Mismatch in DRBD kernel version and requested ganeti"
" usage: kernel is %s.%s, ganeti wants 8.x",
version["k_major"], version["k_minor"])
......@@ -1194,7 +1193,7 @@ class DRBD8(BaseDRBD):
# this also converts the value to an int
number = pyp.Word(pyp.nums).setParseAction(lambda s, l, t: int(t[0]))
comment = pyp.Literal ("#") + pyp.Optional(pyp.restOfLine)
comment = pyp.Literal("#") + pyp.Optional(pyp.restOfLine)
defa = pyp.Literal("_is_default").suppress()
dbl_quote = pyp.Literal('"').suppress()
......
......@@ -270,7 +270,6 @@ def InitCluster(cluster_name, mac_prefix, # pylint: disable-msg=R0913
" entries: %s" % invalid_hvs,
errors.ECODE_INVAL)
ipcls = None
if primary_ip_version == constants.IP4_VERSION:
ipcls = netutils.IP4Address
......@@ -661,6 +660,7 @@ def MasterFailover(no_voting=False):
master_ip = sstore.GetMasterIP()
total_timeout = 30
# Here we have a phase where no master should be running
def _check_ip():
if netutils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
......
......@@ -728,9 +728,9 @@ BACKEND_OPT = cli_option("-B", "--backend-parameters", dest="beparams",
type="keyval", default={},
help="Backend parameters")
HVOPTS_OPT = cli_option("-H", "--hypervisor-parameters", type="keyval",
default={}, dest="hvparams",
help="Hypervisor parameters")
HVOPTS_OPT = cli_option("-H", "--hypervisor-parameters", type="keyval",
default={}, dest="hvparams",
help="Hypervisor parameters")
HYPERVISOR_OPT = cli_option("-H", "--hypervisor-parameters", dest="hypervisor",
help="Hypervisor and hypervisor options, in the"
......@@ -2815,7 +2815,7 @@ def FormatTimestamp(ts):
@return: a string with the formatted timestamp
"""
if not isinstance (ts, (tuple, list)) or len(ts) != 2:
if not isinstance(ts, (tuple, list)) or len(ts) != 2:
return "?"
sec, usec = ts
return time.strftime("%F %T", time.localtime(sec)) + ".%06d" % usec
......
......@@ -113,9 +113,9 @@ def GenericOpCodes(opts, args):
t3 = time.time()
ToStdout("C:op %4d" % op_cnt)
ToStdout("C:job %4d" % job_cnt)
ToStdout("T:submit %4.4f" % (t2-t1))
ToStdout("T:exec %4.4f" % (t3-t2))
ToStdout("T:total %4.4f" % (t3-t1))
ToStdout("T:submit %4.4f" % (t2 - t1))
ToStdout("T:exec %4.4f" % (t3 - t2))
ToStdout("T:total %4.4f" % (t3 - t1))
return 0
......@@ -689,5 +689,6 @@ aliases = {
"allocator": "iallocator",
}
def Main():
return GenericMain(commands, aliases=aliases)
......@@ -1119,13 +1119,13 @@ def _FormatList(buf, data, indent_level):
if isinstance(elem, tuple)] or [0])
for elem in data:
if isinstance(elem, basestring):
buf.write("%*s%s\n" % (2*indent_level, "", elem))
buf.write("%*s%s\n" % (2 * indent_level, "", elem))
elif isinstance(elem, tuple):
key, value = elem
spacer = "%*s" % (max_tlen - len(key), "")
buf.write("%*s%s:%s %s\n" % (2*indent_level, "", key, spacer, value))
buf.write("%*s%s:%s %s\n" % (2 * indent_level, "", key, spacer, value))
elif isinstance(elem, list):
_FormatList(buf, elem, indent_level+1)
_FormatList(buf, elem, indent_level + 1)
def ShowInstanceConfig(opts, args):
......@@ -1179,7 +1179,7 @@ def ShowInstanceConfig(opts, args):
buf.write(" Operating system: %s\n" % instance["os"])
FormatParameterDict(buf, instance["os_instance"], instance["os_actual"],
level=2)
if instance.has_key("network_port"):
if "network_port" in instance:
buf.write(" Allocated network port: %s\n" %
compat.TryToRoman(instance["network_port"],
convert=opts.roman_integers))
......
......@@ -4085,6 +4085,7 @@ class LUOobCommand(NoHooksLU):
raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
utils.CommaJoin(errs))
class _OsQuery(_QueryBase):
FIELDS = query.OS_FIELDS
......@@ -7950,7 +7951,7 @@ def _ComputeDiskSizePerVG(disk_template, disks):
if disk_template not in req_size_dict:
raise errors.ProgrammerError("Disk template '%s' size requirement"
" is unknown" % disk_template)
" is unknown" % disk_template)
return req_size_dict[disk_template]
......@@ -7972,7 +7973,7 @@ def _ComputeDiskSize(disk_template, disks):
if disk_template not in req_size_dict:
raise errors.ProgrammerError("Disk template '%s' size requirement"
" is unknown" % disk_template)
" is unknown" % disk_template)
return req_size_dict[disk_template]
......@@ -8886,7 +8887,7 @@ class LUInstanceCreate(LogicalUnit):
# 'fake' LV disks with the old data, plus the new unique_id
tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
rename_to = []
for t_dsk, a_dsk in zip (tmp_disks, self.disks):
for t_dsk, a_dsk in zip(tmp_disks, self.disks):
rename_to.append(t_dsk.logical_id)
t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
self.cfg.SetDiskID(t_dsk, pnode_name)
......@@ -10826,7 +10827,7 @@ class LUInstanceSetParams(LogicalUnit):
if msg:
# Assume the primary node is unreachable and go ahead
self.warn.append("Can't get info from primary node %s: %s" %
(pnode, msg))
(pnode, msg))
elif not isinstance(pninfo.payload.get("memory_free", None), int):
self.warn.append("Node data from primary node %s doesn't contain"
" free memory information" % pnode)
......@@ -12143,7 +12144,6 @@ class LUGroupSetParams(LogicalUnit):
return result
class LUGroupRemove(LogicalUnit):
HPATH = "group-remove"
HTYPE = constants.HTYPE_GROUP
......
......@@ -67,6 +67,7 @@ def _all(seq):
return False
return True
def _any(seq):
"""Returns True if any element of the iterable are True.
......@@ -75,6 +76,7 @@ def _any(seq):
return True
return False
try:
# pylint: disable-msg=E0601
# pylint: disable-msg=W0622
......@@ -89,6 +91,7 @@ try:
except NameError:
any = _any
def partition(seq, pred=bool): # pylint: disable-msg=W0622
"""Partition a list in two, based on the given predicate.
......
......@@ -50,4 +50,3 @@ def UnpackMagic(payload):
raise errors.ConfdMagicError("UDP payload contains an unkown fourcc")
return payload[_FOURCC_LEN:]
......@@ -333,7 +333,7 @@ class ConfdClient:
elif peer_cnt < 5:
return peer_cnt - 1
else:
return int(peer_cnt/2) + 1
return int(peer_cnt / 2) + 1
def WaitForReply(self, salt, timeout=constants.CONFD_CLIENT_EXPIRE_TIMEOUT):
"""Wait for replies to a given request.
......
......@@ -539,7 +539,6 @@ class ConfigWriter:
cluster.SimpleFillND(nodegroup.ndparams),
constants.NDS_PARAMETER_TYPES)
# drbd minors check
_, duplicates = self._UnlockedComputeDRBDMap()
for node, minor, instance_a, instance_b in duplicates:
......
......@@ -102,7 +102,7 @@ NODED_GROUP = _autoconf.NODED_GROUP
# Wipe
DD_CMD = "dd"
WIPE_BLOCK_SIZE = 1024**2
WIPE_BLOCK_SIZE = 1024 ** 2
MAX_WIPE_CHUNK = 1024 # 1GB
MIN_WIPE_CHUNK_PERCENT = 10
......@@ -125,7 +125,11 @@ IMPORT_EXPORT_DIR_MODE = 0755
ADOPTABLE_BLOCKDEV_ROOT = "/dev/disk/"
# keep RUN_GANETI_DIR first here, to make sure all get created when the node
# daemon is started (this takes care of RUN_DIR being tmpfs)
SUB_RUN_DIRS = [ RUN_GANETI_DIR, BDEV_CACHE_DIR, DISK_LINKS_DIR ]
SUB_RUN_DIRS = [
RUN_GANETI_DIR,
BDEV_CACHE_DIR,
DISK_LINKS_DIR,
]
LOCK_DIR = _autoconf.LOCALSTATEDIR + "/lock"
SSCONF_LOCK_FILE = LOCK_DIR + "/ganeti-ssconf.lock"
# User-id pool lock directory
......@@ -1209,7 +1213,7 @@ RS_ALL = frozenset([
#: Dictionary with special field cases and their verbose/terse formatting
RSS_DESCRIPTION = {
RS_UNKNOWN: ("(unknown)", "??"),
RS_NODATA: ("(nodata)", "?"),
RS_NODATA: ("(nodata)", "?"),
RS_OFFLINE: ("(offline)", "*"),
RS_UNAVAIL: ("(unavail)", "-"),
}
......@@ -1440,7 +1444,7 @@ MAX_UDP_DATA_SIZE = 61440
# User-id pool minimum/maximum acceptable user-ids.
UIDPOOL_UID_MIN = 0
UIDPOOL_UID_MAX = 2**32-1 # Assuming 32 bit user-ids
UIDPOOL_UID_MAX = 2 ** 32 - 1 # Assuming 32 bit user-ids
# Name or path of the pgrep command
PGREP = "pgrep"
......
......@@ -482,4 +482,4 @@ def MaybeRaise(result):
error = GetEncodedError(result)
if error:
(errcls, args) = error
raise errcls, args
raise errcls(args)
......@@ -319,7 +319,7 @@ class HttpClientPool:
"""
try:
pclient = self._pool.pop(identity)
pclient = self._pool.pop(identity)
except KeyError:
# Need to create new client
client = self._GetHttpClientCreator()(self._curl_config_fn)
......
......@@ -386,11 +386,11 @@ class BaseHypervisor(object):
key = splitfields[0].strip()
val = splitfields[1].strip()
if key == "MemTotal":
result["memory_total"] = int(val.split()[0])/1024
result["memory_total"] = int(val.split()[0]) / 1024
elif key in ("MemFree", "Buffers", "Cached"):
sum_free += int(val.split()[0])/1024
sum_free += int(val.split()[0]) / 1024
elif key == "Active":
result["memory_dom0"] = int(val.split()[0])/1024
result["memory_dom0"] = int(val.split()[0]) / 1024
except (ValueError, TypeError), err:
raise errors.HypervisorError("Failed to compute memory usage: %s" %
(err,))
......
......@@ -267,7 +267,7 @@ class KVMHypervisor(hv_base.BaseHypervisor):
arg_list = cmdline.split("\x00")
while arg_list:
arg = arg_list.pop(0)
arg = arg_list.pop(0)
if arg == "-name":
instance = arg_list.pop(0)
elif arg == "-m":
......@@ -526,7 +526,7 @@ class KVMHypervisor(hv_base.BaseHypervisor):
"""
_, v_major, v_min, _ = self._GetKVMVersion()
pidfile = self._InstancePidFile(instance.name)
pidfile = self._InstancePidFile(instance.name)
kvm = constants.KVM_PATH
kvm_cmd = [kvm]
# used just by the vnc server, if enabled
......
......@@ -163,7 +163,7 @@ class XenHypervisor(hv_base.BaseHypervisor):
@return: tuple (name, id, memory, vcpus, stat, times)
"""
xm_list = self._GetXMList(instance_name=="Domain-0")
xm_list = self._GetXMList(instance_name == "Domain-0")
result = None
for data in xm_list:
if data[0] == instance_name:
......
......@@ -58,7 +58,7 @@ _IP_FAMILY_RE = re.compile(r"(?P<family>inet6?)\s+(?P<ip>%s)/" % _IP_RE_TEXT,
# Dict used to convert from a string representing an IP family to an IP
# version
_NAME_TO_IP_VER = {
_NAME_TO_IP_VER = {
"inet": constants.IP4_VERSION,
"inet6": constants.IP6_VERSION,
}
......@@ -417,9 +417,9 @@ class IPAddress(object):
assert 0 <= prefix <= cls.iplen
target_int = cls._GetIPIntFromString(subnet[0])
# Convert prefix netmask to integer value of netmask
netmask_int = (2**cls.iplen)-1 ^ ((2**cls.iplen)-1 >> prefix)
netmask_int = (2 ** cls.iplen) - 1 ^ ((2 ** cls.iplen) - 1 >> prefix)
# Calculate hostmask
hostmask_int = netmask_int ^ (2**cls.iplen)-1
hostmask_int = netmask_int ^ (2 ** cls.iplen) - 1
# Calculate network address by and'ing netmask
network_int = target_int & netmask_int
# Calculate broadcast address by or'ing hostmask
......
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