ppf: Add msgctl.py.
authorRazvan Deaconescu <razvan.deaconescu@cs.pub.ro>
Sat, 20 Aug 2011 16:22:00 +0000 (19:22 +0300)
committerRazvan Deaconescu <razvan.deaconescu@cs.pub.ro>
Sat, 20 Aug 2011 16:55:37 +0000 (19:55 +0300)
Interface for status/verbose messages handling in the database.

ppf/db/msgctl.py [new file with mode: 0644]

diff --git a/ppf/db/msgctl.py b/ppf/db/msgctl.py
new file mode 100644 (file)
index 0000000..dcbd165
--- /dev/null
@@ -0,0 +1,279 @@
+"""
+Verbose/status messages interface to database.
+Add, delete, lists swarms and sessions.
+
+2010, Razvan Deaconescu, razvan.deaconescu@cs.pub.ro
+2010, Adriana Draghici, adriana008@gmail.com
+"""
+
+import sys
+import getopt
+import datetime
+import re
+import logging
+
+import julian
+import access
+
+#
+# Logging code heavily inspired by Logging HOWTO documentation:
+#     http://docs.python.org/dev/howto/logging.html#configuring-logging
+#
+
+# Create logger; default logging level is DEBUG.
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+# Create console handler and set level to ERROR.
+ch = logging.StreamHandler()
+ch.setLevel(logging.ERROR)
+
+# Create formatter.
+formatter = logging.Formatter('%(filename)s:%(lineno)s - %(levelname)s: %(message)s')
+
+# Add formatter to console handler.
+ch.setFormatter(formatter)
+
+# Add console handler to logger.
+logger.addHandler(ch)
+
+
+def usage():
+    print """Usage: python %s action target [-i|--id id] database
+
+action:
+\t--add
+\t-a\t\tadd entry to database
+\t\t\t\t(information is read from standard input)
+\t--list
+\t-l\t\tlist entry/entries from database
+\t--delete
+\t-d\t\tdelete entry from database
+\t--read
+\t-r\t\tread information from standard input
+
+target:
+\tstatus\t\tstatus messages
+\tverbose\t\tverbose messages
+
+id:
+\t--id
+\t-i\t\tclient_session_id
+
+\tdatabase\tSQLite database file
+\t--help
+\t-h\t\tprint this help screen""" %(sys.argv[0])
+
+def read_status_messages(dba, sep = ','):
+    while 1:
+        line = sys.stdin.readline().strip()
+        if line:
+            message_array = line.split(sep)
+
+            cs_id = int(message_array[0].strip())
+            timestamp = message_array[1].strip().split(' ')
+            date = timestamp[0]
+            time = timestamp[1]
+            num_peers = int(message_array[2].strip())
+            dht = int(message_array[3].strip())
+            download_speed = int(message_array[4].strip())
+            upload_speed = int(message_array[5].strip())
+            download_size = int(message_array[6].strip())
+            upload_size = int(message_array[7].strip())
+            eta_string_array = re.split('[dhms]', message_array[8].strip())
+            eta_string_array.remove('')
+            eta = []
+            for i in range(0, len(eta_string_array)):
+                eta.append(int(eta_string_array[i]))
+            for i in range(len(eta_string_array), 4):
+                eta.insert(0, 0)
+
+            dba.add_status_message_date_time(cs_id, date, time,
+                           num_peers, dht, download_speed,
+                           upload_speed, download_size, upload_size, eta)
+        else:
+            break
+
+def read_verbose_messages(dba, sep = ','):
+    while 1:
+        line = sys.stdin.readline().strip()
+        if line:
+            message_array = line.split(sep)
+
+            cs_id = int(message_array[0].strip())
+            timestamp = message_array[1].strip().split(' ')
+            date = timestamp[0]
+            time = timestamp[1]
+            peer_ip = message_array[2].strip()
+            peer_port = int(message_array[3].strip())
+            message_type = int(message_array[4].strip())
+            index = int(message_array[5].strip())
+            begin = int(message_array[6].strip())
+            length = int(message_array[7].strip())
+            listen_port = int(message_array[8].strip())
+
+            dba.add_verbose_message_date_time(cs_id, date, time,
+                           peer_ip, peer_port, message_type,
+                           index, begin, length, listen_port)
+        else:
+            break
+
+def main():
+    """
+    Command line interface for database handling. Allows insertion,
+        deletion and selection of rows in status_messages and verbose_messages
+        tables.
+    If id == -1, all rows in target table are deleted/selected.
+    Uses getopt for command line parsing.
+    Last argument must be a database file.
+    Please check README for details and running examples.
+    """
+
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "ha:l:d:r:i:s:", ["help",
+            "add=", "list=", "delete=", "read=", "id=", "separator="])
+    except getopt.GetoptError, err:
+        print str(err)
+        usage()
+        sys.exit(2)
+
+    action = None
+    target = None
+    id = None
+    sep = None
+
+    for o, a in opts:
+        if o in ("-h", "--help"):
+            usage()
+            sys.exit(0)
+        elif o in ("-a", "--add"):
+            action = "add"
+            target = a
+        elif o in ("-d", "--delete"):
+            action = "delete"
+            target = a
+        elif o in ("-l", "--list"):
+            action = "list"
+            target = a
+        elif o in ("-r", "--read"):
+            action = "read"
+            target = a
+        elif o in ("-i", "--id"):
+            try:
+                id = int(a)
+            except TypeError, err:
+                print str(err)
+                sys.exit(2)
+        elif o in ("-s", "--sep"):
+            sep = a
+        else:
+            assert False, "unhandled option"
+
+    # no database file passed as argument
+    if len(args) != 1:
+        print "Error: no database file passed as argument."
+        sys.exit(2)
+    database = args[0]
+
+    if action == None:
+        print "Error: no action specified."
+        sys.exit(2)
+
+    if target != "status" and target != "verbose":
+        print "Error: invalid target", target, "."
+        sys.exit(2)
+
+    if id != None and (action == "add" or action == "read"):
+        print "Error:", action, "action doesn't use an id field."
+        sys.exit(2)
+
+    if id == None and (action == "delete" or action == "list"):
+        print "Error: no id for", action, "action."
+        sys.exit(2)
+
+    if sep != None and action != "read":
+        print "Error:", action, "action doesn't use a separator argument."
+        sys.exit(2)
+
+    dba = access.SQLiteDatabaseAccess()
+    dba.connect(database)
+
+    if target == "status":
+        if action == "add":
+            print "client session id: ",
+            cs_id = int(sys.stdin.readline().strip())
+            print "timestamp (YYYY-MM-DD HH:MM:SS.ss): ",
+            timestamp = sys.stdin.readline().strip().split(' ')
+            date = timestamp[0]
+            time = timestamp[1]
+            print "number of peers: ",
+            num_peers = int(sys.stdin.readline().strip())
+            print "dht: ",
+            dht = int(sys.stdin.readline().strip())
+            print "current download speed (KB/s): ",
+            download_speed = int(sys.stdin.readline().strip())
+            print "current upload speed (KB/s): ",
+            upload_speed = int(sys.stdin.readline().strip())
+            print "download size (bytes): ",
+            download_size = int(sys.stdin.readline().strip())
+            print "upload size (bytes): ",
+            upload_size = int(sys.stdin.readline().strip())
+            print "eta (XdYhZmWs; e.g. 1d12h34m12s): ",
+            eta_string_array = re.split('[dhms]', sys.stdin.readline().strip())
+            eta_string_array.remove('')
+            eta = []
+            for i in range(0, len(eta_string_array)):
+                eta.append(int(eta_string_array[i]))
+            for i in range(len(eta_string_array), 4):
+                eta.insert(0, 0)
+
+            dba.add_status_message(cs_id, date, time, num_peers, dht, download_speed, upload_speed, download_size, upload_size, eta)
+
+        if action == "delete":
+            dba.delete_status_messages(id)
+
+        if action == "list":
+            dba.show_status_messages(id)
+
+        if action == "read":
+            read_status_messages(dba, sep)
+
+    if target == "verbose":
+        if action == "add":
+            print "client session id: ",
+            cs_id = int(sys.stdin.readline().strip())
+            print "timestamp (YYYY-MM-DD HH:MM:SS.ss): ",
+            timestamp = sys.stdin.readline().strip().split(' ')
+            date = timestamp[0]
+            time = timestamp[1]
+            print "peer IP address (X.Y.Z.T): ",
+            peer_ip = sys.stdin.readline().strip()
+            print "peer port: ",
+            peer_port = int(sys.stdin.readline().strip())
+            print "message_type (0, 1, 2, 3, 4, 5, 6): ",
+            message_type = int(sys.stdin.readline().strip())
+            print "index: ",
+            index = int(sys.stdin.readline().strip())
+            print "begin: ",
+            begin = int(sys.stdin.readline().strip())
+            print "length: ",
+            length = int(sys.stdin.readline().strip())
+            print "listen_port: ",
+            listen_port = int(sys.stdin.readline().strip())
+
+            dba.add_verbose_messages_date_time(cs_id, date, time,
+                           peer_ip, peer_port, message_type, index,
+                           begin, length, listen_port)
+
+        if action == "delete":
+            dba.delete_verbose_messages(id)
+
+        if action == "list":
+            dba.show_verbose_messages(id)
+
+        if action == "read":
+            read_verbose_messages(dba, sep)
+
+
+if __name__ == "__main__":
+    sys.exit(main())