utils.py 9.2 KB

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