utils.py 8.7 KB

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