utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import unittest
  2. import sys
  3. import os
  4. import sys
  5. import time
  6. import json
  7. import urllib
  8. import urllib2
  9. import subprocess
  10. import signal
  11. import random
  12. sys.path.append("interface/HUTN")
  13. from hutn_compiler.compiler import main as do_compile
  14. username = "test_user"
  15. parallel_push = True
  16. ports = []
  17. def getFreePort():
  18. while 1:
  19. port = random.randint(10000, 20000)
  20. ports.append(port)
  21. exists = False
  22. for p in ports:
  23. if p == port:
  24. if not exists:
  25. # We have hopefully found our own
  26. exists = True
  27. else:
  28. # We seem to be the second entry, so chose another one
  29. ports.remove(port)
  30. break
  31. else:
  32. # Didn't find a duplicate
  33. return port
  34. def execute(scriptname, parameters=[], wait=False):
  35. if os.name not in ["nt", "posix"]:
  36. # Stop now, as we would have no clue on how to kill its subtree
  37. raise Exception("Unknown OS version: " + str(os.name))
  38. command = [sys.executable, "scripts/%s.py" % scriptname] + parameters
  39. if wait:
  40. return subprocess.call(command, shell=False)
  41. else:
  42. return subprocess.Popen(command, shell=False)
  43. def kill(process):
  44. if os.name == "nt":
  45. subprocess.call(["taskkill", "/F", "/T", "/PID", "%i" % process.pid])
  46. elif os.name == "posix":
  47. subprocess.call(["pkill", "-P", "%i" % process.pid])
  48. def flush_data(address, data):
  49. if data:
  50. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "username": username})), timeout=10).read()
  51. return []
  52. def compile_file(address, mod_filename, filename, mode, proc):
  53. # Load in the file required
  54. try:
  55. timeout_val = 240
  56. import random
  57. username = str(random.random())
  58. while 1:
  59. proc2 = execute("compile", [address, mod_filename, username, filename, mode], wait=False)
  60. if proc.returncode is not None:
  61. # Modelverse has already terminated, which isn't a good sign!
  62. raise Exception("Modelverse died!")
  63. while proc2.returncode is None:
  64. time.sleep(0.01)
  65. proc2.poll()
  66. timeout_val -= 0.01
  67. if timeout_val < 0:
  68. kill(proc2)
  69. print("Compilation timeout expired!")
  70. return False
  71. if proc2.returncode != 2:
  72. break
  73. # Make sure everything stopped correctly
  74. assert proc2.returncode == 0
  75. if proc2.returncode != 0:
  76. return False
  77. except:
  78. raise
  79. finally:
  80. try:
  81. kill(proc2)
  82. except UnboundLocalError:
  83. pass
  84. def run_file(files, parameters, expected, mode):
  85. # Resolve file
  86. import os.path
  87. time.sleep(0.01)
  88. port = getFreePort()
  89. address = "http://127.0.0.1:%i" % port
  90. try:
  91. # Run Modelverse server
  92. proc = execute("run_local_modelverse", [str(port)], wait=False)
  93. threads = []
  94. for filename in files:
  95. if os.path.isfile("integration/code/%s" % filename):
  96. mod_filename = "integration/code/%s" % filename
  97. elif os.path.isfile("bootstrap/%s" % filename):
  98. mod_filename = "bootstrap/%s" % filename
  99. else:
  100. raise Exception("File not found: %s" % filename)
  101. print("Found file " + str(mod_filename))
  102. if parallel_push:
  103. import threading
  104. threads.append(threading.Thread(target=compile_file, args=[address, mod_filename, filename, mode, proc]))
  105. threads[-1].start()
  106. else:
  107. compile_file(address, mod_filename, filename, mode, proc)
  108. # After the first file, which can be whatever we want, we just have to compile dependencies, all of which are PO for efficiency
  109. mode = "PO"
  110. if parallel_push:
  111. for t in threads:
  112. t.join()
  113. if mode[-1] == "O":
  114. # Fire up the linker
  115. val = execute("link_and_load", [address, username] + files, wait=True)
  116. if val != 0:
  117. raise Exception("Linking error")
  118. # Send in the actual request and wait for replies
  119. var_list = {}
  120. data = []
  121. got_output = []
  122. for p in parameters:
  123. if isinstance(p, int):
  124. if p not in var_list:
  125. data = flush_data(address, data)
  126. proc.poll()
  127. if proc.returncode is not None:
  128. # Modelverse has already terminated, which isn't a good sign!
  129. return False
  130. while 1:
  131. print("Wait for result")
  132. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username})), timeout=120).read()
  133. print("Got result: " + str(val))
  134. l, r = val.split("&", 1)
  135. if l.startswith("id"):
  136. id_str = l
  137. val_str = r
  138. else:
  139. id_str = r
  140. val_str = l
  141. id_val = id_str.split("=", 1)[1]
  142. val_val = val_str.split("=", 1)[1]
  143. if val_val == "None":
  144. var_list[p] = id_val
  145. break
  146. else:
  147. got_output.append(val)
  148. continue
  149. else:
  150. val = var_list[p]
  151. t = "R"
  152. else:
  153. val = p
  154. t = "V"
  155. data.append([t, val])
  156. data = flush_data(address, data)
  157. flush_data(address, data)
  158. for e in expected:
  159. c = len(e) if isinstance(e, set) else 1
  160. for _ in range(c):
  161. if got_output:
  162. val = got_output.pop(0)
  163. else:
  164. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username})), timeout=240).read()
  165. if proc.returncode is not None:
  166. # Modelverse has already terminated, which isn't a good sign!
  167. raise Exception("Modelverse died!")
  168. val = val.split("=", 2)[2]
  169. print("Got %s, expect %s" % (val, e))
  170. if isinstance(e, set):
  171. assert str(val) in e
  172. if str(val) not in e:
  173. return False
  174. else:
  175. assert str(val) == e
  176. if str(val) != e:
  177. return False
  178. # All passed!
  179. return True
  180. except:
  181. raise
  182. finally:
  183. try:
  184. kill(proc)
  185. except UnboundLocalError:
  186. pass
  187. def run_barebone(parameters, expected, interface="0", timeout=False, wait=False, link=None, inputs=[]):
  188. port = getFreePort()
  189. address = "http://127.0.0.1:%i" % port
  190. try:
  191. # Run Modelverse server
  192. proc = execute("run_local_modelverse", [str(port)], wait=False)
  193. # Create user and set interface
  194. timeout_val = 15
  195. start = time.time()
  196. while 1:
  197. proc.poll()
  198. if proc.returncode is not None:
  199. # Modelverse has already terminated, which isn't a good sign!
  200. return False
  201. try:
  202. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "element_type": "V", "value": '"%s"' % username, "username": "user_manager"})), timeout=1).read()
  203. if interface is not None:
  204. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "element_type": "V", "value": interface, "username": username})), timeout=1).read()
  205. break
  206. except:
  207. time.sleep(0.01)
  208. if time.time() - start > timeout_val:
  209. raise
  210. # Send in the actual request and wait for replies
  211. var_list = {}
  212. data = []
  213. for p in parameters:
  214. if isinstance(p, int):
  215. if p not in var_list:
  216. data = flush_data(address, data)
  217. proc.poll()
  218. if proc.returncode is not None:
  219. # Modelverse has already terminated, which isn't a good sign!
  220. return False
  221. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username})), timeout=10).read()
  222. val = val.split("=", 2)[1].split("&", 1)[0]
  223. var_list[p] = val
  224. continue
  225. else:
  226. val = var_list[p]
  227. t = "R"
  228. else:
  229. val = p
  230. t = "V"
  231. data.append([t, val])
  232. data = flush_data(address, data)
  233. # Now do linking and loading
  234. if link is not None:
  235. # Execute linker
  236. timeout_val = 10
  237. proc2 = execute("link_and_load", [address, username] + link, wait=False)
  238. while proc2.returncode is None:
  239. time.sleep(0.01)
  240. proc2.poll()
  241. timeout_val -= 0.01
  242. if timeout_val < 0:
  243. kill(proc2)
  244. print("Linking timeout expired!")
  245. return False
  246. if proc.returncode is not None:
  247. # Modelverse has already terminated, which isn't a good sign!
  248. return False
  249. for inp in inputs:
  250. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "element_type": "V", "value": inp, "username": username})), timeout=1).read()
  251. proc.poll()
  252. if proc.returncode is not None:
  253. # Modelverse has already terminated, which isn't a good sign!
  254. return False
  255. counter = 0
  256. for e in expected:
  257. print("Expect " + str(e))
  258. c = len(e) if isinstance(e, set) else 1
  259. for _ in range(c):
  260. try:
  261. proc.poll()
  262. if proc.returncode is not None:
  263. # Modelverse has already terminated, which isn't a good sign!
  264. return False
  265. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username})), timeout=240 if not timeout else 20).read()
  266. except:
  267. if timeout:
  268. return True
  269. else:
  270. raise
  271. val = val.split("=", 2)[2]
  272. print("Got %s, expect %s" % (val, e))
  273. if isinstance(e, set):
  274. assert str(val) in e
  275. if str(val) not in e:
  276. return False
  277. else:
  278. assert str(val) == e
  279. if str(val) != e:
  280. return False
  281. # All passed!
  282. return not timeout
  283. finally:
  284. kill(proc)
  285. def get_constructor(code):
  286. with open("__constraint.al", "w") as f:
  287. f.write(code)
  288. f.flush()
  289. constructors = do_compile("__constraint.al", "interface/HUTN/grammars/actionlanguage.g", "CS")
  290. print("Got constructors: " + str(constructors))
  291. return constructors