utils.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import ConfigParser
  2. import os
  3. import glob
  4. import json
  5. import socket
  6. from ast import literal_eval
  7. def gather_docker_dependencies(docker_file):
  8. '''
  9. Gathers all the known docker dependencies for the given docker image.
  10. '''
  11. # Avoid setting up a circular import
  12. from setup.linux import setup_util
  13. deps = []
  14. if os.path.exists(docker_file):
  15. with open(docker_file) as fp:
  16. line = fp.readline()
  17. if line:
  18. tokens = line.strip().split(' ')
  19. if tokens[0] == "FROM":
  20. # This is magic that our base image points to
  21. if tokens[1] != "ubuntu:16.04":
  22. depTokens = tokens[1].strip().split(':')
  23. deps.append(depTokens[0])
  24. dep_docker_file = os.path.join(setup_util.get_fwroot(),
  25. "toolset", "setup", "linux", "docker", depTokens[0] + ".dockerfile")
  26. deps.extend(gather_docker_dependencies(dep_docker_file))
  27. return deps
  28. def gather_langauges():
  29. '''
  30. Gathers all the known languages in the suite via the folder names
  31. beneath FWROOT.
  32. '''
  33. # Avoid setting up a circular import
  34. from setup.linux import setup_util
  35. lang_dir = os.path.join(setup_util.get_fwroot(), "frameworks")
  36. langs = []
  37. for dir in glob.glob(os.path.join(lang_dir, "*")):
  38. langs.append(dir.replace(lang_dir,"")[1:])
  39. return langs
  40. def gather_tests(include = [], exclude=[], benchmarker=None):
  41. '''
  42. Given test names as strings, returns a list of FrameworkTest objects.
  43. For example, 'aspnet-mysql-raw' turns into a FrameworkTest object with
  44. variables for checking the test directory, the test database os, and
  45. other useful items.
  46. With no arguments, every test in this framework will be returned.
  47. With include, only tests with this exact name will be returned.
  48. With exclude, all tests but those excluded will be returned.
  49. A benchmarker is needed to construct full FrameworkTest objects. If
  50. one is not provided, a default Benchmarker will be created.
  51. '''
  52. # Avoid setting up a circular import
  53. from benchmark import framework_test
  54. from benchmark.benchmarker import Benchmarker
  55. from setup.linux import setup_util
  56. # Help callers out a bit
  57. if include is None:
  58. include = []
  59. if exclude is None:
  60. exclude = []
  61. # Old, hacky method to exclude all tests was to
  62. # request a test known to not exist, such as ''.
  63. # If test '' was requested, short-circuit and return
  64. # nothing immediately
  65. if len(include) == 1 and '' in include:
  66. return []
  67. # Setup default Benchmarker using example configuration
  68. if benchmarker is None:
  69. default_config = setup_util.get_fwroot() + "/benchmark.cfg"
  70. config = ConfigParser.SafeConfigParser()
  71. config.readfp(open(default_config))
  72. defaults = dict(config.items("Defaults"))
  73. # Convert strings into proper python types
  74. for k,v in defaults.iteritems():
  75. try:
  76. defaults[k] = literal_eval(v)
  77. except Exception:
  78. pass
  79. # Ensure we only run the __init__ method of Benchmarker
  80. defaults['install'] = None
  81. defaults['results_name'] = "(unspecified, datetime = %Y-%m-%d %H:%M:%S)"
  82. defaults['results_environment'] = "My Server Environment"
  83. defaults['test_dir'] = None
  84. defaults['quiet'] = True
  85. benchmarker = Benchmarker(defaults)
  86. # Search for configuration files
  87. fwroot = setup_util.get_fwroot()
  88. config_files = []
  89. if benchmarker.test_dir:
  90. for test_dir in benchmarker.test_dir:
  91. dir_config_files = glob.glob("{!s}/frameworks/{!s}/benchmark_config.json".format(fwroot, test_dir))
  92. if len(dir_config_files):
  93. config_files.extend(dir_config_files)
  94. else:
  95. raise Exception("Unable to locate tests in test-dir: {!s}".format(test_dir))
  96. else:
  97. config_files.extend(glob.glob("{!s}/frameworks/*/*/benchmark_config.json".format(fwroot)))
  98. tests = []
  99. for config_file_name in config_files:
  100. config = None
  101. with open(config_file_name, 'r') as config_file:
  102. try:
  103. config = json.load(config_file)
  104. except ValueError:
  105. # User-friendly errors
  106. print("Error loading '{!s}'.".format(config_file_name))
  107. raise
  108. # Find all tests in the config file
  109. config_tests = framework_test.parse_config(config,
  110. os.path.dirname(config_file_name), benchmarker)
  111. # Filter
  112. for test in config_tests:
  113. if len(include) is 0 and len(exclude) is 0:
  114. # No filters, we are running everything
  115. tests.append(test)
  116. elif test.name in exclude:
  117. continue
  118. elif test.name in include:
  119. tests.append(test)
  120. else:
  121. # An include list exists, but this test is
  122. # not listed there, so we ignore it
  123. pass
  124. # Ensure we were able to locate everything that was
  125. # explicitly included
  126. if 0 != len(include):
  127. names = {test.name for test in tests}
  128. if 0 != len(set(include) - set(names)):
  129. missing = list(set(include) - set(names))
  130. raise Exception("Unable to locate tests %s" % missing)
  131. tests.sort(key=lambda x: x.name)
  132. return tests
  133. def gather_frameworks(include = [], exclude=[], benchmarker=None):
  134. '''Return a dictionary mapping frameworks->[test1,test2,test3]
  135. for quickly grabbing all tests in a grouped manner.
  136. Args have the same meaning as gather_tests'''
  137. tests = gather_tests(include, exclude, benchmarker)
  138. frameworks = dict()
  139. for test in tests:
  140. if test.framework not in frameworks:
  141. frameworks[test.framework] = []
  142. frameworks[test.framework].append(test)
  143. return frameworks
  144. def header(message, top='-', bottom='-'):
  145. '''
  146. Generates a clean header
  147. '''
  148. topheader = (top * 80)[:80]
  149. bottomheader = (bottom * 80)[:80]
  150. result = ""
  151. if topheader != "":
  152. result += "%s" % topheader
  153. if message != "":
  154. if result == "":
  155. result = " %s" % message
  156. else:
  157. result += "\n %s" % message
  158. if bottomheader != "":
  159. if result == "":
  160. result = "%s" % bottomheader
  161. else:
  162. result += "\n%s" % bottomheader
  163. return result + '\n'
  164. def check_services(services):
  165. def check_service(address, port):
  166. try:
  167. s = socket.socket()
  168. s.settimeout(20)
  169. s.connect((address, port))
  170. return (True, "")
  171. except Exception as ex:
  172. return (False, ex)
  173. finally:
  174. s.close
  175. res = []
  176. for s in services:
  177. r = check_service(s[1], s[2])
  178. res.append((s[0], r[0], str(r[1])))
  179. return res
  180. def verify_database_connections(services):
  181. allGo = True
  182. messages = []
  183. for r in check_services(services):
  184. if r[1]:
  185. messages.append(r[0] + ": is GO!")
  186. else:
  187. messages.append(r[0] + ": is _NO_ GO!: ERROR: " + r[2])
  188. allGo = False
  189. return (allGo, messages)