utils.py 7.4 KB

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