summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorYasufumi Ogawa <ogawa.yasufumi@lab.ntt.co.jp>2018-02-27 21:34:28 +0900
committerFerruh Yigit <ferruh.yigit@intel.com>2018-03-02 17:19:14 +0000
commitea63184a32db0075ac2aac3e1499f65efd54fa0d (patch)
tree345eb749b49f6605740ab2607da58c348d3687c8
parentc5c76b19c991caf69dcaeb13f3eb35919873d647 (diff)
downloadspp-ea63184a32db0075ac2aac3e1499f65efd54fa0d.zip
spp-ea63184a32db0075ac2aac3e1499f65efd54fa0d.tar.gz
spp-ea63184a32db0075ac2aac3e1499f65efd54fa0d.tar.xz
spp_vf: refactor to comply with coding style
Refactoring has been made for spp_vf.py to comply with pep8. Signed-off-by: Kentaro Watanabe <watanabe.kentaro.z01@as.ntt-tx.co.jp> Signed-off-by: Yasufumi Ogawa <ogawa.yasufumi@lab.ntt.co.jp>
-rwxr-xr-xsrc/spp_vf.py147
1 files changed, 84 insertions, 63 deletions
diff --git a/src/spp_vf.py b/src/spp_vf.py
index df1ae47..8c2c002 100755
--- a/src/spp_vf.py
+++ b/src/spp_vf.py
@@ -13,6 +13,7 @@ import sys
import json
+
class GrowingList(list):
"""GrowingList"""
@@ -21,6 +22,7 @@ class GrowingList(list):
self.extend([None]*(index + 1 - len(self)))
list.__setitem__(self, index, value)
+
MAX_SECONDARY = 16
# init
@@ -28,14 +30,15 @@ PRIMARY = ''
SECONDARY_LIST = []
SECONDARY_COUNT = 0
-#init primary comm channel
+# init primary comm channel
MAIN2PRIMARY = Queue()
PRIMARY2MAIN = Queue()
-#init secondary comm channel list
+# init secondary comm channel list
MAIN2SEC = GrowingList()
SEC2MAIN = GrowingList()
+
def connectionthread(name, client_id, conn, m2s, s2m):
"""Manage secondary process connections"""
@@ -43,28 +46,29 @@ def connectionthread(name, client_id, conn, m2s, s2m):
recv_str = 'recv'
recv_json = None
- #infinite loop so that function do not terminate and thread do not end.
+ # infinite loop so that function do not terminate and thread do not end.
while True:
try:
- _, _, _ = select.select([conn,], [conn,], [], 5)
+ _, _, _ = select.select([conn, ], [conn, ], [], 5)
except select.error:
break
- #Sending message to connected secondary
+ # Sending message to connected secondary
try:
cmd_str = m2s.get(True)
- conn.send(cmd_str) #send only takes string
+ conn.send(cmd_str) # send only takes string
except KeyError:
break
except Exception, excep:
- print (str(excep))
+ print(str(excep))
break
- #Receiving from secondary
+ # Receiving from secondary
try:
recv_str = ""
while True:
- data = conn.recv(1024) # 1024 stands for bytes of data to be received
+ # 1024 stands for bytes of data to be received
+ data = conn.recv(1024)
if data:
recv_str = recv_str + data
if len(data) < 1024:
@@ -73,42 +77,45 @@ def connectionthread(name, client_id, conn, m2s, s2m):
break
if len(recv_str) > 0:
recv_json = json.loads(recv_str)
- recv_str = "recv:" + str(conn.fileno()) + ":len:" + str(len(recv_str)) + ":\n" + json.dumps(recv_json, indent=4) + "\n"
+ recv_str = "recv:%d:len:%d:\n%s\n" % (
+ conn.fileno(), len(recv_str),
+ json.dumps(recv_json, indent=4))
if not data:
s2m.put(recv_str + "closing:" + str(conn))
break
- #s2m.put("recv:" + str(conn.fileno()) + ":{" + recv_str + "}")
+ # s2m.put("recv:" + str(conn.fileno()) + ":{" + recv_str + "}")
s2m.put(recv_str)
except Exception, excep:
- print (str(excep))
+ print(str(excep))
break
SECONDARY_LIST.remove(client_id)
conn.close()
+
def getclientid(conn):
"""Get client_id from client"""
try:
conn.send("_get_client_id")
- #conn.send("{\"commands\":[{\"command\":\"process\"}]}")
+ # conn.send("{\"commands\":[{\"command\":\"process\"}]}")
except KeyError:
return -1
data = conn.recv(1024)
- if data == None:
+ if data is None:
return -1
- #client_id = int(data.strip('\0'))
+ # client_id = int(data.strip('\0'))
json_dict = json.loads(data)
client_id = int(json_dict['client_id'])
if client_id < 0 or client_id > MAX_SECONDARY:
return -1
- print ("secondary id %d" % client_id)
+ print("secondary id %d" % client_id)
return client_id
found = 0
@@ -140,6 +147,7 @@ def getclientid(conn):
return free_client_id
+
def acceptthread(sock, main2sec, sec2main):
"""Listen for secondary processes"""
@@ -147,16 +155,16 @@ def acceptthread(sock, main2sec, sec2main):
try:
while True:
- #Accepting incoming connections
+ # Accepting incoming connections
conn, _ = sock.accept()
client_id = getclientid(conn)
if client_id < 0:
break
- #Creating new thread.
- #Calling secondarythread function for this function and passing
- #conn as argument.
+ # Creating new thread.
+ # Calling secondarythread function for this function and passing
+ # conn as argument.
SECONDARY_LIST.append(client_id)
main2sec[client_id] = Queue()
@@ -167,35 +175,39 @@ def acceptthread(sock, main2sec, sec2main):
sec2main[client_id], ))
SECONDARY_COUNT += 1
except Exception, excep:
- print (str(excep))
+ print(str(excep))
sock.close()
+
def command_primary(command):
"""Send command to primary process"""
if PRIMARY:
MAIN2PRIMARY.put(command)
- print (PRIMARY2MAIN.get(True))
+ print(PRIMARY2MAIN.get(True))
else:
- print ("primary not started")
+ print("primary not started")
+
def command_secondary(sec_id, command):
"""Send command to secondary process with sec_id"""
if sec_id in SECONDARY_LIST:
MAIN2SEC[sec_id].put(command)
- print (SEC2MAIN[sec_id].get(True))
+ print(SEC2MAIN[sec_id].get(True))
else:
- print ("secondary id %d not exist" % sec_id)
+ print("secondary id %d not exist" % sec_id)
+
def print_status():
"""Display information about connected clients"""
- print ("Soft Patch Panel Status :")
- print ("primary: %d" % PRIMARY)
- print ("secondary count: %d" % len(SECONDARY_LIST))
+ print("Soft Patch Panel Status :")
+ print("primary: %d" % PRIMARY)
+ print("secondary count: %d" % len(SECONDARY_LIST))
for i in SECONDARY_LIST:
- print ("Connected secondary id: %d" % i)
+ print("Connected secondary id: %d" % i)
+
def primarythread(sock, main2primary, primary2main):
"""Manage primary process connection"""
@@ -204,41 +216,43 @@ def primarythread(sock, main2primary, primary2main):
cmd_str = ''
while True:
- #waiting for connection
+ # waiting for connection
PRIMARY = False
conn, addr = sock.accept()
PRIMARY = True
while conn:
try:
- _, _, _ = select.select([conn,], [conn,], [], 5)
+ _, _, _ = select.select([conn, ], [conn, ], [], 5)
except select.error:
break
- #Sending message to connected primary
+ # Sending message to connected primary
try:
cmd_str = main2primary.get(True)
- conn.send(cmd_str) #send only takes string
+ conn.send(cmd_str) # send only takes string
except KeyError:
break
except Exception, excep:
- print (str(excep))
+ print(str(excep))
break
- #Receiving from primary
+ # Receiving from primary
try:
- data = conn.recv(1024) # 1024 stands for bytes of data to be received
+ # 1024 stands for bytes of data to be received
+ data = conn.recv(1024)
if data:
- primary2main.put("recv:" + str(addr) + ":" + "{" + data + "}")
+ primary2main.put("recv:%s:{%s}" % (str(addr), data))
else:
- primary2main.put("closing:" + str(addr))
+ primary2main.put("closing:%s" % str(addr))
conn.close()
break
except Exception, excep:
- print (str(excep))
+ print(str(excep))
break
- print ("primary communication thread end")
+ print("primary communication thread end")
+
def close_all_secondary():
"""Exit all secondary processes"""
@@ -252,6 +266,7 @@ def close_all_secondary():
command_secondary(i, 'exit')
SECONDARY_COUNT = 0
+
def check_sec_cmds(cmds):
"""Validate secondary commands before sending"""
@@ -284,6 +299,7 @@ def check_sec_cmds(cmds):
return valid
+
class Shell(cmd.Cmd, object):
"""SPP command prompt"""
@@ -332,8 +348,8 @@ class Shell(cmd.Cmd, object):
else:
completions = [p
for p in self.COMMANDS
- if p.startswith(text)
- ]
+ if p.startswith(text)]
+
return completions
def complete_sec(self, text, line, begidx, endidx):
@@ -344,8 +360,8 @@ class Shell(cmd.Cmd, object):
else:
completions = [p
for p in self.COMMANDS
- if p.startswith(text)
- ]
+ if p.startswith(text)]
+
return completions
def do_status(self, _):
@@ -359,23 +375,23 @@ class Shell(cmd.Cmd, object):
if command and command in self.COMMANDS:
command_primary(command)
else:
- print ("primary invalid command")
+ print("primary invalid command")
def do_sec(self, arg):
"""Send command to secondary process"""
cmds = arg.split(';')
if len(cmds) < 2:
- print ("error")
+ print("error")
elif str.isdigit(cmds[0]):
sec_id = int(cmds[0])
if check_sec_cmds(cmds[1]):
command_secondary(sec_id, cmds[1])
else:
- print ("invalid cmd")
+ print("invalid cmd")
else:
- print (cmds[0])
- print ("first %s" % cmds[1])
+ print(cmds[0])
+ print("first %s" % cmds[1])
def do_record(self, arg):
"""Save future commands to filename: RECORD filename.cmd"""
@@ -395,7 +411,7 @@ class Shell(cmd.Cmd, object):
lines.append(line)
self.cmdqueue.extend(lines)
except IOError:
- print ("Error: File does not exist.")
+ print("Error: File does not exist.")
def precmd(self, line):
if self.recorded_file and 'playback' not in line:
@@ -424,49 +440,53 @@ class Shell(cmd.Cmd, object):
self.close()
return True
+
def main(argv):
"""main"""
# Defining server address and port
- host = '' #'localhost' or '127.0.0.1' or '' are all same
+ host = '' # 'localhost' or '127.0.0.1' or '' are all same
try:
- opts, _ = getopt.getopt(argv, "p:s:h", ["help", "primary = ", "secondary"])
+ opts, _ = getopt.getopt(
+ argv, "p:s:h", ["help", "primary = ", "secondary"])
except getopt.GetoptError:
- print ('spp.py -p <primary__port_number> -s <secondary_port_number>')
+ print('spp.py -p <primary__port_number> -s <secondary_port_number>')
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
- print ('spp.py -p <primary__port_number> -s <secondary_port_number>')
+ print(
+ 'spp.py -p <primary__port_number> -s <secondary_port_number>')
sys.exit()
elif opt in ("-p", "--primary"):
primary_port = int(arg)
- print ("primary port : %d" % primary_port)
+ print("primary port : %d" % primary_port)
elif opt in ("-s", "--secondary"):
secondary_port = int(arg)
- print ('secondary port : %d' % secondary_port)
+ print('secondary port : %d' % secondary_port)
- #Creating primary socket object
+ # Creating primary socket object
primary_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- #Binding primary socket to a address. bind() takes tuple of host and port.
+ # Binding primary socket to a address. bind() takes tuple of host and port.
primary_sock.bind((host, primary_port))
- #Listening primary at the address
- primary_sock.listen(1) #5 denotes the number of clients can queue
+ # Listening primary at the address
+ primary_sock.listen(1) # 5 denotes the number of clients can queue
primary_thread = Thread(target=primarythread,
args=(primary_sock, MAIN2PRIMARY, PRIMARY2MAIN,))
primary_thread.daemon = True
primary_thread.start()
- #Creating secondary socket object
+ # Creating secondary socket object
secondary_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- #Binding secondary socket to a address. bind() takes tuple of host and port.
+ # Binding secondary socket to a address. bind() takes tuple of host
+ # and port.
secondary_sock.bind((host, secondary_port))
- #Listening secondary at the address
+ # Listening secondary at the address
secondary_sock.listen(MAX_SECONDARY)
# secondary process handling thread
@@ -481,5 +501,6 @@ def main(argv):
secondary_sock.shutdown(socket.SHUT_RDWR)
secondary_sock.close()
+
if __name__ == "__main__":
main(sys.argv[1:])