def keepAlive(): server = config.master while True: try: # Wait keepAlive period time.sleep(config.timeout/5) except: break # Simulate dying #if (randint(0, 10) == 0): # return try: # Connect to master and ask for status print("{time:s} Send KeepAlive".format(time=Utilities.current_time_formatted())) conn = messages.Connection(Utilities.connect((server["address"], server["port"]))) connections_manager.add(conn) sendStatusMessage(conn) for msg in pending_messages.getAll(): print("Sending result: {:s}".format(str(msg))) conn.send(msg) conn.socket.shutdown(socket.SHUT_WR) # Read response for msg in conn: # TM, CN: Backup servers info if type(msg) == messages.NoOperation: messageNoOperation(msg) # TM: Divide problem elif type(msg) == messages.DivideProblem: messageDivideProblem(msg) # CN: Compute partial problems solutions elif type(msg) == messages.SolvePartialProblems: messageSolvePartialProblems(msg) # TM: Merge partial solutions elif type(msg) == messages.Solutions: messageSolutions(msg) else: print("? {:s}".format(str(msg))) conn.socket.close() connections_manager.remove(conn) except OSError as msg: print("KeepAlive connection error: {:s}".format(str(msg))) if config.backups: index = config.backups.index(server) if server in config.backups else -1 server = config.backups[index + 1] if len(config.backups) > index + 1 else None if server == None: print("No further backup servers available, exiting...") break print("Backup list: ", config.backups) print("Connecting to next backup: {:s}:{:d}".format(server["address"], server["port"])) else: break
def registerBackup(address, port, assumeId=None): print("{time:s} Connecting to {address:s}:{port:d}...".format(time=Utilities.current_time_formatted(), address=address, port=port)) while True: try: conn = messages.Connection(connect((address, port), ('', args.port))) connections_manager.add(conn) break except Exception as msg: print("Trying to bind...") time.sleep(1) print("Send Register message") request = messages.Register(Type="CommunicationServer", SolvableProblems=[], ParallelThreads=0, Id=assumeId) conn.send(request) conn.socket.shutdown(socket.SHUT_WR) for msg in conn: if type(msg) == messages.RegisterResponse: # Has BackupCommunicationServers field -> connect to next backup in list if msg.BackupCommunicationServers: backup = msg.BackupCommunicationServers[0] print("Sent to next BCS at {address:s}:{port:d}".format(address=backup['address'], port=backup['port'])) conn.socket.close() connections_manager.remove(conn) registerBackup(backup['address'], backup['port'], msg.Id) return # Registered at last communication server in list else: print("Registered successfully") config.id = msg.Id config.timeout = msg.Timeout config.parent_address = address config.parent_port = port # Messages with state, sent from higher communication server else: parseMessageBCS(msg) conn.socket.close() connections_manager.remove(conn)