utils.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. import operator
  13. sys.path.append("interface/HUTN")
  14. sys.path.append("scripts")
  15. from hutn_compiler.compiler import main as do_compile
  16. from check_objects import to_recompile
  17. USERNAME = "test_user"
  18. PARALLEL_PUSH = True
  19. BOOTSTRAP_FOLDER_NAME = "bootstrap"
  20. CURRENT_FOLDER_NAME = "performance"
  21. PORTS = set()
  22. OPTIMIZATION_LEVEL_LEGACY_INTERPRETER = "legacy-interpreter"
  23. OPTIMIZATION_LEVEL_INTERPRETER = "interpreter"
  24. OPTIMIZATION_LEVEL_BASELINE_JIT = "baseline-jit"
  25. ALL_OPTIMIZATION_LEVELS = [
  26. OPTIMIZATION_LEVEL_LEGACY_INTERPRETER,
  27. OPTIMIZATION_LEVEL_INTERPRETER,
  28. OPTIMIZATION_LEVEL_BASELINE_JIT
  29. ]
  30. class ModelverseTerminated(Exception):
  31. """An exception that tells the user that the Modelverse has terminated."""
  32. pass
  33. def get_code_folder_name():
  34. """Gets the name of the code folder."""
  35. return '%s/code' % CURRENT_FOLDER_NAME
  36. def get_free_port():
  37. """Gets a unique new port."""
  38. while 1:
  39. port = random.randint(10000, 20000)
  40. # Check if this port is in the set of ports.
  41. if port not in PORTS:
  42. # We have found a unique port. Add it to the set and return.
  43. PORTS.add(port)
  44. return port
  45. def execute(scriptname, parameters=None, wait=False):
  46. """Runs a script."""
  47. if os.name not in ["nt", "posix"]:
  48. # Stop now, as we would have no clue on how to kill its subtree
  49. raise Exception("Unknown OS version: " + str(os.name))
  50. command = [sys.executable, "scripts/%s.py" % scriptname] + (
  51. [] if parameters is None else parameters)
  52. if wait:
  53. return subprocess.call(command, shell=False)
  54. else:
  55. return subprocess.Popen(command, shell=False)
  56. def kill(process):
  57. """Kills the given process."""
  58. if os.name == "nt":
  59. subprocess.call(["taskkill", "/F", "/T", "/PID", "%i" % process.pid])
  60. elif os.name == "posix":
  61. subprocess.call(["pkill", "-P", "%i" % process.pid])
  62. def set_input_data(address, data):
  63. """Sets the Modelverse program's input data."""
  64. if data is not None:
  65. urllib2.urlopen(
  66. urllib2.Request(
  67. address,
  68. urllib.urlencode(
  69. {"op": "set_input", "data": json.dumps(data), "username": USERNAME})),
  70. timeout=10).read()
  71. else:
  72. return []
  73. def compile_file(address, mod_filename, filename, mode, proc):
  74. """Compiles the given file."""
  75. # Load in the file required
  76. try:
  77. timeout_val = 240
  78. username = str(random.random())
  79. while 1:
  80. proc2 = execute(
  81. "compile", [address, mod_filename, username, filename, mode], wait=False)
  82. if proc.returncode is not None:
  83. # Modelverse has already terminated, which isn't a good sign!
  84. raise Exception("Modelverse died!")
  85. while proc2.returncode is None:
  86. time.sleep(0.01)
  87. proc2.poll()
  88. timeout_val -= 0.01
  89. if timeout_val < 0:
  90. kill(proc2)
  91. print("Compilation timeout expired!")
  92. return False
  93. if proc2.returncode != 2:
  94. break
  95. # Make sure everything stopped correctly
  96. assert proc2.returncode == 0
  97. if proc2.returncode != 0:
  98. return False
  99. except:
  100. raise
  101. finally:
  102. try:
  103. kill(proc2)
  104. except UnboundLocalError:
  105. pass
  106. def run_file(files, parameters, mode, handle_output, optimization_level=None):
  107. """Compiles the given sequence of files, feeds them the given input in the given mode,
  108. and handles their output."""
  109. # Resolve file
  110. import os.path
  111. time.sleep(0.01)
  112. port = get_free_port()
  113. address = "http://127.0.0.1:%i" % port
  114. try:
  115. # Run Modelverse server
  116. modelverse_args = [str(port)]
  117. if optimization_level is not None:
  118. modelverse_args.append('--kernel=%s' % optimization_level)
  119. proc = execute("run_local_modelverse", modelverse_args, wait=False)
  120. threads = []
  121. mod_files = []
  122. for filename in files:
  123. if os.path.isfile("%s/%s" % (get_code_folder_name(), filename)):
  124. mod_filename = "%s/%s" % (get_code_folder_name(), filename)
  125. elif os.path.isfile("%s/%s" % (BOOTSTRAP_FOLDER_NAME, filename)):
  126. mod_filename = "%s/%s" % (BOOTSTRAP_FOLDER_NAME, filename)
  127. else:
  128. raise Exception("File not found: %s" % filename)
  129. mod_files.append(mod_filename)
  130. to_compile = to_recompile(address, mod_files)
  131. for mod_filename in to_compile:
  132. if PARALLEL_PUSH:
  133. import threading
  134. threads.append(
  135. threading.Thread(
  136. target=compile_file,
  137. args=[address, mod_filename, mod_filename, mode, proc]))
  138. threads[-1].start()
  139. else:
  140. compile_file(address, mod_filename, mod_filename, mode, proc)
  141. if PARALLEL_PUSH:
  142. for t in threads:
  143. t.join()
  144. if mode[-1] == "O":
  145. # Fire up the linker
  146. val = execute("link_and_load", [address, USERNAME] + mod_files, wait=True)
  147. if val != 0:
  148. raise Exception("Linking error")
  149. # Send the request ...
  150. set_input_data(address, parameters)
  151. # ... and wait for replies
  152. while 1:
  153. val = urllib2.urlopen(
  154. urllib2.Request(
  155. address,
  156. urllib.urlencode({"op": "get_output", "username": USERNAME})),
  157. timeout=240).read()
  158. val = json.loads(val)
  159. if proc.returncode is not None:
  160. # Modelverse has terminated. This may or may not be what we want.
  161. raise ModelverseTerminated()
  162. if not handle_output(val):
  163. return
  164. # All passed!
  165. return
  166. except:
  167. raise
  168. finally:
  169. try:
  170. kill(proc)
  171. except UnboundLocalError:
  172. pass
  173. def run_file_to_completion(files, parameters, mode):
  174. """Compiles the given sequence of files, feeds them the given input in the given mode,
  175. and then collects and returns output."""
  176. results = []
  177. def handle_output(output):
  178. """Appends the given output to the list of results."""
  179. results.append(output)
  180. return True
  181. try:
  182. run_file(files, parameters, mode, handle_output)
  183. except ModelverseTerminated:
  184. return results
  185. def run_file_fixed_output_count(files, parameters, mode, output_count, optimization_level=None):
  186. """Compiles the given sequence of files, feeds them the given input in the given mode,
  187. and then collects and returns a fixed number of outputs."""
  188. results = []
  189. def handle_output(output):
  190. """Appends the given output to the list of results."""
  191. if len(results) < output_count:
  192. results.append(output)
  193. return True
  194. else:
  195. return False
  196. run_file(files, parameters, mode, handle_output, optimization_level)
  197. return results
  198. def run_file_single_output(files, parameters, mode, optimization_level=None):
  199. """Compiles the given sequence of files, feeds them the given input in the given mode,
  200. and then collects and returns a single output."""
  201. return run_file_fixed_output_count(files, parameters, mode, 1, optimization_level)[0]
  202. def run_perf_test(files, parameters, optimization_level, n_iterations=1):
  203. """Compiles the given sequence of files, feeds them the given input in the given mode,
  204. and then collects their output. This process is repeated n_iterations times. The
  205. return value is the average of all outputs."""
  206. result = 0.0
  207. for _ in xrange(n_iterations):
  208. result += float(
  209. run_file_single_output(
  210. files, [optimization_level] + parameters + [0], 'CO',
  211. optimization_level)) / float(n_iterations)
  212. return result
  213. def format_output(output):
  214. """Formats the output of `run_file_to_completion` as a string."""
  215. return '\n'.join(output)
  216. def define_perf_test(target_class, test_function, optimization_level):
  217. """Defines a performance test in the given class. The performance test calls the given function
  218. at the given optimization level."""
  219. setattr(
  220. target_class,
  221. 'test_%s' % optimization_level.replace('-', '_').lower(),
  222. lambda self: test_function(self, optimization_level))
  223. def define_perf_tests(target_class, test_function):
  224. """Defines performance tests in the given class. Each test calls the given function."""
  225. for optimization_level in ALL_OPTIMIZATION_LEVELS:
  226. define_perf_test(target_class, test_function, optimization_level)
  227. DEFAULT_PERF_FILE_NAME = 'perf_data.txt'
  228. def write_perf_to_file(test_name, optimization_level, result, file_name=DEFAULT_PERF_FILE_NAME):
  229. """Writes performance data to a file."""
  230. with open(file_name, "a") as perf_file:
  231. perf_file.write('%s:%s:%f\n' % (test_name, optimization_level, result))
  232. def parse_perf_data(file_name):
  233. """Parses the performance data in the given file."""
  234. results = {}
  235. with open(file_name, 'r') as perf_file:
  236. for line in perf_file.readlines():
  237. test_name, optimization_level, result = line.strip().split(':')
  238. if optimization_level not in results:
  239. results[optimization_level] = []
  240. results[optimization_level].append((test_name, result))
  241. return sorted(results.items(), key=operator.itemgetter(1))