utils.py 8.5 KB

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