def process(self, receptionTime): """ generated source for method process """ # Ensure that we aren't already playing a match. If we are, # ignore the message, saying that we're busy. if self.gamer.getMatch() != None: GamerLogger.logError("GamePlayer", "Got start message while already busy playing a game: ignoring.") self.gamer.notifyObservers(GamerUnrecognizedMatchEvent(self.matchId)) return "busy" # Create the new match, and handle all of the associated logistics # in the gamer to indicate that we're starting a new match. match = Match(self.matchId, -1, self.startClock, self.playClock, self.game) self.gamer.setMatch(match) self.gamer.setRoleName(self.roleName) self.gamer.notifyObservers(GamerNewMatchEvent(match, self.roleName)) # Finally, have the gamer begin metagaming. try: self.gamer.notifyObservers(PlayerTimeEvent(self.gamer.getMatch().getStartClock() * 1000)) self.gamer.metaGame(self.gamer.getMatch().getStartClock() * 1000 + receptionTime) except MetaGamingException as e: GamerLogger.logStackTrace("GamePlayer", e) # Upon encountering an uncaught exception during metagaming, # assume that indicates that we aren't actually able to play # right now, and tell the server that we're busy. self.gamer.setMatch(None) self.gamer.setRoleName(None) return "busy" return "ready"
def __init__(self, port, gamer): """ generated source for method __init__ """ super(ProxyGamePlayer, self).__init__() # Use a random gamer as our "default" gamer, that we fall back to # in the event that we don't get a message from the client, or if # we need to handle a simple request (START or STOP). self.theDefaultGamer = RandomGamer() self.observers = ArrayList() self.listener = None while self.listener == None: try: self.listener = ServerSocket(port) except Exception as ex: self.listener = None port += 1 GamerLogger.logError("Proxy", "Failed to start gamer on port: " + (port - 1) + " trying port " + port) self.myPort = port # Start up the socket for communicating with clients clientPort = 17147 while self.clientListener == None: try: self.clientListener = ServerSocket(clientPort) except Exception as ex: self.clientListener = None clientPort += 1 GamerLogger.log("Proxy", "[PROXY] Opened client communication socket on port " + clientPort + ".") # Start up the first ProxyClient self.gamerName = gamer.getSimpleName()
def main(cls, args): """ generated source for method main """ GamerLogger.setSpilloverLogfile("spilloverLog") GamerLogger.log("Proxy", "Starting the ProxyGamePlayerClient program.") if not (len(args)): GamerLogger.logError("Proxy", "Usage is: \n\tProxyGamePlayerClient gamer port") return port = 9147 gamer = None try: port = Integer.valueOf(args[1]) except Exception as e: GamerLogger.logError("Proxy", args[1] + " is not a valid port.") return gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()) gamerNames = ArrayList() if len(gamerNames) != len(gamers): for c in gamers: gamerNames.add(c.__name__.replaceAll("^.*\\.", "")) idx = gamerNames.indexOf(args[0]) if idx == -1: GamerLogger.logError("Proxy", args[0] + " is not a subclass of gamer. Valid options are:") for s in gamerNames: GamerLogger.logError("Proxy", "\t" + s) return try: gamer = (gamers.get(idx).newInstance()) except Exception as ex: GamerLogger.logError("Proxy", "Cannot create instance of " + args[0]) return try: theClient.start() except IOException as e: GamerLogger.logStackTrace("Proxy", e)
def preview(self, game, timeout): """ generated source for method preview """ self.lazilyLoadGamerStub() try: self.theClojureGamer.preview(game, timeout) except GamePreviewException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineMetaGame:") GamerLogger.logStackTrace("GamePlayer", e)
def lazilyLoadGamerStub(self): """ generated source for method lazilyLoadGamerStub """ if self.thePythonGamer == None: try: # Load in the Python gamer, using a Jython intepreter. interpreter.exec_("from " + self.getPythonGamerModule() + " import " + self.getPythonGamerName()) self.thePythonGamer = PyGamerObject.__tojava__(Gamer.__class__) except Exception as e: GamerLogger.logError("GamePlayer", "Caught exception in Python initialization:") GamerLogger.logStackTrace("GamePlayer", e)
def getGoal(self, state, role): """ generated source for method getGoal """ results = self.prover.askAll(ProverQueryBuilder.getGoalQuery(role), ProverQueryBuilder.getContext(state)) if len(results) != 1: GamerLogger.logError("StateMachine", "Got goal results of size: " + len(results) + " when expecting size one.") raise GoalDefinitionException(state, role) try: return Integer.parseInt(constant.__str__()) except Exception as e: raise GoalDefinitionException(state, role)
def abort(self): """ generated source for method abort """ self.lazilyLoadGamerStub() self.theClojureGamer.setMatch(getMatch()) self.theClojureGamer.setRoleName(getRoleName()) try: self.theClojureGamer.abort() except AbortingException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineAbort:") GamerLogger.logStackTrace("GamePlayer", e)
def metaGame(self, timeout): """ generated source for method metaGame """ self.lazilyLoadGamerStub() self.theClojureGamer.setMatch(getMatch()) self.theClojureGamer.setRoleName(getRoleName()) try: self.theClojureGamer.metaGame(timeout) except MetaGamingException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineMetaGame:") GamerLogger.logStackTrace("GamePlayer", e)
def stop(self): """ generated source for method stop """ self.lazilyLoadGamerStub() self.thePythonGamer.setMatch(getMatch()) self.thePythonGamer.setRoleName(getRoleName()) try: self.thePythonGamer.stop() except StoppingException as e: GamerLogger.logError("GamePlayer", "Caught exception in Python stateMachineStop:") GamerLogger.logStackTrace("GamePlayer", e)
def selectMove(self, timeout): """ generated source for method selectMove """ self.lazilyLoadGamerStub() self.theClojureGamer.setMatch(getMatch()) self.theClojureGamer.setRoleName(getRoleName()) try: return self.theClojureGamer.selectMove(timeout) except MoveSelectionException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineSelectMove:") GamerLogger.logStackTrace("GamePlayer", e) return None
def lazilyLoadGamerStub(self): """ generated source for method lazilyLoadGamerStub """ if self.theClojureGamer == None: try: # Load the Clojure script -- as a side effect this initializes the runtime. RT.loadResourceScript(self.getClojureGamerFile() + ".clj") # Get a reference to the gamer-generating function. # Call it! self.theClojureGamer = gamerVar.invoke() except Exception as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure initialization:") GamerLogger.logStackTrace("GamePlayer", e)
def run(self): """ generated source for method run """ while True: try: if self.inputQueue.remainingCapacity() > 0: self.inputQueue.add(ProxyMessage(in_, 0L, receptionTime)) self.inputConnectionQueue.add(connection) GamerLogger.log("Proxy", "[PROXY QueueListener] Got incoming message from game server: " + in_ + ". Added to queue in position " + len(self.inputQueue) + ".") else: GamerLogger.logError("Proxy", "[PROXY QueueListener] Got incoming message from game server: " + in_ + ". Could not add to queue, because queue is full!") except Exception as e: GamerLogger.logStackTrace("Proxy", e) except Error as e: GamerLogger.logStackTrace("Proxy", e)
def process(self, receptionTime): """ generated source for method process """ # First, check to ensure that this play request is for the match # we're currently playing. If we're not playing a match, or we're # playing a different match, send back "busy". if self.gamer.getMatch() == None or not self.gamer.getMatch().getMatchId() == self.matchId: self.gamer.notifyObservers(GamerUnrecognizedMatchEvent(self.matchId)) GamerLogger.logError("GamePlayer", "Got play message not intended for current game: ignoring.") return "busy" if self.moves != None: self.gamer.getMatch().appendMoves(self.moves) try: self.gamer.notifyObservers(PlayerTimeEvent(self.gamer.getMatch().getPlayClock() * 1000)) return self.gamer.selectMove(self.gamer.getMatch().getPlayClock() * 1000 + receptionTime).__str__() except MoveSelectionException as e: GamerLogger.logStackTrace("GamePlayer", e) return "nil"
def process(self, receptionTime): """ generated source for method process """ # First, check to ensure that this abort request is for the match # we're currently playing. If we're not playing a match, or we're # playing a different match, send back "busy". if self.gamer.getMatch() == None or not self.gamer.getMatch().getMatchId() == self.matchId: GamerLogger.logError("GamePlayer", "Got abort message not intended for current game: ignoring.") self.gamer.notifyObservers(GamerUnrecognizedMatchEvent(self.matchId)) return "busy" self.gamer.getMatch().markAborted() self.gamer.notifyObservers(GamerAbortedMatchEvent()) try: self.gamer.abort() except AbortingException as e: GamerLogger.logStackTrace("GamePlayer", e) self.gamer.setRoleName(None) self.gamer.setMatch(None) return "aborted"
def processClientResponse(self, in_, toWakeUp): """ generated source for method processClientResponse """ theirTag = in_.theMessage.substring(0, 5) theirMessage = in_.theMessage.substring(5) if not (in_.messageCode == self.currentMoveCode): if self.currentMoveCode > 0: GamerLogger.logError("Proxy", "CODE MISMATCH: " + self.currentMoveCode + " vs " + in_.messageCode) return if theirTag == "WORK:": self.latestProxiedResponse = theirMessage GamerLogger.log("Proxy", "[PROXY] Got latest working move: " + self.latestProxiedResponse) self.receivedClientMove = True elif theirTag == "DONE:": self.latestProxiedResponse = theirMessage GamerLogger.log("Proxy", "[PROXY] Got a final move: " + self.latestProxiedResponse) self.receivedClientMove = True self.currentMoveCode = 0L toWakeUp.interrupt()
def readFrom(cls, theInput): """ generated source for method readFrom """ try: return ProxyMessage(cls.theMessage, cls.messageCode, cls.receptionTime) except SocketException as se: GamerLogger.log("Proxy", "[ProxyMessage Reader] Socket closed: stopping read operation.") raise se except Exception as e: GamerLogger.logStackTrace("Proxy", e) GamerLogger.logError("Proxy", "[ProxyMessage Reader] Could not digest message. Emptying stream.") try: # TODO: Fix this, I suspect it may be buggy. theInput.skip(Long.MAX_VALUE) except SocketException as se: GamerLogger.log("Proxy", "[ProxyMessage Reader] Socket closed: stopping read operation.") raise se except Exception as ie: GamerLogger.logStackTrace("Proxy", ie) return None
def process(self, receptionTime): """ generated source for method process """ # Ensure that we aren't already playing a match. If we are, # ignore the message, saying that we're busy. if self.gamer.getMatch() != None: GamerLogger.logError("GamePlayer", "Got preview message while already busy playing a game: ignoring.") # gamer.notifyObservers(new GamerUnrecognizedMatchEvent(matchId)); return "busy" # Otherwise, if we're not busy, have the gamer start previewing. try: # gamer.notifyObservers(new PlayerTimeEvent(gamer.getMatch().getStartClock() * 1000)); self.gamer.preview(self.game, self.previewClock * 1000 + receptionTime) # gamer.metaGame(gamer.getMatch().getStartClock() * 1000 + receptionTime); except GamePreviewException as e: GamerLogger.logStackTrace("GamePlayer", e) # Upon encountering an uncaught exception during previewing, # assume that indicates that we aren't actually able to play # right now, and tell the server that we're busy. return "busy" return "ready"
def run(self): """ generated source for method run """ while self.theInput != None: try: if self.pleaseStop: return GamerLogger.log("Proxy", "[PROXY] Got message from client: " + in_) if in_ == None: continue processClientResponse(in_, self.parentThread) except SocketException as se: if self.expectStop: return GamerLogger.logStackTrace("Proxy", se) GamerLogger.logError("Proxy", "Shutting down reader as consequence of socket exception. Presumably this is because the gamer client crashed.") break except Exception as e: GamerLogger.logStackTrace("Proxy", e) except Error as e: GamerLogger.logStackTrace("Proxy", e)
def initialize(self, description): """ generated source for method initialize """ self.gameDescription = description if attemptLoadingInitialMachine(): return GamerLogger.logError("StateMachine", "Failsafe Machine: failed to load initial state machine. Falling back...") if attemptLoadingProverMachine(): return GamerLogger.logError( "StateMachine", "Failsafe Machine: catastrophic failure to load *any* state machine. Cannot recover." ) GamerLogger.logError("StateMachine", "Failsafe Machine: cannot recover from current state. Shutting down.") self.theBackingMachine = None
def failGracefully(self, e1, e2): """ generated source for method failGracefully """ if e1 != None: GamerLogger.logStackTrace("StateMachine", e1) if e2 != None: GamerLogger.logStackTrace("StateMachine", e2) GamerLogger.logError("StateMachine", "Failsafe Machine: graceful failure mode kicking in.") if self.theBackingMachine.__class__ != ProverStateMachine.__class__: GamerLogger.logError( "StateMachine", "Failsafe Machine: online failure for " + self.theBackingMachine.__class__ + ". Attempting to restart with a standard prover.", ) if attemptLoadingProverMachine(): return self.theBackingMachine = None GamerLogger.logError("StateMachine", "Failsafe Machine: online failure for regular prover. Cannot recover.")
def run(self): """ generated source for method run """ GamerConfiguration.showConfiguration() GamerLogger.setSpilloverLogfile("spilloverLog") # Start up the client manager self.theClientManager = self.ClientManager(Thread.currentThread()) self.theClientManager.start() # Start up the input queue listener inputQueue = ArrayBlockingQueue(100) inputConnectionQueue = ArrayBlockingQueue(100) theListener = QueueListenerThread() theListener.start() while True: try: # First, read a message from the server. self.notifyObservers(PlayerReceivedMessageEvent(in_)) GamerLogger.log("Proxy", "[PROXY] Got incoming message:" + in_) # Formulate a request, and see how the legal gamer responds. try: legalProxiedResponse = request.process(receptionTime) except OutOfMemoryError as e: # Something went horribly wrong -- our baseline prover failed. System.gc() GamerLogger.logStackTrace("Proxy", e) legalProxiedResponse = "SORRY" latestProxiedResponse = legalProxiedResponse GamerLogger.log("Proxy", "[PROXY] Selected fallback move:" + latestProxiedResponse) if not (isinstance(request, (InfoRequest, ))): # Update the move codes and prepare to send the request on to the client. self.receivedClientMove = False self.currentMoveCode = 1 + self.theRandomGenerator.nextLong() if isinstance(request, (StopRequest, )) or isinstance(request, (AbortRequest, )): self.theClientManager.expectStop = True # Send the request on to the client, along with the move code. self.theClientManager.sendMessage(theMessage) if not (isinstance(request, (PlayRequest, ))): self.currentMoveCode = 0L # the default gamer handle it by switching move code. # Wait the appropriate amount of time for the request. proxyProcessRequest(request, receptionTime) else: self.receivedClientMove = True # Get the latest response, and complain if it's the default response, or isn't a valid response. if not self.receivedClientMove and (isinstance(request, (PlayRequest, ))): GamerLogger.logError("Proxy", "[PROXY] Did not receive any move information from client for this turn; falling back to first legal move.") GamerLogger.logError("ExecutiveSummary", "Proxy did not receive any move information from client this turn: used first legal move.") # Cycle the move codes again so that we will ignore any more responses # that the client sends along to us. self.currentMoveCode = 0L # And finally write the latest response out to the server. GamerLogger.log("Proxy", "[PROXY] Wrote outgoing message:" + out) HttpWriter.writeAsServer(connection, out) connection.close() self.notifyObservers(PlayerSentMessageEvent(out)) # Once everything is said and done, restart the client if we're # due for a restart (having finished playing a game). if self.needRestart: self.theClientManager.closeClient() self.theClientManager.pleaseStop = True if GamerConfiguration.runningOnLinux(): # Clean up the working directory and terminate any orphan processes. Thread.sleep(500) GamerLogger.log("Proxy", "[PROXY] Calling cleanup scripts.") try: Runtime.getRuntime().exec_("./cleanup.sh").waitFor() except IOException as e: GamerLogger.logStackTrace("Proxy", e) Thread.sleep(500) self.theClientManager = self.ClientManager(Thread.currentThread()) self.theClientManager.start() self.theDefaultGamer = RandomGamer() GdlPool.drainPool() SymbolPool.drainPool() GamerLogger.log("Proxy", "[PROXY] Before collection, using " + usedMemoryInMegs + "mb of memory as proxy.") while i < 10: System.gc() Thread.sleep(100) i += 1 usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() usedMemoryInMegs = usedMemory / 1024.0 / 1024.0 GamerLogger.log("Proxy", "[PROXY] After collection, using a non-transient " + usedMemoryInMegs + "mb of memory as proxy.") print "Cleaned up completed match, with a residual " + usedMemoryInMegs + "mb of memory as proxy." self.needRestart = False except Exception as e: GamerLogger.logStackTrace("Proxy", e) self.notifyObservers(PlayerDroppedPacketEvent()) except Error as e: GamerLogger.logStackTrace("Proxy", e) self.notifyObservers(PlayerDroppedPacketEvent())