3 # CGI wrapper to qchess
14 path = "../qchess-cgi-data/"
16 def open_fifo(name, mode, timeout=None):
18 return open(name, mode)
21 class Worker(threading.Thread):
23 threading.Thread.__init__(self)
30 self.result = open(name, mode)
40 while time.time() - start < timeout:
41 if w.is_alive() == False:
43 if w.exception != None:
50 #sys.stderr.write("FIFO_TIMEOUT!\n")
51 # Recursive to deal with possible race condition
54 f = open_fifo(name, "w", 1)
56 f = open_fifo(name, "r", 1)
60 #sys.stderr.write("Opened other end!\n")
67 raise Exception("FIFO_TIMEOUT")
70 if w.exception != None:
76 if os.path.exists(path+client+".in") and os.path.exists(path+client+".out"):
78 fifo_out = open_fifo(path+client+".in", "w", 5)
83 fifo_out.write("quit\n")
87 fifo_in = open_fifo(path+client+".out", "r", 5)
92 s = fifo_in.readline().strip(" \r\n")
95 s = fifo_in.readline().strip(" \r\n")
98 log = open(path+client, "a")
99 log.write(" -> %s\n" % str(datetime.datetime.now()))
108 print "Content-Type: text/plain\r\n\r\n"
111 form = cgi.FieldStorage()
112 client = cgi.escape(os.environ["REMOTE_ADDR"])
114 #client = "127.0.0.1"
122 request = form["r"].value
128 mode = form["m"].value
137 x = int(form["x"].value)
138 y = int(form["y"].value)
141 if os.path.exists(path+client+".in") and os.path.exists(path+client+".out"):
142 if request == "quit":
147 print "Game in progress expects x and y."
149 elif request == "start":
151 args = path+"qchess.py --no-graphics"
152 if mode == None or mode == "bishop":
153 args += " @fifo:../qchess-cgi-data/"+client+" @internal:AgentBishop"
155 args += " @fifo:../qchess-cgi-data/"+client+" @internal:AgentRandom"
156 elif mode == "eigengame":
157 args += " --server=progcomp.ucc.asn.au @fifo:../qchess-cgi-data/"+client
159 os.system("echo '"+args+"' | at now")
161 # subprocess.Popen(args)
162 # os.spawnl(os.P_NOWAIT, args)
167 log = open(path+client, "a")
168 log.write("%s" % str(datetime.datetime.now()))
172 print "No game in progress."
176 if not (os.path.exists(path+client+".in") and os.path.exists(path+client+".out")):
177 print "No game in progress."
181 fifo_out = open_fifo(path+client+".in", "w")
185 fifo_out.write("%d %d\n" % (x, y))
190 #sys.stderr.write("\ncgi read from fifo here\n")
192 fifo_in = open_fifo(path+client+".out", "r")
196 # sys.stderr.write("cgi opened fine\n")
197 s = fifo_in.readline().strip(" \r\n")
198 #sys.stderr.write("cgi read first line: "+str(s)+"\n")
199 while s != "SELECT?" and s != "MOVE?" and not s.split(" ")[0] in ["white","black"]:
202 # sys.stderr.write("Read: " + str(s) + "\n")
204 s = fifo_in.readline().strip(" \r\n")
207 if s.split(" ")[0] in ["white", "black"]:
208 #sys.stderr.write("cgi quit!\n")
211 #sys.stderr.write("cgi qchess Done\n")
215 if __name__ == "__main__":
217 sys.exit(main(sys.argv))
220 sys.stderr.write(sys.argv[0] + ": " + str(e) + "\n")