+#!/usr/bin/python
+#
+# Calin-Andrei Burloiu, 2011, calin.burloiu@gmail.com
+#
+# This script does the following in a loop until a SIGUSR1 is received:
+# 1. Sends a TCP packet to the handle packets server.
+# 2. Parses the SystemTap output file and dumps the delay of the packet from
+# the transport level.
+#
+
+import sys
+import signal
+import socket
+import time
+
+# Socket
+s = None
+# Files
+fIn = None
+fOut = None
+
+def signalHandler(signum, frame):
+ global s
+ global fIn
+ global fOut
+ s.close()
+ fIn.close()
+ fOut.close()
+ print "Handle packets script exited."
+ exit(0)
+
+def main():
+ if len(sys.argv) != 4:
+ sys.stderr.write('usage: python ' + sys.argv[0] + ' server_host server_port\n')
+ exit(1)
+
+ global s
+ global fIn
+ global fOut
+ HOST = sys.argv[1]
+ PORT = int(sys.argv[2])
+ DATA = 'x' * 1000
+ stapOutput = "stap.log"
+ delaysOutput = sys.argv[3]
+
+ # Set the signal handler.
+ signal.signal(signal.SIGUSR1, signalHandler)
+
+ # Wait until SystemTap finishes initialization
+ # i.e. creates the output file.
+ while True:
+ try:
+ fIn = open(stapOutput, 'r')
+ except IOError:
+ time.sleep(1)
+ continue
+ break
+
+ # Open the output file.
+ fOut = open(delaysOutput, 'w')
+ fOut.truncate(0)
+
+ # Connect to the server.
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.connect((HOST, PORT))
+
+ # The loop
+ while True:
+ # Send a TCP packet to the server.
+ # SystemTap will write new information in stap.log.
+ s.send(DATA, socket.MSG_EOR)
+
+ time.sleep(1)
+
+ # Process stap.log.
+ t1 = -1
+ t2 = -1
+ delta = -1
+ while True:
+ line = fIn.readline()
+ if not line: break
+ if line.find('sendmsg') != -1:
+ t1 = int(line.partition(' ')[0])
+ if t1 != -1 and t2 == -1 and line.find('transmit') != -1:
+ t2 = int(line.partition(' ')[0])
+ delta = t2 - t1
+ fOut.write(str(delta) + '\n')
+
+ return 0
+
+if __name__ == "__main__":
+ sys.exit(main())