Example #1
0
def ProxyClientCommand(sock, server_addr, server_port, cache, max_age_in_sec):
    """Receives a command from a client and forwards it to a server:port.

    A single command is read from `sock`. That command is passed to the specified
    `server`:`port`. The response from the server is then passed back through
    `sock`.

    Args:
      sock: A TCP socket that connects to the client.
      server_addr: A string with the name of the server to forward requests to.
      server_port: An int from 0 to 2^16 with the port the server is listening on.
      cache: A KeyValueStore object that maintains a temorary cache.
      max_age_in_sec: float. Cached values older than this are re-retrieved from
        the server.
    """

    command_line = library.ReadCommand(sock)  # obtain command from user
    command, _, _ = library.ParseCommand(command_line)
    if command == "GET" or command == "get":  # if command involves cache
        cached_result = cache.GetValue(command_line, max_age_in_sec)
        if cached_result is not None:  # if command was previously utilized
            print("Cache utilized")
            result = cached_result
        else:
            result = ForwardCommandToServer(command_line, server_addr,
                                            server_port)
            cache.StoreValue(command_line,
                             result)  # cache result for future use
    else:
        result = ForwardCommandToServer(command_line, server_addr, server_port)

    MirrorMessage(sock, result)  # output message to client
Example #2
0
def ProxyClientCommand(sock, server_addr, server_port, cache):
    """Receives a command from a client and forwards it to a server:port.
        
        A single command is read from `sock`. That command is passed to the specified
        `server`:`port`. The response from the server is then passed back through
        `sock`.
        
        Args:
        sock: A TCP socket that connects to the client.
        server_addr: A string with the name of the server to forward requests to.
        server_port: An int from 0 to 2^16 with the port the server is listening on.
        cache: A KeyValueStore object that maintains a temporary cache.
        max_age_in_sec: float. Cached values older than this are re-retrieved from
        the server.
        """

    command = library.ReadCommand(sock)
    result = CheckCachedResponse(command, cache)

    if result:
        if result[1]:
            msg = result[1]
        else:
            msg = ForwardCommandToServer(command, server_addr, server_port)
            if msg != "Not Found.":
                cache.StoreValue(result[0], msg)
    else:
        msg = ForwardCommandToServer(command, server_addr, server_port)

    sock.send('%s\n' % msg)
def ProxyClientCommand(client_sock, server_addr, server_port, cache):
    """Receives a command from a client and forwards it to a server:port.

    A single command is read from `sock`. That command is passed to the specified
    `server`:`port`. The response from the server is then passed back through
    `sock`.

    Args:
    sock: A TCP socket that connects to the client.
    server_addr: A string with the name of the server to forward requests to.
    server_port: An int from 0 to 2^16 with the port the server is listening on.
    cache: A KeyValueStore object that maintains a temorary cache.
    max_age_in_sec: float. Cached values older than this are re-retrieved from
      the server.
    """

    ###########################################
    #TODO: Implement ProxyClientCommand
    ###########################################
    command_line = library.ReadCommand(client_sock)
    response = CheckCachedResponse(command_line, cache)
    cmd, name, text = library.ParseCommand(command_line)
    if not response:
        # If there is no response from the proxy, go to main server else get response from cache
        response = ForwardCommandToServer(command_line, server_addr,
                                          server_port)
        if cmd == "GET":
            # Only on the GET commands do we store the value in the cache if there was no response from the proxy
            cache.StoreValue(name, response)

    client_sock.sendall('%s\n' % response)
Example #4
0
def ProxyClientCommand(sock, server_addr, server_port, cache):
    """Receives a command from a client and forwards it to a server:port.

    A single command is read from `sock`. That command is passed to the specified
    `server`:`port`. The response from the server is then passed back through
    `sock`.

    Args:
      sock: A TCP socket that connects to the client.
      server_addr: A string with the name of the server to forward requests to.
      server_port: An int from 0 to 2^16 with the port the server is listening on.
      cache: A KeyValueStore object that maintains a temorary cache.
      max_age_in_sec: float. Cached values older than this are re-retrieved from
        the server.
    """
    command_line = library.ReadCommand(sock)
    cmd, name, text = library.ParseCommand(command_line)
    result = ''
    
    # Update the cache for PUT commands but also pass the traffic to the server.
    # GET commands can be cached.
    msg_to_server = (command_line, server_addr, server_port)
    if cmd == 'PUT':
        result = PutCommand(name, text, cache, msg_to_server)
    elif cmd == 'GET':
        result = GetCommand(name, cache, msg_to_server)
    elif cmd == 'DUMP':
        result = DumpCommand(msg_to_server)
    else:
        result = f'Unknown command {cmd}'
    
    SendText(sock, result)
def main():
    # Store all key/value pairs in here.
    database = library.KeyValueStore()
    # The server socket that will listen on the specified port. If you don't
    # have permission to listen on the port, try a higher numbered port.
    server_sock = library.CreateServerSocket(LISTENING_PORT)
    
    # Handle commands indefinitely. Use ^C to exit the program.
    while True:
        # Wait until a client connects and then get a socket that connects to the
        # client.
        client_sock, (address, port) = library.ConnectClientToServer(server_sock)
        print('Received connection from %s:%d' % (address, port))
        # Read a command.
        command_line = library.ReadCommand(client_sock)
        command, name, text = library.ParseCommand(command_line)
        
        # Execute the command based on the first word in the command line.
        if command == 'PUT':
            result = PutCommand(name, text, database)
        elif command == 'GET':
            result = GetCommand(name, database)
        elif command == 'DUMP':
            result = DumpCommand(database)
        else:
            result = 'Unknown command %s' % command
        
        SendText(client_sock, result)
        client_sock.close()
def main():
    # Store all key/value pairs in here.
    database = library.KeyValueStore()
    # The server socket that will listen on the specified port. If you don't
    # have permission to listen on the port, try a higher numbered port.
    server_sock = library.CreateServerSocket(LISTENING_PORT)

    # It will now handle it completely.
    while True:
        # Wait until a client connects and then get a socket that connects to the
        # client.
        client_sock, (address, port) = library.ConnectClientToServer(
            server_sock, LISTENING_PORT)
        print('Received connection from %s:%d' % (address, port))

        # It now reads the command and executes it.
        command_line = library.ReadCommand(client_sock)
        command, name, text = library.ParseCommand(command_line)

        if command == 'PUT':
            result = PutCommand(name, text, database)
        elif command == 'GET':
            result = GetCommand(name, database)
        elif command == 'DUMP':
            result = DumpCommand(database)
        else:
            SendText(client_sock, 'Unknown command %s' % command)

        SendText(client_sock, result)

        # We're done with the client, so clean up the socket.

        #################################
        client_sock.close()
Example #7
0
def ProxyClientCommand(sock, server_addr, server_port, cache):
  """Receives a command from a client and forwards it to a server:port.

  A single command is read from `sock`. That command is passed to the specified
  `server`:`port`. The response from the server is then passed back through
  `sock`.

  Args:
    sock: A TCP socket that connects to the client.
    server_addr: A string with the name of the server to forward requests to.
    server_port: An int from 0 to 2^16 with the port the server is listening on.
    cache: A KeyValueStore object that maintains a temorary cache.
    max_age_in_sec: float. Cached values older than this are re-retrieved from
      the server.
  """
    command_line = library.ReadCommand(sock)
    cmd, name, text = library.ParseCommand(command_line)

    response = ForwardCommandToServer(command_line,server_addr,server_port)

    checkedResponse = CheckCachedResponse(command_line, cache):
    if checkedResponse == None:
        sock.send(response)
    else:
        sock.send(checkedResponse)
Example #8
0
def ForwardCommandToServer(command, server_addr, server_port):
    
    client_socket = library.CreateClientSocket(server_addr, server_port)
    client_socket.send(command + '\n')
    server_response = library.ReadCommand(client_socket)
    client_socket.close()

    return server_response + '\n'
Example #9
0
def ForwardCommandToServer(command, server_addr, server_port):
  s = library.CreateClientSocket(server_addr,server_port)
  s.sendall(command)
  data = library.ReadCommand(s)
  data=data.strip('/n')
  s.close()
  return data
  """Opens a TCP socket to the server, sends a command, and returns response.
Example #10
0
def main(records_file=None):
    # Store all key/value pairs in here.
    if records_file:
        try:
            database = library.KeyValueStore(fileName=records_file)
        except library.InvalidRecordFormatException as e:
            print(e)
            print("Initializing an empty database")
            database = library.KeyValueStore()
        except library.InvalidRecordTypeException as e:
            print(e)
            print("Initializing an empty database")
            database = library.KeyValueStore()
    else:
        database = library.KeyValueStore()
    # The server socket that will listen on the specified port. If you don't
    # have permission to listen on the port, try a higher numbered port.
    server_sock = library.CreateServerSocket(LISTENING_PORT)
    # Handle commands indefinitely. Use ^C to exit the program.
    try:
        while True:
            # Wait until a client connects and then get a socket that connects to the
            # client.
            client_sock, (address,
                          port) = library.ConnectClientToServer(server_sock)
            print('Received connection from %s:%d' % (address, port))

            # Read a command.
            command_line = library.ReadCommand(client_sock)
            command, name, text = library.ParseCommand(command_line)

            # Execute the command based on the first word in the command line.
            if command == 'PUT':
                result = PutCommand(name, text, database)
            elif command == 'GET':
                result = GetCommand(name, database)
            elif command == 'DUMP':
                result = DumpCommand(database)
            else:
                SendText(client_sock, 'Unknown command %s' % command)

            SendText(client_sock, result)

            # We're done with the client, so clean up the socket.
            client_sock.close()
    except KeyboardInterrupt:
        # Write records to a file, which can be restored later.
        # Close the server socket.
        server_sock.close()
        with open("server-records.txt", 'w') as fileHandle:
            fileHandle.write(str(database))
Example #11
0
def ForwardCommandToServer(command, server_addr, server_port):
    """Opens a TCP socket to the server, sends a command, and returns response.
        
        Args:
        command: A single line string command with no newlines in it.
        server_addr: A string with the name of the server to forward requests to.
        server_port: An int from 0 to 2^16 with the port the server is listening on.
        Returns:
        A single line string response with no newlines.
        """
    sock = library.CreateClientSocket(server_addr, server_port)
    sock.send('%s\n' % command)
    result = library.ReadCommand(sock)
    sock.close()
    return result.strip('\n')
Example #12
0
def ForwardCommandToServer(command, server_addr, server_port):
    """Opens a TCP socket to the server, sends a command, and returns response.

    Args:
      command: A single line string command with no newlines in it.
      server_addr: A string with the name of the server to forward requests to.
      server_port: An int from 0 to 2^16 with the port the server is listening on.
    Returns:
      A single line string response with no newlines.
    """
    socket = library.CreateClientSocket(server_addr, server_port)
    socket.send(command)

    # Wait to receive the data from the server socket.
    return library.ReadCommand(socket)
Example #13
0
def ForwardCommandToServer(command, server_addr, server_port):
    # """Opens a TCP socket to the server, sends a command, and returns response.
    #
    # Args:
    #   command: A single line string command with no newlines in it.
    #   server_addr: A string with the name of the server to forward requests to.
    #   server_port: An int from 0 to 2^16 with the port the server is listening on.
    # Returns:
    #   A single line string response with no newlines.
    # """

    ###################################################
    Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Socket.connect((server_addr, server_port))
    Socket.send(command)
    return library.ReadCommand(Socket)
Example #14
0
def ProxyClientCommand(sock, server_addr, server_port, cache):
    command_line = library.ReadCommand(sock)
    cmd, name, value = library.ParseCommand(command_line)

    if cmd == 'PUT':
        server_response = ForwardCommandToServer(command_line, server_addr, server_port)
        cache.StoreValue(name, server_response)

    elif (cmd == 'GET'):
        server_response = cache.GetValue(name)
        if server_response == None:
            server_response = ForwardCommandToServer(command_line, server_addr, server_port)

    else:
        server_response = ForwardCommandToServer(command_line, server_addr, server_port)

    sock.send(server_response)
def ProxyClientCommand(sock, server_addr, server_port, cache):

    command_line = library.ReadCommand(sock)
    command, name, text = library.ParseCommand(command_line)
    returning_str = ""

    if (command == "GET"):  #if GET, name might be in cache or not
        if (name in cache.keyvalue):
            timeElapsed = time.time() - (cache.keyvalue[name])[1]
            if (
                    timeElapsed < MAX_CACHE_AGE_SEC
            ):  #No problem with cached information if last cached time is less than 60 seconds.
                returning_text = (cache.keyvalue[name])[0].decode(
                ) + "     ( Returned from proxy)    "
                SendText(sock, returning_text)
            else:
                data = ForwardCommandToServer(
                    command_line, server_addr, server_port
                )  #If last cached time is more than 60 seconds, pull the info from main server
                cache.keyvalue[name] = [data, time.time()]
                sock.send(data + b"\n")
        else:  #if not found in cache, forward to the server. Server will handle KEY NOT FOUND error
            data = ForwardCommandToServer(command_line, server_addr,
                                          server_port)
            if (ServerFound(data) == True):
                cache.keyvalue[name] = [
                    data, time.time()
                ]  #cache the data only if server found the key
            sock.send(data + b"\n")

    elif (command == "PUT"):
        if (name == None or text == None):
            returning_str = "Key And Value both needed for PUT operation\n"
            SendText(sock, returning_str)
        else:
            returning_str = name + " = " + text
            ForwardCommandToServer(command_line, server_addr, server_port)
            SendText(sock, returning_str)

    elif (command == "DUMP"):  #command = "DUMP"
        data = ForwardCommandToServer(command_line, server_addr, server_port)
        sock.send(data + b"\n")
    else:
        SendText(sock, 'Unknown command %s' % command)
    return
Example #16
0
def ForwardCommandToServer(command, server_addr, server_port):
    """Opens a TCP socket to the server, sends a command, and returns response.

  Args:
    command: A single line string command with no newlines in it.
    server_addr: A string with the name of the server to forward requests to.
    server_port: An int from 0 to 2^16 with the port the server is listening on.
  Returns:
    A single line string response with no newlines.
  """

  ###################################################
  #TODO: Implement Function: WiP
    The_Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Socket.connect((server_addr, server_port))
    Socket.send(command)
    The_Response = library.ReadCommand(Socket)
    return The_Response
Example #17
0
def ForwardCommandToServer(command, server_addr, server_port):
    """Opens a TCP socket to the server, sends a command, and returns response.

    Args:
      command: A single line string command with no newlines in it.
      server_addr: A string with the name of the server to forward requests to.
      server_port: An int from 0 to 2^16 with the port the server is listening on.
    Returns:
      A single line string response with no newlines.
    """

    transfer_socket = library.CreateClientSocket(
        server_addr, server_port)  # connect to actual server
    transfer_socket.sendall(command.encode())  # transfer command to server
    result = library.ReadCommand(
        transfer_socket)  # obtain response from server
    transfer_socket.close()  # close server connection
    return result
Example #18
0
def ProxyClientCommand(sock, server_addr, server_port, cache):
    """Receives a command from a client and forwards it to a server:port.

    A single command is read from `sock`. That command is passed to the specified
    `server`:`port`. The response from the server is then passed back through
    `sock`.

    Args:
      sock: A TCP socket that connects to the client.
      server_addr: A string with the name of the server to forward requests to.
      server_port: An int from 0 to 2^16 with the port the server is listening on.
      cache: A KeyValueStore object that maintains a temorary cache.
      max_age_in_sec: float. Cached values older than this are re-retrieved from
        the server.
    """
    command_line = library.ReadCommand(sock)

    cmd, name, text = library.ParseCommand(command_line)

    if cmd == "GET":
        if cache.GetValue(name, MAX_CACHE_AGE_SEC):
            print('Key %s in the cache.' % name)
            sock.send("Key: {0}, Value: {1}\n".format(
                name, cache.GetValue(name, MAX_CACHE_AGE_SEC)))
            return

        # Get record from the server, and update the cache.
        serverResponse = ForwardCommandToServer(command_line, server_addr,
                                                server_port)
        cache.StoreValue(name, serverResponse)
    elif cmd == "PUT":
        print('Writing %s: %s to the cache' % (name, text))
        cache.StoreValue(name, text)
        serverResponse = ForwardCommandToServer(command_line, server_addr,
                                                server_port)
    elif cmd == "DUMP":
        serverResponse = ForwardCommandToServer(command_line, server_addr,
                                                server_port)
    else:
        return

    # Forward the server response to the client.
    print("Forwarding the response from the server to the client")
    sock.send(serverResponse)
def ForwardCommandToServer(command, server_addr, server_port):
    """Opens a TCP socket to the server, sends a command, and returns response.

    Args:
    command: A single line string command with no newlines in it.
    server_addr: A string with the name of the server to forward requests to.
    server_port: An int from 0 to 2^16 with the port the server is listening on.
    Returns:
    A single line string response with no newlines.
    """

    proxy_as_client = library.CreateClientSocket(server_addr, server_port)

    # proxy_as_client.sendto(command, (server_addr, server_port) )
    proxy_as_client.send(command)
    response_from_server = library.ReadCommand(proxy_as_client)
    # proxy_as_client.close()

    return response_from_server.strip()
def ProxyClientCommand(client_socket, server_addr, server_port, cache):
    """Receives a command from a client and forwards it to a server:port.
    
     A single command is read from `sock`. That command is passed to the specified
    `server`:`port`. The response from the server is then passed back through
    `sock`.

    Args:
        sock: A TCP socket that connects to the client.
        server_addr: A string with the name of the server to forward requests to.
        server_port: An int from 0 to 2^16 with the port the server is listening on.
        cache: A KeyValueStore object that maintains a temorary cache.
        max_age_in_sec: float. Cached values older than this are re-retrieved from
        the server.
    """
    # Get the client's request/command
    request = library.ReadCommand(client_socket)
    cmd, name, text = library.ParseCommand(request)

    # Forward the request to the server and retrieve response
    data = ForwardCommandToServer(request, server_addr, server_port)

    # print("Data is here : {}".format(data))
    if cmd == "PUT":
        if name not in cache.Names():
            cache.StoreValue(name, text)
            client_socket.sendall('%s\n' % data)
        else:
            print("Key", name, "already exists")

    elif cmd == "GET":
        if name not in cache.Names():
            print("Key ", name, " does not exist")
        else:
            cache.GetValue(name, MAX_CACHE_AGE_SEC)
            client_socket.sendall('%s\n' % data)

    elif cmd == "DUMP":
        cache.Keys()
        client_socket.sendall(data)

    client_socket.close()
Example #21
0
def ProxyClientCommand(sock, server_addr, server_port, cache, max_age_in_sec):
    """Receives a command from a client and forwards it to a server:port.

  A single command is read from `sock`. That command is passed to the specified
  `server`:`port`. The response from the server is then passed back through
  `sock`.

  Args:
    sock: A TCP socket that connects to the client.
    server_addr: A string with the name of the server to forward requests to.
    server_port: An int from 0 to 2^16 with the port the server is listening on.
    cache: A KeyValueStore object that maintains a temorary cache.
    max_age_in_sec: float. Cached values older than this are re-retrieved from
      the server.
  """

    ###########################################
    #TODO: Implement ProxyClientCommand
    ###########################################
    command_line = library.ReadCommand(sock)
    command, name, text = library.ParseCommand(command_line)

    if command == "GET" or command == "get":  #if get
        cached_result = cache.GetValue(command_line, max_age_in_sec)
        if cached_result is not None:
            print("Cache used")
            result = cached_result  #if post
        else:
            result = ForwardCommandToServer(command_line, server_addr,
                                            server_port)
            cache.StoreValue(command_line, result)
    elif (command == "PUT" or command == "put"):  #if put
        if (name == None or text == None):
            result = "Key and Value needed for PUT operation\n"
        else:
            result = ForwardCommandToServer(command_line, server_addr,
                                            server_port)
    elif (command == "DUMP" or command == "dump"):  #if dump
        result = ForwardCommandToServer(command_line, server_addr, server_port)
    else:
        result = "Invalid Operation\n"
    sock.send(result)
Example #22
0
def ForwardCommandToServer(msg_to_server):
    """Opens a TCP socket to the server, sends a command, and returns response.

    Args:
      msg_to_server: Contains the cmdline, server_addr, and server_port
    Returns:
      A single line string response with no newlines.
    """
    command_line, server_addr, server_port = msg_to_server
    client_socket = library.CreateClientSocket(server_addr, server_port)
    
    res = None

    try:
        # Relay command_line to server and return the response.
        client_socket.sendall(command_line.encode())
        res = library.ReadCommand(client_socket).strip('\n')

    finally:
        client_socket.close()
    
    return res
def ProxyClientCommand(sock, server_addr, server_port, cache):
    """
  Receives a command from a client and forwards it to a server:port.

  A single command is read from `sock`. That command is passed to the specified
  `server`:`port`. The response from the server is then passed back through
  `sock`.

  Args:
    sock: A TCP socket that connects to the client.
    server_addr: A string with the name of the server to forward requests to.
    server_port: An int from 0 to 2^16 with the port the server is listening on.
    cache: A KeyValueStore object that maintains a temorary cache.
    max_age_in_sec: float. Cached values older than this are re-retrieved from
      the server.
  """
    data = library.ReadCommand(sock)
    response = CheckCachedResponse(data, cache)
    if not response:
        result = ForwardCommandToServer(data, server_addr, server_port)
        sock.sendall((result + "\n").encode('utf-8'))
    else:
        sock.sendall((response + "\n").encode('utf-8'))
Example #24
0
def ProxyClientCommand(sock, server_addr, server_port, cache):

    command_line = library.ReadCommand(sock)
    response = CheckCachedResponse(command_line, cache, server_addr,
                                   server_port)
    sock.send(response)
Example #25
0
  A single command is read from `sock`. That command is passed to the specified
  `server`:`port`. The response from the server is then passed back through
  `sock`.

  Args:
    sock: A TCP socket that connects to the client.
    server_addr: A string with the name of the server to forward requests to.
    server_port: An int from 0 to 2^16 with the port the server is listening on.
    cache: A KeyValueStore object that maintains a temorary cache.
    max_age_in_sec: float. Cached values older than this are re-retrieved from
      the server.
  """

  ###########################################
  #TODO: Implement ProxyClientCommand
   Command_Line = library.ReadCommand(sock)
   Is_response = CheckCachedResponse(Command_Line, cache, server_addr, server_port)
   sock.send(Is_response)
  ###########################################

def main():
  # Listen on a specified port...
  Server_Sock = library.CreateServerSocket(LISTENING_PORT)
  Cache = library.KeyValueStore()
  # Accept incoming commands indefinitely.
  while True:
    # Wait until a client connects and then get a socket that connects to the
    # client.

    client_sock, (address, port) = library.ConnectClientToServer(server_sock, SERVER_PORT)
    print('Received connection from %s:%d' % (address, port))