def __init__(self, parentThread): """ generated source for method __init__ """ super(ClientManager, self).__init__() self.parentThread = parentThread command = GamerConfiguration.getCommandForJava() processArgs = ArrayList() processArgs.add(command) processArgs.add("-mx" + GamerConfiguration.getMemoryForGamer() + "m") processArgs.add("-server") processArgs.add("-XX:-DontCompileHugeMethods") processArgs.add("-XX:MinHeapFreeRatio=10") processArgs.add("-XX:MaxHeapFreeRatio=10") processArgs.add("-classpath") processArgs.add(System.getProperty("java.class.path")) processArgs.add("org.ggp.base.player.proxy.ProxyGamePlayerClient") processArgs.add(self.gamerName) processArgs.add("" + self.clientListener.getLocalPort()) if GamerConfiguration.runningOnLinux(): processArgs.add(0, "nice") pb = ProcessBuilder(processArgs) try: GamerLogger.log("Proxy", "[PROXY] Starting a new proxy client, using gamer " + self.gamerName + ".") self.theClientProcess = pb.start() self.outConnector = StreamConnector(self.theClientProcess.getErrorStream(), System.err) self.errConnector = StreamConnector(self.theClientProcess.getInputStream(), System.out) self.outConnector.start() self.errConnector.start() self.theClientConnection = self.clientListener.accept() self.theOutput = PrintStream(self.theClientConnection.getOutputStream()) self.theInput = BufferedReader(InputStreamReader(self.theClientConnection.getInputStream())) GamerLogger.log("Proxy", "[PROXY] Proxy client started.") except IOException as e: GamerLogger.logStackTrace("Proxy", e)
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 proxyProcessRequest(self, theRequest, receptionTime): """ generated source for method proxyProcessRequest """ startSleeping = System.currentTimeMillis() timeToFinish = receptionTime timeToSleep = 0L try: if isinstance(theRequest, (PlayRequest, )): if self.theDefaultGamer.getMatch() != None: timeToFinish = receptionTime + self.theDefaultGamer.getMatch().getPlayClock() * 1000 - self.PLAY_BUFFER else: timeToFinish = System.currentTimeMillis() timeToSleep = timeToFinish - System.currentTimeMillis() if timeToSleep > 0: Thread.sleep(timeToSleep) elif isinstance(theRequest, (StartRequest, )): GamerLogger.startFileLogging(self.theDefaultGamer.getMatch(), self.theDefaultGamer.getRoleName().__str__()) print "Started playing " + self.theDefaultGamer.getMatch().getMatchId() + "." timeToFinish = receptionTime + self.theDefaultGamer.getMatch().getStartClock() * 1000 - self.METAGAME_BUFFER timeToSleep = timeToFinish - System.currentTimeMillis() if timeToSleep > 0: Thread.sleep(timeToSleep) elif isinstance(theRequest, (StopRequest, )) or isinstance(theRequest, (AbortRequest, )): GamerLogger.stopFileLogging() self.needRestart = True except InterruptedException as ie: GamerLogger.log("Proxy", "[PROXY] Got woken up by final move!") GamerLogger.log("Proxy", "[PROXY] Proxy slept for " + (System.currentTimeMillis() - startSleeping) + ", and woke up " + (System.currentTimeMillis() - timeToFinish) + "ms late (started " + (startSleeping - receptionTime) + "ms after receiving message).")
def create(cls, description): """ generated source for method create """ try: GamerLogger.log("StateMachine", "Converting...") return PropNetConverter().convert(Role.computeRoles(description), flatDescription) except Exception as e: GamerLogger.logStackTrace("StateMachine", e) return None
def flatten(self): """ generated source for method flatten """ self.description = DeORer.run(self.description) if noAnnotations(): GamerLogger.log("StateMachine", "Could not find 'base' annotations. Attempting to generate them...") self.description = PropNetAnnotater(self.description).getAugmentedDescription() GamerLogger.log("StateMachine", "Annotations generated.") self.templates = recordTemplates(self.description) self.instantiations = initializeInstantiations(self.description) flatDescription = ArrayList() for constant in templates.keySet(): flatDescription.addAll(getInstantiations(constant)) return flatDescription
def attemptLoadingInitialMachine(self): """ generated source for method attemptLoadingInitialMachine """ try: self.theBackingMachine.initialize(self.gameDescription) GamerLogger.log("StateMachine", "Failsafe Machine: successfully activated initial state machine for use!") return True except Exception as e1: pass except ThreadDeath as d: raise d except Error as e2: pass return False
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 switchStateMachine(self, newStateMachine): """ generated source for method switchStateMachine """ try: # Attempt to run through the game history in the new machine for nextMove in theMoveHistory: for theSentence in nextMove: theJointMove.add(newStateMachine.getMoveFromTerm(theSentence)) newCurrentState = newStateMachine.getNextStateDestructively(newCurrentState, theJointMove) # Finally, switch over if everything went well. role = newRole currentState = newCurrentState stateMachine = newStateMachine except Exception as e: GamerLogger.log("GamePlayer", "Caught an exception while switching state machine!") GamerLogger.logStackTrace("GamePlayer", e)
def attemptLoadingProverMachine(self): """ generated source for method attemptLoadingProverMachine """ try: theStateMachine.initialize(self.gameDescription) self.theBackingMachine = theStateMachine GamerLogger.log("StateMachine", "Failsafe Machine: successfully loaded traditional prover.") return True except Exception as e1: pass except ThreadDeath as d: raise d except OutOfMemoryError as e: raise e except Error as e2: pass return False
def run(self): """ generated source for method run """ try: while not self.pleaseStop: if next == -1: break if not self.isPrintableChar(str(next)): next = '@' self.theOutput.write(next) except IOException as e: GamerLogger.log("Proxy", "Might be okay:") GamerLogger.logStackTrace("Proxy", e) except Exception as e: GamerLogger.logStackTrace("Proxy", e) except Error as e: GamerLogger.logStackTrace("Proxy", e)
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 updateDomains(self): """ generated source for method updateDomains """ changedSomething = True itrNum = 0 lastUpdatedDomains = HashSet(self.domains.values()) while changedSomething: GamerLogger.log("StateMachine", "Beginning domain finding iteration: " + itrNum) changedSomething = False for d in domains.values(): for ruleRef in d.ruleRefs: for c in ruleRef.conditions: if lastUpdatedDomains.contains(c.dom): containsUpdatedDomain = True break if not containsUpdatedDomain: continue rulesConsidered += 1 for instantiation in instantiations: for t in ruleRef.productionTemplate: if isinstance(t, (GdlConstant, )): a.add(t) else: a.add(instantiation.get(var)) if not d.assignments.contains(a): currUpdatedDomains.add(d) d.assignments.add(a) changedSomething = True d.addAssignmentToIndex(a) if len(instantiations) == 0: findSatisfyingInstantiations(ruleRef) for t in ruleRef.productionTemplate: if isinstance(t, (GdlConstant, )): a.add(t) else: isVar = True break if not isVar and not d.assignments.contains(a): currUpdatedDomains.add(d) d.assignments.add(a) changedSomething = True d.addAssignmentToIndex(a) itrNum += 1 lastUpdatedDomains = currUpdatedDomains GamerLogger.log("StateMachine", "\tDone with iteration. Considered " + rulesConsidered + " rules.")
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 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 checkMachineConsistency(cls, theReference, theSubject, timeToSpend): """ generated source for method checkMachineConsistency """ startTime = System.currentTimeMillis() GamerLogger.log("StateMachine", "Performing automatic consistency testing on " + theSubject.__class__.__name__ + " using " + theReference.__class__.__name__ + " as a reference.") theMachines = ArrayList() theMachines.add(theReference) theMachines.add(theSubject) GamerLogger.emitToConsole("Consistency checking: [") nRound = 0 while True: nRound += 1 GamerLogger.emitToConsole(".") while i < len(theMachines): try: theCurrentStates[i] = theMachines.get(i).getInitialState() except Exception as e: GamerLogger.log("StateMachine", "Machine #" + i + " failed to generate an initial state!") return False i += 1 while not theMachines.get(0).isTerminal(theCurrentStates[0]): if System.currentTimeMillis() > startTime + timeToSpend: break # Do per-state consistency checks while i < len(theMachines): for theRole in theMachines.get(0).getRoles(): try: if not (theMachines.get(i).getLegalMoves(theCurrentStates[i], theRole).size() == theMachines.get(0).getLegalMoves(theCurrentStates[0], theRole).size()): GamerLogger.log("StateMachine", "Inconsistency between machine #" + i + " and ProverStateMachine over state " + theCurrentStates[0] + " vs " + theCurrentStates[i].getContents()) GamerLogger.log("StateMachine", "Machine #" + 0 + " has move count = " + theMachines.get(0).getLegalMoves(theCurrentStates[0], theRole).size() + " for player " + theRole) GamerLogger.log("StateMachine", "Machine #" + i + " has move count = " + theMachines.get(i).getLegalMoves(theCurrentStates[i], theRole).size() + " for player " + theRole) return False except Exception as e: GamerLogger.logStackTrace("StateMachine", e) i += 1 try: while i < len(theMachines): try: theCurrentStates[i] = theMachines.get(i).getNextState(theCurrentStates[i], theJointMove) except Exception as e: GamerLogger.logStackTrace("StateMachine", e) i += 1 except Exception as e: GamerLogger.logStackTrace("StateMachine", e) if System.currentTimeMillis() > startTime + timeToSpend: break while i < len(theMachines): if not theMachines.get(i).isTerminal(theCurrentStates[i]): GamerLogger.log("StateMachine", "Inconsistency between machine #" + i + " and ProverStateMachine over terminal-ness of state " + theCurrentStates[0] + " vs " + theCurrentStates[i]) return False for theRole in theMachines.get(0).getRoles(): try: theMachines.get(0).getGoal(theCurrentStates[0], theRole) except Exception as e: continue try: if theMachines.get(i).getGoal(theCurrentStates[i], theRole) != theMachines.get(0).getGoal(theCurrentStates[0], theRole): GamerLogger.log("StateMachine", "Inconsistency between machine #" + i + " and ProverStateMachine over goal value for " + theRole + " of state " + theCurrentStates[0] + ": " + theMachines.get(i).getGoal(theCurrentStates[i], theRole) + " vs " + theMachines.get(0).getGoal(theCurrentStates[0], theRole)) return False except Exception as e: GamerLogger.log("StateMachine", "Inconsistency between machine #" + i + " and ProverStateMachine over goal-ness of state " + theCurrentStates[0] + " vs " + theCurrentStates[i]) return False i += 1 GamerLogger.emitToConsole("]\n") GamerLogger.log("StateMachine", "Completed automatic consistency testing on " + theSubject.__class__.__name__ + ", w/ " + nRound + " rounds: all tests pass!") return True
def run(self): """ generated source for method run """ while not isInterrupted(): try: GamerLogger.log("Proxy", "[ProxyClient] Got message: " + theMessage) self.theCode = theMessage.messageCode self.notifyObservers(PlayerReceivedMessageEvent(in_)) if isinstance(request, (StartRequest, )): RequestFactory().create(theDefaultGamer, in_).process(1) GamerLogger.startFileLogging(theDefaultGamer.getMatch(), theDefaultGamer.getRoleName().__str__()) GamerLogger.log("Proxy", "[ProxyClient] Got message: " + theMessage) outMessage.writeTo(self.theOutput) GamerLogger.log("Proxy", "[ProxyClient] Sent message: " + outMessage) self.notifyObservers(PlayerSentMessageEvent(out)) if isinstance(request, (StopRequest, )): GamerLogger.log("Proxy", "[ProxyClient] Got stop request, shutting down.") System.exit(0) if isinstance(request, (AbortRequest, )): GamerLogger.log("Proxy", "[ProxyClient] Got abort request, shutting down.") System.exit(0) except Exception as e: GamerLogger.logStackTrace("Proxy", e) self.notifyObservers(PlayerDroppedPacketEvent()) GamerLogger.log("Proxy", "[ProxyClient] Got interrupted, shutting down.")
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())
def observe(self, event): """ generated source for method observe """ if isinstance(event, (WorkingResponseSelectedEvent, )): theMessage.writeTo(self.theOutput) GamerLogger.log("Proxy", "[ProxyClient] Sent message: " + theMessage)
def sendMessage(self, theMessage): """ generated source for method sendMessage """ if self.theOutput != None: theMessage.writeTo(self.theOutput) GamerLogger.log("Proxy", "[PROXY] Wrote message to client: " + theMessage)