utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. taskname = "test_task"
  17. parallel_push = True
  18. INIT_TIMEOUT = 30
  19. TIMEOUT = 2000
  20. try:
  21. import pytest
  22. slow = pytest.mark.skipif(
  23. not pytest.config.getoption("--runslow"),
  24. reason="need --runslow option to run"
  25. )
  26. except:
  27. slow = lambda i:i
  28. ports = set()
  29. def getFreePort():
  30. """Gets a unique new port."""
  31. while 1:
  32. port = random.randint(10000, 20000)
  33. # Check if this port is in the set of ports.
  34. if port not in ports:
  35. # We have found a unique port. Add it to the set and return.
  36. ports.add(port)
  37. return port
  38. def execute(scriptname, parameters=[], wait=False):
  39. if os.name not in ["nt", "posix"]:
  40. # Stop now, as we would have no clue on how to kill its subtree
  41. raise Exception("Unknown OS version: " + str(os.name))
  42. command = [sys.executable, "-u", "scripts/%s.py" % scriptname] + parameters
  43. if wait:
  44. return subprocess.call(command, shell=False)
  45. else:
  46. return subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
  47. def kill(process):
  48. if os.name == "nt":
  49. subprocess.call(["taskkill", "/F", "/T", "/PID", "%i" % process.pid])
  50. elif os.name == "posix":
  51. # Kill parents
  52. subprocess.call(["pkill", "-P", "%i" % process.pid])
  53. # Kill self
  54. subprocess.call(["kill", "%i" % process.pid])
  55. def flush_data(address, data):
  56. if data:
  57. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": taskname})), timeout=INIT_TIMEOUT).read()
  58. return []
  59. def compile_file(address, mod_filename, filename, mode, proc):
  60. # Load in the file required
  61. try:
  62. timeout_val = 240
  63. import random
  64. taskname = str(random.random())
  65. while 1:
  66. proc2 = execute("compile", [address, mod_filename, taskname, filename, mode], wait=False)
  67. if proc.returncode is not None:
  68. # Modelverse has already terminated, which isn't a good sign!
  69. raise Exception("Modelverse died!")
  70. while proc2.returncode is None:
  71. time.sleep(0.01)
  72. proc2.poll()
  73. timeout_val -= 0.01
  74. if timeout_val < 0:
  75. kill(proc2)
  76. print("Compilation timeout expired!")
  77. return False
  78. if proc2.returncode != 2:
  79. break
  80. # Make sure everything stopped correctly
  81. assert proc2.returncode == 0
  82. if proc2.returncode != 0:
  83. return False
  84. except:
  85. raise
  86. finally:
  87. try:
  88. kill(proc2)
  89. except UnboundLocalError:
  90. pass
  91. def start_mvc():
  92. address = "http://127.0.0.1:%s" % getFreePort()
  93. proc = execute("run_MvC_server", [address], wait=False)
  94. # TODO Return only when everything is fine! (i.e., parse the output of proc and wait until it contains "MvC is ready"
  95. while 1:
  96. l = proc.stdout.readline()
  97. if "MvC is ready" in l:
  98. return proc, address
  99. def run_file(files, parameters, expected, wait=False):
  100. # Resolve file
  101. import os.path
  102. if wait is True:
  103. expected = None
  104. time.sleep(0.01)
  105. port = getFreePort()
  106. address = "http://127.0.0.1:%i" % port
  107. try:
  108. # Run Modelverse server
  109. proc = execute("run_local_modelverse", [str(port)], wait=False)
  110. threads = []
  111. mod_files = []
  112. for filename in files:
  113. if os.path.isfile(filename):
  114. mod_filename = filename
  115. elif os.path.isfile("integration/code/%s" % filename):
  116. mod_filename = "integration/code/%s" % filename
  117. elif os.path.isfile("bootstrap/%s" % filename):
  118. mod_filename = "bootstrap/%s" % filename
  119. else:
  120. raise Exception("File not found: %s" % filename)
  121. mod_files.append(mod_filename)
  122. to_compile = to_recompile(address, mod_files)
  123. for mod_filename in to_compile:
  124. if mod_filename.endswith(".mvc"):
  125. model_mode = "MO"
  126. mod_files.remove(mod_filename)
  127. else:
  128. model_mode = "PO"
  129. if parallel_push:
  130. import threading
  131. threads.append(threading.Thread(target=compile_file, args=[address, mod_filename, mod_filename, model_mode, proc]))
  132. threads[-1].start()
  133. else:
  134. compile_file(address, mod_filename, mod_filename, model_mode, proc)
  135. if parallel_push:
  136. for t in threads:
  137. t.join()
  138. # Fire up the linker
  139. val = execute("link_and_load", [address, taskname] + mod_files, wait=True)
  140. if val != 0:
  141. raise Exception("Linking error")
  142. # Send the request ...
  143. flush_data(address, parameters)
  144. # ... and wait for replies
  145. if expected is None:
  146. while 1:
  147. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname})), timeout=TIMEOUT).read()
  148. val = json.loads(val)
  149. print(val)
  150. for e in expected:
  151. c = len(e) if isinstance(e, set) else 1
  152. if isinstance(e, set):
  153. # Copy set before we start popping from it, as it might be reused elsewhere
  154. e = set(e)
  155. for _ in range(c):
  156. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname})), timeout=TIMEOUT).read()
  157. val = json.loads(val)
  158. if proc.returncode is not None:
  159. # Modelverse has already terminated, which isn't a good sign!
  160. raise Exception("Modelverse died!")
  161. print("Got %s, expect %s" % (val, e))
  162. if isinstance(e, set):
  163. assert val in e
  164. if val not in e:
  165. return False
  166. e.remove(val)
  167. elif e is None:
  168. # Skip output value
  169. pass
  170. else:
  171. assert val == e
  172. if val != e:
  173. return False
  174. # All passed!
  175. return True
  176. except:
  177. raise
  178. finally:
  179. try:
  180. kill(proc)
  181. except UnboundLocalError:
  182. pass
  183. def run_barebone(parameters, expected, interface="0", timeout=False, wait=False, link=None, inputs=[]):
  184. port = getFreePort()
  185. address = "http://127.0.0.1:%i" % port
  186. try:
  187. # Run Modelverse server
  188. proc = execute("run_local_modelverse", [str(port)], wait=False)
  189. # Create task and set interface
  190. timeout_val = INIT_TIMEOUT
  191. start = time.time()
  192. while 1:
  193. proc.poll()
  194. if proc.returncode is not None:
  195. # Modelverse has already terminated, which isn't a good sign!
  196. return False
  197. try:
  198. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % taskname, "taskname": "task_manager"})), timeout=INIT_TIMEOUT).read()
  199. if interface is not None:
  200. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": interface, "taskname": taskname})), timeout=INIT_TIMEOUT).read()
  201. break
  202. except:
  203. time.sleep(0.01)
  204. if time.time() - start > timeout_val:
  205. raise
  206. # Send the request
  207. print("Sending data: " + str(parameters))
  208. flush_data(address, parameters)
  209. # Now do linking and loading
  210. if link is not None:
  211. # Execute linker
  212. timeout_val = INIT_TIMEOUT
  213. proc2 = execute("link_and_load", [address, taskname] + link, wait=False)
  214. while proc2.returncode is None:
  215. time.sleep(0.01)
  216. proc2.poll()
  217. timeout_val -= 0.01
  218. if timeout_val < 0:
  219. kill(proc2)
  220. print("Linking timeout expired!")
  221. return False
  222. if proc.returncode is not None:
  223. # Modelverse has already terminated, which isn't a good sign!
  224. return False
  225. for inp in inputs:
  226. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": inp, "taskname": taskname})), timeout=INIT_TIMEOUT).read()
  227. proc.poll()
  228. if proc.returncode is not None:
  229. # Modelverse has already terminated, which isn't a good sign!
  230. return False
  231. counter = 0
  232. for e in expected:
  233. c = len(e) if isinstance(e, set) else 1
  234. for _ in range(c):
  235. try:
  236. proc.poll()
  237. if proc.returncode is not None:
  238. # Modelverse has already terminated, which isn't a good sign!
  239. return False
  240. val = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname})), timeout=TIMEOUT if not timeout else INIT_TIMEOUT).read()
  241. val = json.loads(val)
  242. except:
  243. if timeout:
  244. return True
  245. else:
  246. raise
  247. #print("Got %s, expect %s" % (val, e))
  248. if isinstance(e, set):
  249. assert val in e
  250. if val not in e:
  251. return False
  252. e.remove(val)
  253. elif e is None:
  254. # Skip this input
  255. pass
  256. else:
  257. assert val == e
  258. if val != e:
  259. return False
  260. # All passed!
  261. return not timeout
  262. finally:
  263. kill(proc)
  264. def get_constructor(code):
  265. code_fragments = code.split("\n")
  266. code_fragments = [i for i in code_fragments if i.strip() != ""]
  267. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  268. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  269. code_fragments = [i[initial_tabs:] for i in code_fragments]
  270. code_fragments.append("")
  271. code = "\n".join(code_fragments)
  272. with open("__constraint.alc", "w") as f:
  273. f.write(code)
  274. f.flush()
  275. constructors = do_compile("__constraint.alc", "interface/HUTN/grammars/actionlanguage.g", "CS")
  276. return constructors
  277. def get_model_constructor(code):
  278. # First change multiple spaces to a tab
  279. code_fragments = code.split("\n")
  280. code_fragments = [i for i in code_fragments if i.strip() != ""]
  281. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  282. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  283. code_fragments = [i[initial_tabs:] for i in code_fragments]
  284. code_fragments.append("")
  285. code = "\n".join(code_fragments)
  286. with open("__model.mvc", "w") as f:
  287. f.write(code)
  288. f.flush()
  289. return get_model_constructor_2("__model.mvc")
  290. def get_model_constructor_2(f):
  291. return do_compile(f, "interface/HUTN/grammars/modelling.g", "M") + ["exit"]