utils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 the request ...
  119. flush_data(address, parameters)
  120. # ... and wait for replies
  121. for e in expected:
  122. c = len(e) if isinstance(e, set) else 1
  123. for _ in range(c):
  124. if got_output:
  125. val = got_output.pop(0)
  126. else:
  127. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username})), timeout=240).read()
  128. if proc.returncode is not None:
  129. # Modelverse has already terminated, which isn't a good sign!
  130. raise Exception("Modelverse died!")
  131. print("Got %s, expect %s" % (val, e))
  132. if isinstance(e, set):
  133. assert str(val) in e
  134. if str(val) not in e:
  135. return False
  136. else:
  137. assert str(val) == e
  138. if str(val) != e:
  139. return False
  140. # All passed!
  141. return True
  142. except:
  143. raise
  144. finally:
  145. try:
  146. kill(proc)
  147. except UnboundLocalError:
  148. pass
  149. def run_barebone(parameters, expected, interface="0", timeout=False, wait=False, link=None, inputs=[]):
  150. port = getFreePort()
  151. address = "http://127.0.0.1:%i" % port
  152. try:
  153. # Run Modelverse server
  154. proc = execute("run_local_modelverse", [str(port)], wait=False)
  155. # Create user and set interface
  156. timeout_val = 15
  157. start = time.time()
  158. while 1:
  159. proc.poll()
  160. if proc.returncode is not None:
  161. # Modelverse has already terminated, which isn't a good sign!
  162. return False
  163. try:
  164. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "element_type": "V", "value": '"%s"' % username, "username": "user_manager"})), timeout=1).read()
  165. if interface is not None:
  166. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "element_type": "V", "value": interface, "username": username})), timeout=1).read()
  167. break
  168. except:
  169. time.sleep(0.01)
  170. if time.time() - start > timeout_val:
  171. raise
  172. # Send the request
  173. flush_data(address, parameters)
  174. # Now do linking and loading
  175. if link is not None:
  176. # Execute linker
  177. timeout_val = 10
  178. proc2 = execute("link_and_load", [address, username] + link, wait=False)
  179. while proc2.returncode is None:
  180. time.sleep(0.01)
  181. proc2.poll()
  182. timeout_val -= 0.01
  183. if timeout_val < 0:
  184. kill(proc2)
  185. print("Linking timeout expired!")
  186. return False
  187. if proc.returncode is not None:
  188. # Modelverse has already terminated, which isn't a good sign!
  189. return False
  190. for inp in inputs:
  191. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "element_type": "V", "value": inp, "username": username})), timeout=1).read()
  192. proc.poll()
  193. if proc.returncode is not None:
  194. # Modelverse has already terminated, which isn't a good sign!
  195. return False
  196. counter = 0
  197. for e in expected:
  198. print("Expect " + str(e))
  199. c = len(e) if isinstance(e, set) else 1
  200. for _ in range(c):
  201. try:
  202. proc.poll()
  203. if proc.returncode is not None:
  204. # Modelverse has already terminated, which isn't a good sign!
  205. return False
  206. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username})), timeout=240 if not timeout else 20).read()
  207. except:
  208. if timeout:
  209. return True
  210. else:
  211. raise
  212. print("Got %s, expect %s" % (val, e))
  213. if isinstance(e, set):
  214. assert str(val) in e
  215. if str(val) not in e:
  216. return False
  217. else:
  218. assert str(val) == e
  219. if str(val) != e:
  220. return False
  221. # All passed!
  222. return not timeout
  223. finally:
  224. kill(proc)
  225. def get_constructor(code):
  226. with open("__constraint.al", "w") as f:
  227. f.write(code)
  228. f.flush()
  229. constructors = do_compile("__constraint.al", "interface/HUTN/grammars/actionlanguage.g", "CS")
  230. return constructors