more changes to support a common usage of double quotes

This commit is contained in:
Blake J. Harnden 2017-08-04 14:51:25 -07:00
parent 2281051edf
commit 76bec9950d
7 changed files with 75 additions and 76 deletions

View file

@ -259,28 +259,28 @@ def example():
def repeat(interval, count):
count -= 1
msg('repeat: interval: %s; remaining: %s' % (interval, count))
msg("repeat: interval: %s; remaining: %s" % (interval, count))
if count > 0:
loop.add_event(interval, repeat, interval, count)
def sleep(delay):
msg('sleep %s' % delay)
msg("sleep %s" % delay)
time.sleep(delay)
msg('sleep done')
msg("sleep done")
def stop(arg):
msg(arg)
loop.stop()
loop.add_event(0, msg, 'start')
loop.add_event(0, msg, 'time zero')
loop.add_event(0, msg, "start")
loop.add_event(0, msg, "time zero")
for delay in 5, 4, 10, -1, 0, 9, 3, 7, 3.14:
loop.add_event(delay, msg, 'time %s' % delay)
loop.add_event(delay, msg, "time %s" % delay)
loop.run()
loop.add_event(0, repeat, 1, 5)
loop.add_event(12, sleep, 10)
loop.add_event(15.75, stop, 'stop time: 15.75')
loop.add_event(15.75, stop, "stop time: 15.75")

View file

@ -45,7 +45,7 @@ class MacAddress(object):
"""
if not self.addr:
return IpAddress.from_string("::")
tmp = struct.unpack("!Q", '\x00\x00' + self.addr)[0]
tmp = struct.unpack("!Q", "\x00\x00" + self.addr)[0]
nic = long(tmp) & 0x000000FFFFFFL
oui = long(tmp) & 0xFFFFFF000000L
# toggle U/L bit
@ -203,7 +203,7 @@ class IpAddress(object):
:rtype: int
"""
bin = socket.inet_pton(AF_INET, s)
return struct.unpack('!I', bin)[0]
return struct.unpack("!I", bin)[0]
class IpPrefix(object):
@ -221,14 +221,14 @@ class IpPrefix(object):
# prefixstr format: address/prefixlen
tmp = prefixstr.split("/")
if len(tmp) > 2:
raise ValueError("invalid prefix: '%s'" % prefixstr)
raise ValueError("invalid prefix: %s" % prefixstr)
self.af = af
if self.af == AF_INET:
self.addrlen = 32
elif self.af == AF_INET6:
self.addrlen = 128
else:
raise ValueError("invalid address family: '%s'" % self.af)
raise ValueError("invalid address family: %s" % self.af)
if len(tmp) == 2:
self.prefixlen = int(tmp[1])
else:

View file

@ -79,16 +79,15 @@ class CtrlNet(LxBrNet):
addr = self.prefix.addr(self.hostid)
else:
addr = self.prefix.max_addr()
msg = "Added control network bridge: %s %s" % \
(self.brname, self.prefix)
msg = "Added control network bridge: %s %s" % (self.brname, self.prefix)
addrlist = ["%s/%s" % (addr, self.prefix.prefixlen)]
if self.assign_address:
self.addrconfig(addrlist=addrlist)
msg += " address %s" % addr
logger.info(msg)
if self.updown_script is not None:
logger.info("interface %s updown script '%s startup' called" % \
(self.brname, self.updown_script))
logger.info("interface %s updown script (%s startup) called",
self.brname, self.updown_script)
subprocess.check_call([self.updown_script, self.brname, "startup"])
if self.serverintf is not None:
try:
@ -106,16 +105,16 @@ class CtrlNet(LxBrNet):
:return: True if an old bridge was detected, False otherwise
:rtype: bool
"""
retstat, retstr = utils.cmdresult([constants.BRCTL_BIN, 'show'])
retstat, retstr = utils.cmdresult([constants.BRCTL_BIN, "show"])
if retstat != 0:
logger.error("Unable to retrieve list of installed bridges")
lines = retstr.split('\n')
lines = retstr.split("\n")
for line in lines[1:]:
cols = line.split('\t')
cols = line.split("\t")
oldbr = cols[0]
flds = cols[0].split('.')
flds = cols[0].split(".")
if len(flds) == 3:
if flds[0] == 'b' and flds[1] == self.objid:
if flds[0] == "b" and flds[1] == self.objid:
logger.error(
"Error: An active control net bridge (%s) found. " \
"An older session might still be running. " \
@ -127,7 +126,7 @@ class CtrlNet(LxBrNet):
# Do this if we want to delete the old bridge
logger.warn("Warning: Old %s bridge found: %s" % (self.objid, oldbr))
try:
check_call([BRCTL_BIN, 'delbr', oldbr])
check_call([BRCTL_BIN, "delbr", oldbr])
except subprocess.CalledProcessError as e:
logger.exception("Error deleting old bridge %s", oldbr, e)
logger.info("Deleted %s", oldbr)
@ -148,7 +147,7 @@ class CtrlNet(LxBrNet):
self.serverintf, self.brname)
if self.updown_script is not None:
logger.info("interface %s updown script '%s shutdown' called" % (self.brname, self.updown_script))
logger.info("interface %s updown script (%s shutdown) called" % (self.brname, self.updown_script))
subprocess.check_call([self.updown_script, self.brname, "shutdown"])
LxBrNet.shutdown(self)
@ -221,7 +220,7 @@ class PtpNet(LxBrNet):
interface1_ip6 = None
interface1_ip6_mask = None
for address in if1.addrlist:
ip, sep, mask = address.partition('/')
ip, sep, mask = address.partition("/")
mask = int(mask)
if ipaddress.is_ipv4_address(ip):
family = AF_INET
@ -239,7 +238,7 @@ class PtpNet(LxBrNet):
interface2_ip6 = None
interface2_ip6_mask = None
for address in if2.addrlist:
ip, sep, mask = address.partition('/')
ip, sep, mask = address.partition("/")
mask = int(mask)
if ipaddress.is_ipv4_address(ip):
family = AF_INET
@ -253,7 +252,7 @@ class PtpNet(LxBrNet):
interface2_ip6_mask = mask
# TODO: not currently used
# loss=netif.getparam('loss')
# loss=netif.getparam("loss")
link_data = LinkData(
message_type=flags,
node1_id=if1.node.objid,
@ -643,12 +642,12 @@ class RJ45Node(PyCoreNode, PyCoreNetIf):
return
lines = tmp.stdout.read()
tmp.stdout.close()
for l in lines.split('\n'):
for l in lines.split("\n"):
items = l.split()
if len(items) < 2:
continue
if items[1] == "%s:" % self.localname:
flags = items[2][1:-1].split(',')
flags = items[2][1:-1].split(",")
if "UP" in flags:
self.old_up = True
elif items[0] == "inet":

View file

@ -91,7 +91,7 @@ class OvsNet(PyCoreNet):
try:
# turn off spanning tree protocol and forwarding delay
# TODO: appears stp and rstp are off by default, make sure this always holds true
# TODO: apears ovs only supports rstp forward delay and again it's off by default
# TODO: apears ovs only supports rstp forward delay and again it"s off by default
subprocess.check_call([constants.IP_BIN, "link", "set", self.bridge_name, "up"])
# create a new ebtables chain for this bridge
@ -428,7 +428,7 @@ class OvsCtrlNet(OvsNet):
self.serverintf, self.bridge_name)
if self.updown_script:
logger.info("interface %s updown script '%s shutdown' called", self.bridge_name, self.updown_script)
logger.info("interface %s updown script (%s shutdown) called", self.bridge_name, self.updown_script)
subprocess.check_call([self.updown_script, self.bridge_name, "shutdown"])
OvsNet.shutdown(self)
@ -478,7 +478,7 @@ class OvsPtpNet(OvsNet):
interface1_ip6 = None
interface1_ip6_mask = None
for address in if1.addrlist:
ip, sep, mask = address.partition('/')
ip, sep, mask = address.partition("/")
mask = int(mask)
if ipaddress.is_ipv4_address(ip):
family = AF_INET
@ -496,7 +496,7 @@ class OvsPtpNet(OvsNet):
interface2_ip6 = None
interface2_ip6_mask = None
for address in if2.addrlist:
ip, sep, mask = address.partition('/')
ip, sep, mask = address.partition("/")
mask = int(mask)
if ipaddress.is_ipv4_address(ip):
family = AF_INET
@ -510,7 +510,7 @@ class OvsPtpNet(OvsNet):
interface2_ip6_mask = mask
# TODO: not currently used
# loss=netif.getparam('loss')
# loss=netif.getparam("loss")
link_data = LinkData(
message_type=flags,
node1_id=if1.node.objid,
@ -723,11 +723,11 @@ class OvsGreTapBridge(OvsNet):
if self.gretap:
raise ValueError("gretap already exists for %s" % self.name)
remoteip = addresses[0].split('/')[0]
remoteip = addresses[0].split("/")[0]
localip = None
if len(addresses) > 1:
localip = addresses[1].split('/')[0]
localip = addresses[1].split("/")[0]
self.gretap = GreTap(session=self.session, remoteip=remoteip, objid=None, name=None,
localip=localip, ttl=self.ttl, key=self.grekey)

View file

@ -101,7 +101,7 @@ class TunTap(PyCoreNetIf):
# TODO: more sophisticated TAP creation here
# Debian does not support -p (tap) option, RedHat does.
# For now, this is disabled to allow the TAP to be created by another
# system (e.g. EMANE's emanetransportd)
# system (e.g. EMANE"s emanetransportd)
# check_call(["tunctl", "-t", self.name])
# self.install()
self.up = True
@ -133,19 +133,19 @@ class TunTap(PyCoreNetIf):
r = func()
if r == 0:
return
msg = 'attempt %s failed with nonzero exit status %s' % (i, r)
msg = "attempt %s failed with nonzero exit status %s" % (i, r)
if i < attempts + 1:
msg += ', retrying...'
msg += ", retrying..."
logger.info(msg)
time.sleep(delay)
delay = delay + delay
if delay > maxretrydelay:
delay = maxretrydelay
else:
msg += ', giving up'
msg += ", giving up"
logger.info(msg)
raise RuntimeError('command failed after %s attempts' % attempts)
raise RuntimeError("command failed after %s attempts" % attempts)
def waitfordevicelocal(self):
"""
@ -157,7 +157,7 @@ class TunTap(PyCoreNetIf):
"""
def localdevexists():
cmd = (constants.IP_BIN, 'link', 'show', self.localname)
cmd = (constants.IP_BIN, "link", "show", self.localname)
return utils.mutecall(cmd)
self.waitfor(localdevexists)
@ -170,7 +170,7 @@ class TunTap(PyCoreNetIf):
"""
def nodedevexists():
cmd = (constants.IP_BIN, 'link', 'show', self.name)
cmd = (constants.IP_BIN, "link", "show", self.name)
return self.node.cmd(cmd)
count = 0
@ -183,7 +183,7 @@ class TunTap(PyCoreNetIf):
# waiting if EMANE is still running
# TODO: remove emane code
if count < 5 and nodeutils.is_node(self.net, NodeTypes.EMANE) and \
self.node.session.emane.emanerunning(self.node):
self.node.session.emane.emanerunning(self.node):
count += 1
else:
raise e

View file

@ -194,7 +194,7 @@ class EbtablesQueue(object):
def ebchange(self, wlan):
"""
Flag a change to the given WLAN's _linked dict, so the ebtables
Flag a change to the given WLAN"s _linked dict, so the ebtables
chain will be rebuilt at the next interval.
:return: nothing
@ -300,7 +300,7 @@ class LxBrNet(PyCoreNet):
# turn off multicast snooping so mcast forwarding occurs w/o IGMP joins
snoop = "/sys/devices/virtual/net/%s/bridge/multicast_snooping" % self.brname
if os.path.exists(snoop):
open(snoop, "w").write('0')
open(snoop, "w").write("0")
except subprocess.CalledProcessError:
logger.exception("Error setting bridge parameters")
@ -443,7 +443,7 @@ class LxBrNet(PyCoreNet):
tc = [constants.TC_BIN, "qdisc", "replace", "dev", devname]
parent = ["root"]
changed = False
if netif.setparam('bw', bw):
if netif.setparam("bw", bw):
# from tc-tbf(8): minimum value for burst is rate / kernel_hz
if bw is not None:
burst = max(2 * netif.mtu, bw / 1000)
@ -455,28 +455,28 @@ class LxBrNet(PyCoreNet):
if self.up:
logger.info("linkconfig: %s" % ([tc + parent + ["handle", "1:"] + tbf],))
subprocess.check_call(tc + parent + ["handle", "1:"] + tbf)
netif.setparam('has_tbf', True)
netif.setparam("has_tbf", True)
changed = True
elif netif.getparam('has_tbf') and bw <= 0:
elif netif.getparam("has_tbf") and bw <= 0:
tcd = [] + tc
tcd[2] = "delete"
if self.up:
subprocess.check_call(tcd + parent)
netif.setparam('has_tbf', False)
netif.setparam("has_tbf", False)
# removing the parent removes the child
netif.setparam('has_netem', False)
netif.setparam("has_netem", False)
changed = True
if netif.getparam('has_tbf'):
if netif.getparam("has_tbf"):
parent = ["parent", "1:1"]
netem = ["netem"]
changed = max(changed, netif.setparam('delay', delay))
changed = max(changed, netif.setparam("delay", delay))
if loss is not None:
loss = float(loss)
changed = max(changed, netif.setparam('loss', loss))
changed = max(changed, netif.setparam("loss", loss))
if duplicate is not None:
duplicate = float(duplicate)
changed = max(changed, netif.setparam('duplicate', duplicate))
changed = max(changed, netif.setparam('jitter', jitter))
changed = max(changed, netif.setparam("duplicate", duplicate))
changed = max(changed, netif.setparam("jitter", jitter))
if not changed:
return
# jitter and delay use the same delay statement
@ -494,18 +494,18 @@ class LxBrNet(PyCoreNet):
netem += ["duplicate", "%s%%" % min(duplicate, 100)]
if delay <= 0 and jitter <= 0 and loss <= 0 and duplicate <= 0:
# possibly remove netem if it exists and parent queue wasn't removed
if not netif.getparam('has_netem'):
if not netif.getparam("has_netem"):
return
tc[2] = "delete"
if self.up:
logger.info("linkconfig: %s" % ([tc + parent + ["handle", "10:"]],))
subprocess.check_call(tc + parent + ["handle", "10:"])
netif.setparam('has_netem', False)
netif.setparam("has_netem", False)
elif len(netem) > 1:
if self.up:
logger.info("linkconfig: %s" % ([tc + parent + ["handle", "10:"] + netem],))
subprocess.check_call(tc + parent + ["handle", "10:"] + netem)
netif.setparam('has_netem', True)
netif.setparam("has_netem", True)
def linknet(self, net):
"""
@ -650,10 +650,10 @@ class GreTapBridge(LxBrNet):
"""
if self.gretap:
raise ValueError("gretap already exists for %s" % self.name)
remoteip = addrlist[0].split('/')[0]
remoteip = addrlist[0].split("/")[0]
localip = None
if len(addrlist) > 1:
localip = addrlist[1].split('/')[0]
localip = addrlist[1].split("/")[0]
self.gretap = GreTap(session=self.session, remoteip=remoteip, objid=None, name=None,
localip=localip, ttl=self.ttl, key=self.grekey)
self.attach(self.gretap)

View file

@ -81,8 +81,8 @@ class SimpleLxcNode(PyCoreNode):
if self.nodedir:
vnoded += ["-C", self.nodedir]
env = self.session.get_environment(state=False)
env['NODE_NUMBER'] = str(self.objid)
env['NODE_NAME'] = str(self.name)
env["NODE_NUMBER"] = str(self.objid)
env["NODE_NAME"] = str(self.name)
try:
tmp = subprocess.Popen(vnoded, stdout=subprocess.PIPE, env=env)
@ -245,7 +245,7 @@ class SimpleLxcNode(PyCoreNode):
source = os.path.abspath(source)
logger.info("mounting %s at %s" % (source, target))
try:
shcmd = "mkdir -p '%s' && %s -n --bind '%s' '%s'" % (
shcmd = 'mkdir -p "%s" && %s -n --bind "%s" "%s"' % (
target, constants.MOUNT_BIN, source, target)
self.shcmd(shcmd)
self._mounts.append((source, target))
@ -259,7 +259,7 @@ class SimpleLxcNode(PyCoreNode):
:param str target: target directory to unmount
:return: nothing
"""
logger.info("unmounting '%s'" % target)
logger.info("unmounting: %s", target)
try:
self.cmd([constants.UMOUNT_BIN, "-n", "-l", target])
except IOError:
@ -295,16 +295,16 @@ class SimpleLxcNode(PyCoreNode):
sessionid = self.session.short_session_id()
try:
suffix = '%x.%s.%s' % (self.objid, ifindex, sessionid)
suffix = "%x.%s.%s" % (self.objid, ifindex, sessionid)
except TypeError:
suffix = '%s.%s.%s' % (self.objid, ifindex, sessionid)
suffix = "%s.%s.%s" % (self.objid, ifindex, sessionid)
localname = 'veth' + suffix
localname = "veth" + suffix
if len(localname) >= 16:
raise ValueError("interface local name '%s' too long" % localname)
name = localname + 'p'
raise ValueError("interface local name (%s) too long" % localname)
name = localname + "p"
if len(name) >= 16:
raise ValueError, "interface name '%s' too long" % name
raise ValueError("interface name (%s) too long" % name)
veth = VEth(node=self, name=name, localname=localname, mtu=1500, net=net, start=self.up)
if self.up:
@ -389,7 +389,7 @@ class SimpleLxcNode(PyCoreNode):
:return: nothing
"""
if self.up:
if ":" in str(addr): # check if addr is ipv6
if ":" in str(addr): # check if addr is ipv6
self.cmd([constants.IP_BIN, "addr", "add", str(addr),
"dev", self.ifname(ifindex)])
else:
@ -519,7 +519,7 @@ class SimpleLxcNode(PyCoreNode):
:param str filename: file name to add
:return: nothing
"""
shcmd = "mkdir -p $(dirname '%s') && mv '%s' '%s' && sync" % (filename, srcname, filename)
shcmd = 'mkdir -p $(dirname "%s") && mv "%s" "%s" && sync' % (filename, srcname, filename)
self.shcmd(shcmd)
def getaddr(self, ifname, rescan=False):
@ -626,7 +626,7 @@ class LxcNode(SimpleLxcNode):
"""
if path[0] != "/":
raise ValueError("path not fully qualified: %s" % path)
hostpath = os.path.join(self.nodedir, os.path.normpath(path).strip('/').replace('/', '.'))
hostpath = os.path.join(self.nodedir, os.path.normpath(path).strip("/").replace("/", "."))
try:
os.mkdir(hostpath)
@ -637,7 +637,7 @@ class LxcNode(SimpleLxcNode):
def hostfilename(self, filename):
"""
Return the name of a node's file on the host filesystem.
Return the name of a node"s file on the host filesystem.
:param str filename: host file name
:return: path to file
@ -653,7 +653,7 @@ class LxcNode(SimpleLxcNode):
def opennodefile(self, filename, mode="w"):
"""
Open a node file, within it's directory.
Open a node file, within it"s directory.
:param str filename: file name to open
:param str mode: mode to open file in
@ -679,7 +679,7 @@ class LxcNode(SimpleLxcNode):
f.write(contents)
os.chmod(f.name, mode)
f.close()
logger.info("created nodefile: '%s'; mode: 0%o" % (f.name, mode))
logger.info("created nodefile: %s; mode: 0%o", f.name, mode)
def nodefilecopy(self, filename, srcfilename, mode=None):
"""
@ -695,4 +695,4 @@ class LxcNode(SimpleLxcNode):
shutil.copy2(srcfilename, hostfilename)
if mode is not None:
os.chmod(hostfilename, mode)
logger.info("copied nodefile: '%s'; mode: %s" % (hostfilename, mode))
logger.info("copied nodefile: %s; mode: %s", hostfilename, mode)