utils.py 7.8 KB

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