From 09079cb2990513b6092d4e98c8154291e3c461a1 Mon Sep 17 00:00:00 2001 From: P2P-Next Date: Sat, 16 Oct 2010 22:21:00 +0300 Subject: [PATCH] server: added GET_OUTPUT msg --- autorun/Util.py | 8 +-- autorun/server/BTClientsControl.py | 29 ++++++++--- autorun/server/Client.py | 83 +++++++++++------------------- autorun/server/DataControl.py | 81 +++++++++++++++++++++++++++++ autorun/server/Server.py | 25 ++++----- 5 files changed, 149 insertions(+), 77 deletions(-) create mode 100644 autorun/server/DataControl.py diff --git a/autorun/Util.py b/autorun/Util.py index 02293b6..b49cf01 100644 --- a/autorun/Util.py +++ b/autorun/Util.py @@ -9,14 +9,13 @@ SERVER_PORT = 10004 SERVER_HOST = "10.1.9.1" import os -def get_sessions_file_path(): +def get_info_dir_path(): dirpath = os.environ['HOME']+"/"+".autorun/" if not os.path.exists(dirpath): os.mkdir(dirpath) - path = dirpath +"sessions.txt" # FIND A BETTER NAME!!! - return path + return dirpath -SESSIONS_FILE = get_sessions_file_path() +INFO_DIR = get_info_dir_path() BUFFER_SIZE = 4096 """ Message types: client -> server """ @@ -53,6 +52,7 @@ TRIBLER = "tribler" TRANSMISSION = "transmission" HRKTORRENT = "hrktorrent" NEXTSHARE = "next-share" + #status line TIMESTAMP = "timestamp" DL_SIZE = "download_size" diff --git a/autorun/server/BTClientsControl.py b/autorun/server/BTClientsControl.py index e0b9302..1bdf9b8 100644 --- a/autorun/server/BTClientsControl.py +++ b/autorun/server/BTClientsControl.py @@ -3,6 +3,7 @@ import signal import logging from Util import * +from DataControl import * from BitTorrentClientRun import * from HrktorrentRun import * from TransmissionRun import * @@ -18,13 +19,13 @@ class BTClientsControl: """ processes_fd = {} # keeps lists of file descriptors for each process processes_info = {} # keeps lists of BT clients name, torrent name and status log name for each process - + logger = None def __init__(self): logging.basicConfig(level = logging.DEBUG) self.logger = logging.getLogger('autorun.BTClientsControl') - self.logger.setLevel(logging.DEBUG) + self.logger.setLevel(logging.ERROR) def start_bt_client(self, bt_client_data): """ Starts a process for a BitTorrent client and returns its pid. @@ -32,6 +33,9 @@ class BTClientsControl: """ btcr = None + if type(bt_client_data) != type({}) or len(bt_client_data) == 0: + self.error_msg = "Wrong parameters" + return -1 if bt_client_data[CLIENT] == TRANSMISSION: btcr = TransmissionRun(bt_client_data[BASE_DIR]) @@ -58,19 +62,28 @@ class BTClientsControl: bt_client_data[TORRENT], bt_client_data[OUT_DIR] + "/" + bt_client_data[OUT_FILE]] - self.logger.debug(" started client with pid = " + str(pid)) - return pid - + self.logger.debug(" started client with pid = " + str(pid)) except Exception, ex: self.logger.error(" Exception occured: " + str(ex)) self.error_msg = "Error occurred when starting the BT Client: " + str(ex) +"." return -1 + # save transfer information + try: + save_download_info(bt_client_data, pid) + self.logger.debug(" saved info for client with pid = " + str(pid)) + except Exception,ex: + self.logger.error(" Exception occured: " + str(ex)) + self.error_msg = "Error occurred when starting the BT Client: " + "failed to save transfer info" +"." + self.stop_bt_client(pid) + + return pid + def stop_bt_client(self, pid): """ Stops a BT client by killing it.""" self.error_msg = "" - try: + try: int_pid = int(pid) if self.check_pid(pid) == -1: return -1 @@ -78,7 +91,7 @@ class BTClientsControl: os.wait() self.processes_fd[int_pid][0].close() self.processes_fd[int_pid][1].close() - + del self.processes_fd[int_pid] del self.processes_info[int_pid] @@ -90,7 +103,7 @@ class BTClientsControl: def resume_bt_client(self, pid): self.error_msg = "" - try: + try: if self.check_pid(int(pid)) == -1: return -1 os.kill(int(pid),signal.SIGCONT) diff --git a/autorun/server/Client.py b/autorun/server/Client.py index c20feba..f2f9a0a 100644 --- a/autorun/server/Client.py +++ b/autorun/server/Client.py @@ -30,7 +30,7 @@ class MySocket: if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent - + def send_command(self, msg_type, config_data): self.send_pickled_data((msg_type, config_data)) print "am trimis ", msg_type @@ -67,22 +67,22 @@ class MySocket: msg = msg + chunk if len(chunk) < BUFFER_SIZE: break - + dd = pickle.loads(msg) #print "am primit mesajul: ", dd return dd # send a pickled dictionary def send_dict(self, data): - dumped_data = pickle.dumps(data) + dumped_data = pickle.dumps(data) self.send_msg(dumped_data) +#end class + + # basic test that starts and stops a BT Client def test_all_commands(torrent_file): - s = MySocket() - s.connect(SERVER_HOST, SERVER_PORT) torrent_name = torrent_file[(torrent_file.rfind("/")+1):torrent_file.find(".torrent")]; - start_data_tribler = { CLIENT: TRIBLER, PORT:10150, BASE_DIR:"/home/p2p/p2p-clients/tribler", @@ -134,62 +134,39 @@ def test_all_commands(torrent_file): UP_LIMIT: 250 } - #print s.send_command(GET_OUTPUT, "") - - response = s.send_command(START_MSG, start_data_nextshare) - print response - pid1 = response[1] - print pid1 - + print "-----------------Testing start+stop------------------" + pid1 = test_start(start_data_nextshare) + time.sleep(2) + test_command(GET_OUTPUT, pid1) time.sleep(7) - s = MySocket() - s.connect(SERVER_HOST, SERVER_PORT) - response = s.send_command(SUSPEND_MSG,pid1) - print response - - time.sleep(20) - - s = MySocket() - s.connect(SERVER_HOST, SERVER_PORT) - response = s.send_command(RESUME_MSG,pid1) - print response + test_command(STOP_MSG,pid1) + print "-----------------End Testing start+stop--------------" - time.sleep(17) - - s = MySocket() - s.connect(SERVER_HOST, SERVER_PORT) - response = s.send_command(STOP_MSG,pid1) - print response - """response = s.send_command(START_MSG, start_data_transmission) - print response - pid2 = response[1] - print pid2 - - s = MySocket() - s.connect(SERVER_HOST, SERVER_PORT) - response = s.send_command(GET_CLIENTS,"") - print response - """ - """time.sleep(3) - - response = s.send_command(START_MSG, start_data_hrktorrent) - print response - pid1 = response[1] - print pid1 - - + +def test_start(msg_data): s = MySocket() s.connect(SERVER_HOST, SERVER_PORT) - response = s.send_command(STOP_MSG, pid2) + response = s.send_command(START_MSG, msg_data) print response - - + pid = response[1] + print pid + return pid + +def test_command(type, msg_data): s = MySocket() s.connect(SERVER_HOST, SERVER_PORT) - response = s.send_command(STOP_MSG, pid1) + if type == STOP_MSG: + response = s.send_command(STOP_MSG,msg_data) + elif type == SUSPEND_MSG: + response = s.send_command(SUSPEND_MSG,msg_data) + elif type == RESUME_MSG: + response = s.send_command(RESUME_MSG,msg_data) + elif type == GET_OUTPUT: + response = s.send_command(GET_OUTPUT,msg_data) + else: return print response - """ + def test_send_recv(): # test 1 diff --git a/autorun/server/DataControl.py b/autorun/server/DataControl.py new file mode 100644 index 0000000..e20235d --- /dev/null +++ b/autorun/server/DataControl.py @@ -0,0 +1,81 @@ +""" +Methods for controlling BitTorrent transfers' related data. +@author Adriana Draghici adriana.cdraghici@gmail.com +""" + +import sys,os +from Util import * +from time import time, localtime, strftime + +def save_download_info(data, client_id): + try: + filename = strftime("%Y%m%d_", localtime()) + str(client_id); + f = open(INFO_DIR + filename, "w") + f.write(strftime("%d-%b-%Y %H:%M:%S", localtime()) +"\n") + for k in data.keys(): + f.write(str(k)+":"+str(data[k])+"\n") + f.close() + except Exception,ex: + raise + +def archive_files(): + + pass + +def cleanup_files(): + + pass + +def get_download_info(client_id): + info_dict = {} + try: + file_list = os.listdir(INFO_DIR) + int_date = 0 + info_file_name = "" + client_id_str = str(client_id) + for f in file_list: + if f.find("_"+client_id_str) > -1: + parts = f.split('_') + if len(parts) != 2: + print "Wrong file name " + INFO_DIR + name + "." + return [] + if int_date < int(parts[0]): # consider only the newest file + info_file_name = f + int_date = int(parts[0]) + + if info_file_name == "": + print "No file for id " + client_id + return "Could not load information for transfer id "+ client_id + ". Might be wrong id." + + f = open(INFO_DIR + info_file_name) #reading mode + f.readline() #ignore first line(with the date) + lines = f.readlines() + for line in lines: + parts = line.strip().split(':') + if len(parts) != 2: + print "Wrong format for file " + INFO_DIR + name + "." + return [] + info_dict[parts[0]] = parts[1] + + f.close() + except Exception, ex: + print "Error when retrieving transfer info: " + str(ex) + return "Error retrieving transfer info" + + if CLIENT not in info_dict or TORRENT not in info_dict: + print "Wrong format for file " + INFO_DIR + name + "." + return [] + info_list = [info_dict[CLIENT],info_dict[TORRENT]] + if LOG_DIR in info_dict: + info_list.append((info_dict[LOG_DIR], LOG_DIR)) + if OUT_DIR in info_dict: + info_list.append((info_dict[OUT_DIR], OUT_DIR)) + if OUT_FILE in info_dict: + info_list.append((info_dict[OUT_FILE], OUT_FILE)) + if LOG_FILE in info_dict: + info_list.append((info_dict[LOG_FILE], LOG_FILE)) + return info_list + + + + diff --git a/autorun/server/Server.py b/autorun/server/Server.py index a16e1bd..bed5717 100644 --- a/autorun/server/Server.py +++ b/autorun/server/Server.py @@ -11,7 +11,7 @@ from daemon import Daemon from Util import * from Util import SERVER_PORT from BTClientsControl import BTClientsControl - +from DataControl import * class ServerDaemon(Daemon): """ Server class @@ -83,22 +83,23 @@ class ServerDaemon(Daemon): try: self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.logger.debug( " host ip = %s, port = %s"%(ip,SERVER_PORT)) - + self.serversocket.bind((ip,SERVER_PORT)); self.serversocket.listen(10) #max 10 requests self.set_linger(self.serversocket,1, 0) except Exception, e: self.logger.error(" Exception occured while connecting: " + str(e)) return + while(1): try: self.logger.debug(" accepting connections") (clientsock, address) = self.serversocket.accept(); self.logger.debug(" accepted connection from " +str(address)) msg = self.recv_pickled_data(clientsock) - + response = '' - + if msg[0] == START_MSG: bt_client_data = msg[1] response = btcc.start_bt_client(bt_client_data) #returns client_pid @@ -110,26 +111,26 @@ class ServerDaemon(Daemon): #except Exception: # err_msg = "Client started but transfer info could not be saved." elif msg[0] == STOP_MSG: - client_pid = msg[1] - response = btcc.stop_bt_client(client_pid) + response = btcc.stop_bt_client(msg[1]) if response < -1: err_msg = btcc.get_error_msg() else: response = "" elif msg[0] == RESUME_MSG: - client_pid = msg[1] - response = btcc.resume_bt_client(client_pid) + response = btcc.resume_bt_client(msg[1]) if response < -1: err_msg = btcc.get_error_msg() else: response = "" - + elif msg[0] == SUSPEND_MSG: - client_pid = msg[1] - response = btcc.suspend_bt_client(client_pid) + response = btcc.suspend_bt_client(msg[1]) if response < -1: err_msg = btcc.get_error_msg() else: response = "" - + elif msg[0] == GET_OUTPUT: + response = get_download_info(msg[1]) + if type(response) != type([]): + err_msg = response else: err_msg = "Error: wrong message type"; -- 2.20.1