more updates to using f string
This commit is contained in:
parent
79cde8cd59
commit
7d2a615716
23 changed files with 248 additions and 251 deletions
|
@ -17,7 +17,9 @@ from core import constants
|
|||
from core.api.grpc.server import CoreGrpcServer
|
||||
from core.api.tlv.corehandlers import CoreHandler, CoreUdpHandler
|
||||
from core.api.tlv.coreserver import CoreServer, CoreUdpServer
|
||||
from core.constants import CORE_CONF_DIR, COREDPY_VERSION
|
||||
from core.emulator import enumerations
|
||||
from core.emulator.enumerations import CORE_API_PORT
|
||||
from core.utils import close_onexec, load_logging_config
|
||||
|
||||
|
||||
|
@ -67,7 +69,9 @@ def cored(cfg):
|
|||
# initialize grpc api
|
||||
if cfg["grpc"] == "True":
|
||||
grpc_server = CoreGrpcServer(server.coreemu)
|
||||
grpc_address = "%s:%s" % (cfg["grpcaddress"], cfg["grpcport"])
|
||||
address_config = cfg["grpcaddress"]
|
||||
port_config = cfg["grpcport"]
|
||||
grpc_address = f"{address_config}:{port_config}"
|
||||
grpc_thread = threading.Thread(target=grpc_server.listen, args=(grpc_address,))
|
||||
grpc_thread.daemon = True
|
||||
grpc_thread.start()
|
||||
|
@ -91,30 +95,34 @@ def get_merged_config(filename):
|
|||
:rtype: dict
|
||||
"""
|
||||
# these are the defaults used in the config file
|
||||
default_log = os.path.join(constants.CORE_CONF_DIR, "logging.conf")
|
||||
default_grpc_port = "50051"
|
||||
default_threads = "1"
|
||||
default_address = "localhost"
|
||||
defaults = {
|
||||
"port": "%d" % enumerations.CORE_API_PORT,
|
||||
"listenaddr": "localhost",
|
||||
"numthreads": "1",
|
||||
"grpcport": "50051",
|
||||
"grpcaddress": "localhost",
|
||||
"logfile": os.path.join(constants.CORE_CONF_DIR, "logging.conf")
|
||||
"port": str(CORE_API_PORT),
|
||||
"listenaddr": default_address,
|
||||
"numthreads": default_threads,
|
||||
"grpcport": default_grpc_port,
|
||||
"grpcaddress": default_address,
|
||||
"logfile": default_log
|
||||
}
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="CORE daemon v.%s instantiates Linux network namespace nodes." % constants.COREDPY_VERSION)
|
||||
description=f"CORE daemon v.{COREDPY_VERSION} instantiates Linux network namespace nodes.")
|
||||
parser.add_argument("-f", "--configfile", dest="configfile",
|
||||
help="read config from specified file; default = %s" % filename)
|
||||
help=f"read config from specified file; default = {filename}")
|
||||
parser.add_argument("-p", "--port", dest="port", type=int,
|
||||
help="port number to listen on; default = %s" % defaults["port"])
|
||||
help=f"port number to listen on; default = {CORE_API_PORT}")
|
||||
parser.add_argument("-n", "--numthreads", dest="numthreads", type=int,
|
||||
help="number of server threads; default = %s" % defaults["numthreads"])
|
||||
help=f"number of server threads; default = {default_threads}")
|
||||
parser.add_argument("--ovs", action="store_true", help="enable experimental ovs mode, default is false")
|
||||
parser.add_argument("--grpc", action="store_true", help="enable grpc api, default is false")
|
||||
parser.add_argument("--grpc-port", dest="grpcport",
|
||||
help="grpc port to listen on; default %s" % defaults["grpcport"])
|
||||
help=f"grpc port to listen on; default {default_grpc_port}")
|
||||
parser.add_argument("--grpc-address", dest="grpcaddress",
|
||||
help="grpc address to listen on; default %s" % defaults["grpcaddress"])
|
||||
parser.add_argument("-l", "--logfile", help="core logging configuration; default %s" % defaults["logfile"])
|
||||
help=f"grpc address to listen on; default {default_address}")
|
||||
parser.add_argument("-l", "--logfile", help=f"core logging configuration; default {default_log}")
|
||||
|
||||
# parse command line options
|
||||
args = parser.parse_args()
|
||||
|
@ -146,7 +154,7 @@ def main():
|
|||
:return: nothing
|
||||
"""
|
||||
# get a configuration merged from config file and command-line arguments
|
||||
cfg = get_merged_config("%s/core.conf" % constants.CORE_CONF_DIR)
|
||||
cfg = get_merged_config(f"{CORE_CONF_DIR}/core.conf")
|
||||
|
||||
# load logging configuration
|
||||
load_logging_config(cfg["logfile"])
|
||||
|
|
|
@ -38,7 +38,7 @@ class FileUpdater(object):
|
|||
txt = "Updating"
|
||||
if self.action == "check":
|
||||
txt = "Checking"
|
||||
sys.stdout.write("%s file: %s\n" % (txt, self.filename))
|
||||
sys.stdout.write(f"{txt} file: {self.filename}\n")
|
||||
|
||||
if self.target == "service":
|
||||
r = self.update_file(fn=self.update_services)
|
||||
|
@ -52,9 +52,9 @@ class FileUpdater(object):
|
|||
if not r:
|
||||
txt = "NOT "
|
||||
if self.action == "check":
|
||||
sys.stdout.write("String %sfound.\n" % txt)
|
||||
sys.stdout.write(f"String {txt} found.\n")
|
||||
else:
|
||||
sys.stdout.write("File %supdated.\n" % txt)
|
||||
sys.stdout.write(f"File {txt} updated.\n")
|
||||
|
||||
return r
|
||||
|
||||
|
@ -70,7 +70,7 @@ class FileUpdater(object):
|
|||
r = self.update_keyvals(key, vals)
|
||||
if self.action == "check":
|
||||
return r
|
||||
valstr = "%s" % r
|
||||
valstr = str(r)
|
||||
return "= ".join([key, valstr]) + "\n"
|
||||
|
||||
def update_emane_models(self, line):
|
||||
|
@ -125,7 +125,7 @@ class FileUpdater(object):
|
|||
else:
|
||||
raise ValueError("unknown target")
|
||||
if not os.path.exists(filename):
|
||||
raise ValueError("file %s does not exist" % filename)
|
||||
raise ValueError(f"file {filename} does not exist")
|
||||
return search, filename
|
||||
|
||||
def update_file(self, fn=None):
|
||||
|
@ -187,18 +187,17 @@ class FileUpdater(object):
|
|||
|
||||
|
||||
def main():
|
||||
actions = ", ".join(FileUpdater.actions)
|
||||
targets = ", ".join(FileUpdater.targets)
|
||||
usagestr = "usage: %prog [-h] [options] <action> <target> <string>\n"
|
||||
usagestr += "\nHelper tool to add, remove, or check for "
|
||||
usagestr += "services, models, and node types\nin a CORE installation.\n"
|
||||
usagestr += "\nExamples:\n %prog add service newrouting"
|
||||
usagestr += "\n %prog -v check model RfPipe"
|
||||
usagestr += "\n %prog --userpath=\"$HOME/.core\" add nodetype \"{ftp ftp.gif ftp.gif {DefaultRoute FTP} netns {FTP server} }\" \n"
|
||||
usagestr += "\nArguments:\n <action> should be one of: %s" % \
|
||||
", ".join(FileUpdater.actions)
|
||||
usagestr += "\n <target> should be one of: %s" % \
|
||||
", ".join(FileUpdater.targets)
|
||||
usagestr += "\n <string> is the text to %s" % \
|
||||
", ".join(FileUpdater.actions)
|
||||
usagestr += f"\nArguments:\n <action> should be one of: {actions}"
|
||||
usagestr += f"\n <target> should be one of: {targets}"
|
||||
usagestr += f"\n <string> is the text to {actions}"
|
||||
parser = optparse.OptionParser(usage=usagestr)
|
||||
parser.set_defaults(userpath=None, verbose=False, )
|
||||
|
||||
|
@ -222,14 +221,14 @@ def main():
|
|||
|
||||
action = args[0]
|
||||
if action not in FileUpdater.actions:
|
||||
usage("invalid action %s" % action, 1)
|
||||
usage(f"invalid action {action}", 1)
|
||||
|
||||
target = args[1]
|
||||
if target not in FileUpdater.targets:
|
||||
usage("invalid target %s" % target, 1)
|
||||
usage(f"invalid target {target}", 1)
|
||||
|
||||
if target == "nodetype" and not options.userpath:
|
||||
usage("user path option required for this target (%s)" % target)
|
||||
usage(f"user path option required for this target ({target})")
|
||||
|
||||
data = args[2]
|
||||
|
||||
|
@ -237,7 +236,7 @@ def main():
|
|||
up = FileUpdater(action, target, data, options)
|
||||
r = up.process()
|
||||
except Exception as e:
|
||||
sys.stderr.write("Exception: %s\n" % e)
|
||||
sys.stderr.write(f"Exception: {e}\n")
|
||||
sys.exit(1)
|
||||
if not r:
|
||||
sys.exit(1)
|
||||
|
|
|
@ -21,9 +21,9 @@ def print_available_tlvs(t, tlv_class):
|
|||
"""
|
||||
Print a TLV list.
|
||||
"""
|
||||
print("TLVs available for %s message:" % t)
|
||||
print(f"TLVs available for {t} message:")
|
||||
for tlv in sorted([tlv for tlv in tlv_class.tlv_type_map], key=lambda x: x.name):
|
||||
print("%s:%s" % (tlv.value, tlv.name))
|
||||
print(f"{tlv.value}:{tlv.name}")
|
||||
|
||||
|
||||
def print_examples(name):
|
||||
|
@ -54,9 +54,9 @@ def print_examples(name):
|
|||
"srcname=\"./test.log\"",
|
||||
"move a test.log file from host to node 2"),
|
||||
]
|
||||
print("Example %s invocations:" % name)
|
||||
print(f"Example {name} invocations:")
|
||||
for cmd, descr in examples:
|
||||
print(" %s %s\n\t\t%s" % (name, cmd, descr))
|
||||
print(f" {name} {cmd}\n\t\t{descr}")
|
||||
|
||||
|
||||
def receive_message(sock):
|
||||
|
@ -86,11 +86,11 @@ def receive_message(sock):
|
|||
except KeyError:
|
||||
msg = coreapi.CoreMessage(msgflags, msghdr, msgdata)
|
||||
msg.message_type = msgtype
|
||||
print("unimplemented CORE message type: %s" % msg.type_str())
|
||||
print(f"unimplemented CORE message type: {msg.type_str()}")
|
||||
return msg
|
||||
if len(data) > msglen + coreapi.CoreMessage.header_len:
|
||||
print("received a message of type %d, dropping %d bytes of extra data" \
|
||||
% (msgtype, len(data) - (msglen + coreapi.CoreMessage.header_len)))
|
||||
data_size = len(data) - (msglen + coreapi.CoreMessage.header_len)
|
||||
print(f"received a message of type {msgtype}, dropping {data_size} bytes of extra data")
|
||||
return msgcls(msgflags, msghdr, msgdata)
|
||||
|
||||
|
||||
|
@ -132,7 +132,7 @@ def connect_to_session(sock, requested):
|
|||
print("requested session not found!")
|
||||
return False
|
||||
|
||||
print("joining session: %s" % session)
|
||||
print(f"joining session: {session}")
|
||||
tlvdata = coreapi.CoreSessionTlv.pack(SessionTlvs.NUMBER.value, session)
|
||||
flags = MessageFlags.ADD.value
|
||||
smsg = coreapi.CoreSessionMessage.pack(flags, tlvdata)
|
||||
|
@ -147,9 +147,9 @@ def receive_response(sock, opt):
|
|||
print("waiting for response...")
|
||||
msg = receive_message(sock)
|
||||
if msg is None:
|
||||
print("disconnected from %s:%s" % (opt.address, opt.port))
|
||||
print(f"disconnected from {opt.address}:{opt.port}")
|
||||
sys.exit(0)
|
||||
print("received message: %s" % msg)
|
||||
print(f"received message: {msg}")
|
||||
|
||||
|
||||
def main():
|
||||
|
@ -160,36 +160,36 @@ def main():
|
|||
flags = [flag.name for flag in MessageFlags]
|
||||
usagestr = "usage: %prog [-h|-H] [options] [message-type] [flags=flags] "
|
||||
usagestr += "[message-TLVs]\n\n"
|
||||
usagestr += "Supported message types:\n %s\n" % types
|
||||
usagestr += "Supported message flags (flags=f1,f2,...):\n %s" % flags
|
||||
usagestr += f"Supported message types:\n {types}\n"
|
||||
usagestr += f"Supported message flags (flags=f1,f2,...):\n {flags}"
|
||||
parser = optparse.OptionParser(usage=usagestr)
|
||||
default_address = "localhost"
|
||||
default_session = None
|
||||
default_tcp = False
|
||||
parser.set_defaults(
|
||||
port=CORE_API_PORT,
|
||||
address="localhost",
|
||||
session=None,
|
||||
address=default_address,
|
||||
session=default_session,
|
||||
listen=False,
|
||||
examples=False,
|
||||
tlvs=False,
|
||||
tcp=False
|
||||
tcp=default_tcp
|
||||
)
|
||||
|
||||
parser.add_option("-H", dest="examples", action="store_true",
|
||||
help="show example usage help message and exit")
|
||||
parser.add_option("-p", "--port", dest="port", type=int,
|
||||
help="TCP port to connect to, default: %d" % \
|
||||
parser.defaults["port"])
|
||||
help=f"TCP port to connect to, default: {CORE_API_PORT}")
|
||||
parser.add_option("-a", "--address", dest="address", type=str,
|
||||
help="Address to connect to, default: %s" % \
|
||||
parser.defaults["address"])
|
||||
help=f"Address to connect to, default: {default_address}")
|
||||
parser.add_option("-s", "--session", dest="session", type=str,
|
||||
help="Session to join, default: %s" % \
|
||||
parser.defaults["session"])
|
||||
help=f"Session to join, default: {default_session}")
|
||||
parser.add_option("-l", "--listen", dest="listen", action="store_true",
|
||||
help="Listen for a response message and print it.")
|
||||
parser.add_option("-t", "--list-tlvs", dest="tlvs", action="store_true",
|
||||
help="List TLVs for the specified message type.")
|
||||
parser.add_option("--tcp", dest="tcp", action="store_true",
|
||||
help="Use TCP instead of UDP and connect to a session default: %s" % parser.defaults["tcp"])
|
||||
help=f"Use TCP instead of UDP and connect to a session default: {default_tcp}")
|
||||
|
||||
def usage(msg=None, err=0):
|
||||
sys.stdout.write("\n")
|
||||
|
@ -209,7 +209,7 @@ def main():
|
|||
# given a message type t, determine the message and TLV classes
|
||||
t = args.pop(0)
|
||||
if t not in types:
|
||||
usage("Unknown message type requested: %s" % t)
|
||||
usage(f"Unknown message type requested: {t}")
|
||||
message_type = MessageTypes[t]
|
||||
msg_cls = coreapi.CLASS_MAP[message_type.value]
|
||||
tlv_cls = msg_cls.tlv_class
|
||||
|
@ -225,7 +225,7 @@ def main():
|
|||
for a in args:
|
||||
typevalue = a.split("=")
|
||||
if len(typevalue) < 2:
|
||||
usage("Use \"type=value\" syntax instead of \"%s\"." % a)
|
||||
usage(f"Use \"type=value\" syntax instead of \"{a}\".")
|
||||
tlv_typestr = typevalue[0]
|
||||
tlv_valstr = "=".join(typevalue[1:])
|
||||
if tlv_typestr == "flags":
|
||||
|
@ -237,7 +237,7 @@ def main():
|
|||
tlv_type = tlv_cls.tlv_type_map[tlv_name]
|
||||
tlvdata += tlv_cls.pack_string(tlv_type.value, tlv_valstr)
|
||||
except KeyError:
|
||||
usage("Unknown TLV: \"%s\"" % tlv_name)
|
||||
usage(f"Unknown TLV: \"{tlv_name}\"")
|
||||
|
||||
flags = 0
|
||||
for f in flagstr.split(","):
|
||||
|
@ -249,7 +249,7 @@ def main():
|
|||
n = flag_enum.value
|
||||
flags |= n
|
||||
except KeyError:
|
||||
usage("Invalid flag \"%s\"." % f)
|
||||
usage(f"Invalid flag \"{f}\".")
|
||||
|
||||
msg = msg_cls.pack(flags, tlvdata)
|
||||
|
||||
|
@ -264,7 +264,7 @@ def main():
|
|||
try:
|
||||
sock.connect((opt.address, opt.port))
|
||||
except Exception as e:
|
||||
print("Error connecting to %s:%s:\n\t%s" % (opt.address, opt.port, e))
|
||||
print(f"Error connecting to {opt.address}:{opt.port}:\n\t{e}")
|
||||
sys.exit(1)
|
||||
|
||||
if opt.tcp and not connect_to_session(sock, opt.session):
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue