예제 #1
0
    def _process_request(self, msg, addr):
        msg = msg.decode("utf-8")
        tokens = msg.split()

        if tokens[1] == "JOIN":
            self.routing_table.add(tokens[2], tokens[3])
            response = query_builder("JOINOK", ["0"])
            udp_send_recv(addr[0], addr[1], response, recieve=False)

        elif tokens[1] == "LEAVE":
            for node in self.routing_table.get():
                if node[1] == tokens[3]:
                    self.routing_table.remove(node)
                    break
            response = query_builder("LEAVEOK", ["0"])
            udp_send_recv(addr[0], addr[1], response, recieve=False)

        elif tokens[1] == "SER":
            hops = int(tokens[5])
            files_found, file_names = search_file(tokens[4])

            if files_found > 0:
                response = query_builder("SEROK", [files_found, cfg.FlaskServer['ip'], cfg.FlaskServer['port'], hops,
                                                   file_names])
                # time.sleep(random.randint(1, 100) / 100)
                udp_send_recv(tokens[2], tokens[3], response, recieve=False)

            elif hops > 0:
                request = query_builder("SER", [tokens[2], tokens[3], tokens[4], hops - 1])
                for node in self.routing_table.get():
                    udp_send_recv(node[0], node[1], request, recieve=False)

        elif tokens[1] == "SEROK":
            pretty_print_message_to_cli(
                "Files Found: " + " ".join(tokens[6:]) + " | Flask IP: " + tokens[3] + " | Flask Port: " + tokens[4])
예제 #2
0
    def _process_request(self, msg, addr):
        msg = msg.decode("utf-8")
        tokens = msg.split()

        if tokens[1] == "JOIN":
            self.routing_table.add(tokens[2], tokens[3])
            response = query_builder("JOINOK", ["0"])
            udp_send_recv(addr[0], addr[1], response, recieve=False)

        elif tokens[1] == "LEAVE":
            for node in self.routing_table.get():
                if node[1] == tokens[3]:
                    self.routing_table.remove(node)
                    break
            response = query_builder("LEAVEOK", ["0"])
            udp_send_recv(addr[0], addr[1], response, recieve=False)

        elif tokens[1] == "SER":
            hops = int(tokens[-1])
            file_name = " ".join(tokens[4:-1])
            files_found, file_names = search_file(file_name)

            if files_found > 0:
                response = query_builder("SEROK", [
                    files_found, cfg.FlaskServer['ip'],
                    cfg.FlaskServer['port'], hops, file_names
                ])
                udp_send_recv(tokens[2], tokens[3], response, recieve=False)

            elif hops > 0:
                request = query_builder(
                    "SER", [tokens[2], tokens[3], file_name, hops - 1])
                for node in self.routing_table.get():
                    udp_send_recv(node[0], node[1], request, recieve=False)

        elif tokens[1] == "SEROK":
            dir = cfg.Application['dir']
            films = " ".join(tokens[6:]).strip()

            self.lock.acquire()
            f = open(f"{dir}/film_details.txt", "a")
            file1 = open(f"{dir}/film_details.txt")

            for film in films.split(','):
                found = False
                for line in file1.readlines():
                    if film in line:
                        found = True
                if not found:
                    print(f"\t* {film}")
                    f.write(f"{film}|{tokens[3]}|{tokens[4]}\n")

            f.close()
            file1.close()
            self.lock.release()
def search_file(filename, local_search=False):
    file_name = filename.lower().split(" ")
    file_found = False
    file_names = []
    dir = cfg.Application['dir']
    if os.path.exists(dir):
        available_files = os.listdir(dir)
        for file in available_files:
            file_tokens = file.lower().split(" ")

            for token in file_name:
                if token not in file_tokens:
                    break
            else:
                file_found = True
                file_names.append(file)

    if local_search:
        if file_found:
            print(">>>>> File Found in the Local Repository")
        else:
            dir = cfg.Application['dir']
            f = open(f"{dir}/film_details.txt", "w")
            f.truncate()
            f.close()
            ip = cfg.UdpServer['ip']
            port = cfg.UdpServer['port']
            request = query_builder("SER",
                                    [ip, port, filename, 3])  #NO of HOPS = 3
            return udp_send_recv(ip, port, request, recieve=False)
    else:
        return file_found, ",".join(file_names)
예제 #4
0
 def unreg_from_bs(self):
     query = query_builder("UNREG",
                           data=[self.udp_ip, self.udp_port, self.username])
     res = udp_send_recv(self.bs_ip, self.bs_port, query)
     try:
         res_type, res = query_parser(res)
     except Exception as e:
         pass
예제 #5
0
 def disconnect_from_network(self):
     for ip, port in self.routing_table.get():
         query = query_builder("LEAVE", data=[self.udp_ip, self.udp_port])
         data = udp_send_recv(ip, port, query)
         try:
             res_type, data = query_parser(data)
         except Exception as e:
             print("Error:", str(e))
         else:
             if res_type == "LEAVEOK":
                 pass
예제 #6
0
 def connect_to_network(self):
     for ip, port in self.routing_table.get():
         query = query_builder("JOIN", data=[self.udp_ip, self.udp_port])
         data = udp_send_recv(ip, port, query)
         try:
             res_type, data = query_parser(data)
         except Exception as e:
             print("Error:", str(e))
             self.routing_table.remove((ip, port))
         else:
             if res_type == "JOINOK":
                 pass
예제 #7
0
    def reg_in_bs(self):

        query = query_builder("REG",
                              data=[self.udp_ip, self.udp_port, self.username])
        data = udp_send_recv(self.bs_ip, self.bs_port, query)

        try:
            res_type, data = query_parser(data)
        except Exception as e:
            print("Error:", str(e))
            sys.exit("Exiting, Couldn't connect to BS")
        else:
            if res_type == "REGOK":
                for i in range(0, len(data), 2):
                    self.routing_table.add(data[i], data[i + 1])
            else:
                print("Error: Invalid response from BS")
                sys.exit("Exiting, Couldn't connect to BS")
예제 #8
0
import random
import os
import time
import sys
from utils import query_builder

with open("demo.log", "w") as f1:
    f1.truncate()

args = sys.argv[1:]
nodeId = int(args[0])
query = " ".join(args[1:])
port = 5500 + nodeId

request = query_builder("SER", ["127.0.1.1", port, query, 3]).decode('utf-8')
command = f"echo '{request}' | nc -u 127.0.1.1 {port} &"

os.system(command)
time.sleep(5)

logs = open("demo.log").readlines()
os.system("kill -9 $(ps -aux | grep  '[n]c -u 127.0.1.1' | awk '{print $2}')")

start_time = 0
end_time = 0
no_requests = 0
no_forwards = 0
no_resolves = 0
min_hops = 3

nodes_got_messages = []
예제 #9
0
    def _process_request(self, msg, addr):
        msg = msg.decode("utf-8")
        tokens = msg.split()

        if tokens[1] == "JOIN":
            logging.info("Request recieved to Join network from node%s to %s", tokens[3][-1], self.name)
            self.routing_table.add(tokens[2], tokens[3])
            response = query_builder("JOINOK", ["0"])
            udp_send_recv(addr[0], addr[1], response, recieve=False)

        elif tokens[1] == "LEAVE":
            logging.info("Request recieved to leave network from node%s to %s", tokens[3][-1], self.name)
            for node in self.routing_table.get():
                if node[1] == tokens[3]:
                    self.routing_table.remove(node)
                    break
            response = query_builder("LEAVEOK", ["0"])
            udp_send_recv(addr[0], addr[1], response, recieve=False)

        elif tokens[1] == "SER":
            hops = int(tokens[-1])
            file_name = " ".join(tokens[4:-1])
            if hops==3:
                logging.info("Request recieved to start search film %s from node%s to %s at time %s", file_name, tokens[3][-1], self.name, str(time.time()))
                #logging.info("%s Started %s at time %s", self.name, tokens[4], str(time.time()))
            else:
                logging.info("Request recieved to search film %s from node%s to %s", file_name, tokens[3][-1], self.name)
                #logging.info("%s Requested %s", self.name, tokens[4])
            files_found, file_names = search_file(file_name)

            if files_found > 0:
                logging.info("Request resolved for film %s by %s after hop count of %s", file_name,  self.name, 3-hops)
                response = query_builder("SEROK", [files_found, cfg.FlaskServer['ip'], cfg.FlaskServer['port'], hops, file_names])
                udp_send_recv(tokens[2], tokens[3], response, recieve=False)

            elif hops > 0:
                request = query_builder("SER", [tokens[2], tokens[3], file_name, hops-1])
                for node in self.routing_table.get():
                    udp_send_recv(node[0], node[1], request, recieve=False)
                    logging.info("Request for the film %s is Forwarded by %s to node%s", file_name, self.name, node[1][-1])
        
        elif tokens[1] == "SEROK":
            dir = cfg.Application['dir'] 
            films = " ".join(tokens[6:]).strip()
            logging.info("Response got for film %s by node%s to %s at time %s", films, tokens[4][-1], self.name, str(time.time()))

            self.lock.acquire()
            f = open(f"{dir}/film_details.txt", "a")
            file1 = open(f"{dir}/film_details.txt")

            for film in films.split(','):
                found = False
                for line in file1.readlines():
                    if film in line:
                        found = True
                if not found:
                    print(f"\t* {film}")
                    f.write(f"{film}|{tokens[3]}|{tokens[4]}\n")
                    
            f.close()
            file1.close()
            self.lock.release()