Commit 8c604f1b authored by Alvin Natawiguna's avatar Alvin Natawiguna
Browse files

Fixed JoinCommand

parent c3bf4852
......@@ -85,10 +85,10 @@ class CommandFactory(object):
method = self.__json["method"]
if method == Command.METHOD_JOIN:
if 'ip' in self.__json and 'port' in self.__json:
return JoinCommand(self.__json['ip'], self.__json['port'])
if 'external_ip' in self.__json and 'external_port' in self.__json:
return JoinCommand(self.__json['external_ip'], self.__json['external_port'], self.__json['ip'], self.__json['port'])
else:
return JoinCommand()
return JoinCommand(self.__json['ip'], self.__json['port'])
elif method == Command.METHOD_SERVERSTATUS:
return ServerStatusCommand(self.__json['server'])
elif method == Command.METHOD_SIGNUP:
......@@ -139,11 +139,14 @@ class CommandFactory(object):
class JoinCommand(Command):
DEFAULT_TRACKER_IP, DEFAULT_TRACKER_PORT = '167.205.32.46', 8000
def __init__(self, ip = DEFAULT_TRACKER_IP, port = DEFAULT_TRACKER_PORT):
def __init__(self, extIp, extPort, trackerIp = DEFAULT_TRACKER_IP, trackerPort = DEFAULT_TRACKER_PORT):
super().__init__()
self.ip = ip
self.port = port
self.ext_ip = extIp
self.ext_port = extPort
self.tracker_ip = trackerIp
self.tracker_port = trackerPort
self.result = None
......@@ -151,12 +154,12 @@ class JoinCommand(Command):
sock = socket.socket()
try:
sock.connect((JoinCommand.DEFAULT_TRACKER_IP, JoinCommand.DEFAULT_TRACKER_PORT))
sock.connect((self.tracker_ip, self.tracker_port))
request = {
'method': Command.METHOD_JOIN,
'ip': self.ip,
'port': self.port
'ip': self.ext_ip,
'port': self.ext_port
}
sock.sendall(json.dumps(request).encode('utf-8'))
......
......@@ -14,7 +14,7 @@ class Location(object):
if isinstance(other, self.__class__):
return self.x == other.x and self.y == other.y
else:
raise TypeError("Unknown comparision between Item and {}".format(other.__class__))
raise TypeError("Unknown comparision between Location and {}".format(other.__class__))
def __ne__(self, other):
return self.__eq__(other)
......
......@@ -80,13 +80,15 @@ class RequestHandler(socketserver.BaseRequestHandler):
class ThreadedTcpServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
def connectTracker(ip, port, myExtIp):
def connectTracker(externalAddr, trackerAddr = (command.JoinCommand.DEFAULT_TRACKER_IP, command.JoinCommand.DEFAULT_TRACKER_PORT)):
print("[TRACKER] Connecting to tracker...")
factory = command.CommandFactory({
'method': command.Command.METHOD_JOIN,
'ip': ip,
'port': port
'external_ip': externalAddr[0],
'external_port': externalAddr[1],
'ip': trackerAddr[0],
'port': trackerAddr[1]
})
myCommand = factory.getCommand()
......@@ -127,7 +129,7 @@ def getExternalIp():
else:
return ip
def scheduleBatchFindOffer(scheduler, addr, extip):
def scheduleBatchFindOffer(scheduler, externalAddr):
import datetime
print("")
......@@ -136,14 +138,14 @@ def scheduleBatchFindOffer(scheduler, addr, extip):
db = client.get_database('if3230-sister')
assert db.authenticate('sister', 'sisterpoi')
print("[BATCH_OFFER_FETCH] fetching items from other servers...")
print("[BATCH_OFFER_FETCH] Refreshing item offers...")
servers = []
cursor = db.activeServers.find()
if cursor.count() == 0:
# reconnect to tracker if no more active serve
connectTracker(extip, addr[1], extip)
connectTracker(externalAddr)
cursor = db.activeServers.find()
# fetch active servers list
......@@ -183,26 +185,26 @@ def scheduleBatchFindOffer(scheduler, addr, extip):
).strftime("%Y-%m-%d %H:%M:%S")
)
)
print("[BATCH_OFFER_FETCH] finished.")
print("[BATCH_OFFER_FETCH] Cached offers refreshed.")
else:
print("[BATCH_OFFER_FETCH] no active server found.")
print("[BATCH_OFFER_FETCH] No active server found.")
del servers
# repeat
scheduler.enter(60, 2, scheduleBatchFindOffer, argument=(scheduler, addr, extip,))
scheduler.enter(60, 2, scheduleBatchFindOffer, argument=(scheduler, externalAddr,))
if __name__ == '__main__':
HOST, PORT = '0.0.0.0', int(sys.argv[1])
extip = getExternalIp()
connectTracker(extip, PORT, extip)
connectTracker((extip, PORT))
server = ThreadedTcpServer((HOST, PORT), RequestHandler)
print("")
print("[INFO] Starting server at {}:{}".format(HOST, PORT))
print("[INFO] Your external IP: ", extip)
print("[INFO] Starting server at ({}, {})".format(HOST, PORT))
print("[INFO] Your external IP:", extip)
# start a server thread
server_thread = threading.Thread(target=server.serve_forever)
......@@ -211,10 +213,11 @@ if __name__ == '__main__':
server_thread.daemon = True
server_thread.start()
print("[INFO] Server running on thread: ", server_thread.name)
print("[INFO] Server running on thread:", server_thread.name)
# start scheduler
scheduler = sched.scheduler()
scheduler.enter(5, 2, scheduleBatchFindOffer, argument=(scheduler, (HOST, PORT), extip,))
scheduler.enter(5, 2, scheduleBatchFindOffer, argument=(scheduler, (extip, PORT),))
scheduler.run()
while True:
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment