metadata_helper.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import os
  2. import glob
  3. import json
  4. from collections import OrderedDict
  5. from toolset.utils.output_helper import log
  6. def gather_langauges(benchmarker_config):
  7. '''
  8. Gathers all the known languages in the suite via the folder names
  9. beneath FWROOT.
  10. '''
  11. lang_dir = os.path.join(benchmarker_config.fwroot, "frameworks")
  12. langs = []
  13. for dir in glob.glob(os.path.join(lang_dir, "*")):
  14. langs.append(dir.replace(lang_dir, "")[1:])
  15. return langs
  16. def gather_tests(include=[], exclude=[], benchmarker_config=None,
  17. results=None):
  18. '''
  19. Given test names as strings, returns a list of FrameworkTest objects.
  20. For example, 'aspnet-mysql-raw' turns into a FrameworkTest object with
  21. variables for checking the test directory, the test database os, and
  22. other useful items.
  23. With no arguments, every test in this framework will be returned.
  24. With include, only tests with this exact name will be returned.
  25. With exclude, all tests but those excluded will be returned.
  26. A config is needed to construct full FrameworkTest objects. If
  27. one is not provided, a default config will be created.
  28. '''
  29. # Help callers out a bit
  30. if include is None:
  31. include = []
  32. if exclude is None:
  33. exclude = []
  34. # Old, hacky method to exclude all tests was to
  35. # request a test known to not exist, such as ''.
  36. # If test '' was requested, short-circuit and return
  37. # nothing immediately
  38. if len(include) == 1 and '' in include:
  39. return []
  40. # Search for configuration files
  41. config_files = []
  42. if benchmarker_config.test_lang:
  43. benchmarker_config.test_dir = []
  44. for lang in benchmarker_config.test_lang:
  45. if os.path.exists("{!s}/frameworks/{!s}".format(
  46. benchmarker_config.fwroot, lang)):
  47. for test_dir in os.listdir("{!s}/frameworks/{!s}".format(
  48. benchmarker_config.fwroot, lang)):
  49. benchmarker_config.test_dir.append("{!s}/{!s}".format(
  50. lang, test_dir))
  51. else:
  52. raise Exception(
  53. "Unable to locate language directory: {!s}".format(lang))
  54. if benchmarker_config.test_dir:
  55. for test_dir in benchmarker_config.test_dir:
  56. dir_config_files = glob.glob(
  57. "{!s}/frameworks/{!s}/benchmark_config.json".format(
  58. benchmarker_config.fwroot, test_dir))
  59. if len(dir_config_files):
  60. config_files.extend(dir_config_files)
  61. else:
  62. raise Exception(
  63. "Unable to locate tests in test-dir: {!s}".format(
  64. test_dir))
  65. else:
  66. config_files.extend(
  67. glob.glob("{!s}/frameworks/*/*/benchmark_config.json".format(
  68. benchmarker_config.fwroot)))
  69. tests = []
  70. for config_file_name in config_files:
  71. config = None
  72. with open(config_file_name, 'r') as config_file:
  73. try:
  74. config = json.load(config_file)
  75. except ValueError:
  76. raise Exception(
  77. "Error loading '{!s}'.".format(config_file_name))
  78. # Find all tests in the config file
  79. config_tests = parse_config(config, os.path.dirname(config_file_name),
  80. benchmarker_config, results)
  81. # Filter
  82. for test in config_tests:
  83. if len(include) is 0 and len(exclude) is 0:
  84. # No filters, we are running everything
  85. tests.append(test)
  86. elif test.name in exclude:
  87. continue
  88. elif test.name in include:
  89. tests.append(test)
  90. else:
  91. # An include list exists, but this test is
  92. # not listed there, so we ignore it
  93. pass
  94. # Ensure we were able to locate everything that was
  95. # explicitly included
  96. if 0 != len(include):
  97. names = {test.name for test in tests}
  98. if 0 != len(set(include) - set(names)):
  99. missing = list(set(include) - set(names))
  100. raise Exception("Unable to locate tests %s" % missing)
  101. tests.sort(key=lambda x: x.name)
  102. return tests
  103. def gather_remaining_tests(config, results):
  104. '''
  105. Gathers the tests remaining in a current benchmark run.
  106. '''
  107. return gather_tests(config.test, config.exclude, config, results)
  108. def gather_frameworks(include=[], exclude=[], config=None):
  109. '''
  110. Return a dictionary mapping frameworks->[test1,test2,test3]
  111. for quickly grabbing all tests in a grouped manner.
  112. Args have the same meaning as gather_tests
  113. '''
  114. tests = gather_tests(include, exclude, config)
  115. frameworks = dict()
  116. for test in tests:
  117. if test.framework not in frameworks:
  118. frameworks[test.framework] = []
  119. frameworks[test.framework].append(test)
  120. return frameworks
  121. def test_order(type_name):
  122. """
  123. This sort ordering is set up specifically to return the length
  124. of the test name. There were SO many problems involved with
  125. 'plaintext' being run first (rather, just not last) that we
  126. needed to ensure that it was run last for every framework.
  127. """
  128. return len(type_name)
  129. def parse_config(config, directory, benchmarker_config, results):
  130. """
  131. Parses a config file into a list of FrameworkTest objects
  132. """
  133. from toolset.benchmark.framework_test import FrameworkTest
  134. tests = []
  135. # The config object can specify multiple tests
  136. # Loop over them and parse each into a FrameworkTest
  137. for test in config['tests']:
  138. tests_to_run = [name for (name, keys) in test.iteritems()]
  139. if "default" not in tests_to_run:
  140. log("Framework %s does not define a default test in benchmark_config.json"
  141. % config['framework'])
  142. # Check that each test configuration is acceptable
  143. # Throw exceptions if a field is missing, or how to improve the field
  144. for test_name, test_keys in test.iteritems():
  145. # Validates the benchmark_config entry
  146. validate_test(test_name, test_keys, directory)
  147. # Map test type to a parsed FrameworkTestType object
  148. runTests = dict()
  149. for type_name, type_obj in benchmarker_config.types.iteritems():
  150. try:
  151. # Makes a FrameWorkTestType object using some of the keys in config
  152. # e.g. JsonTestType uses "json_url"
  153. runTests[type_name] = type_obj.copy().parse(test_keys)
  154. except AttributeError:
  155. # This is quite common - most tests don't support all types
  156. # Quitely log it and move on (debug logging is on in travis and this causes
  157. # ~1500 lines of debug, so I'm totally ignoring it for now
  158. # log("Missing arguments for test type %s for framework test %s" % (type_name, test_name))
  159. pass
  160. # We need to sort by test_type to run
  161. sortedTestKeys = sorted(runTests.keys(), key=test_order)
  162. sortedRunTests = OrderedDict()
  163. for sortedTestKey in sortedTestKeys:
  164. sortedRunTests[sortedTestKey] = runTests[sortedTestKey]
  165. # Prefix all test names with framework except 'default' test
  166. # Done at the end so we may still refer to the primary test as `default` in benchmark config error messages
  167. if test_name == 'default':
  168. test_name = config['framework']
  169. else:
  170. test_name = "%s-%s" % (config['framework'], test_name)
  171. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  172. tests.append(
  173. FrameworkTest(test_name, directory, benchmarker_config,
  174. results, sortedRunTests, test_keys))
  175. return tests
  176. def validate_test(test_name, test_keys, directory):
  177. """
  178. Validate benchmark config values for this test based on a schema
  179. """
  180. recommended_lang = directory.split('/')[-2]
  181. windows_url = "https://github.com/TechEmpower/FrameworkBenchmarks/issues/1038"
  182. schema = {
  183. 'language': {
  184. 'help':
  185. ('language', 'The language of the framework used, suggestion: %s' %
  186. recommended_lang)
  187. },
  188. 'webserver': {
  189. 'help':
  190. ('webserver',
  191. 'Name of the webserver also referred to as the "front-end server"'
  192. )
  193. },
  194. 'classification': {
  195. 'allowed': [('Fullstack', '...'), ('Micro', '...'), ('Platform',
  196. '...')]
  197. },
  198. 'database': {
  199. 'allowed':
  200. [('MySQL',
  201. 'One of the most popular databases around the web and in TFB'),
  202. ('Postgres',
  203. 'An advanced SQL database with a larger feature set than MySQL'),
  204. ('MongoDB', 'A popular document-store database'),
  205. ('Cassandra', 'A highly performant and scalable NoSQL database'),
  206. ('Elasticsearch',
  207. 'A distributed RESTful search engine that is used as a database for TFB tests'
  208. ),
  209. ('Redis',
  210. 'An open-sourced, BSD licensed, advanced key-value cache and store'
  211. ),
  212. ('SQLite',
  213. 'A network-less database, still supported for backwards compatibility'
  214. ), ('SQLServer', 'Microsoft\'s SQL implementation'),
  215. ('None',
  216. 'No database was used for these tests, as is the case with Json Serialization and Plaintext'
  217. )]
  218. },
  219. 'approach': {
  220. 'allowed': [('Realistic', '...'), ('Stripped', '...')]
  221. },
  222. 'orm': {
  223. 'allowed':
  224. [('Full',
  225. 'Has a full suite of features like lazy loading, caching, multiple language support, sometimes pre-configured with scripts.'
  226. ),
  227. ('Micro',
  228. 'Has basic database driver capabilities such as establishing a connection and sending queries.'
  229. ),
  230. ('Raw',
  231. 'Tests that do not use an ORM will be classified as "raw" meaning they use the platform\'s raw database connectivity.'
  232. )]
  233. },
  234. 'platform': {
  235. 'help':
  236. ('platform',
  237. 'Name of the platform this framework runs on, e.g. Node.js, PyPy, hhvm, JRuby ...'
  238. )
  239. },
  240. 'framework': {
  241. # Guranteed to be here and correct at this point
  242. # key is left here to produce the set of required keys
  243. },
  244. 'os': {
  245. 'allowed':
  246. [('Linux',
  247. 'Our best-supported host OS, it is recommended that you build your tests for Linux hosts'
  248. ),
  249. ('Windows',
  250. 'TFB is not fully-compatible on windows, contribute towards our work on compatibility: %s'
  251. % windows_url)]
  252. },
  253. 'database_os': {
  254. 'allowed':
  255. [('Linux',
  256. 'Our best-supported host OS, it is recommended that you build your tests for Linux hosts'
  257. ),
  258. ('Windows',
  259. 'TFB is not fully-compatible on windows, contribute towards our work on compatibility: %s'
  260. % windows_url)]
  261. }
  262. }
  263. # Confirm required keys are present
  264. required_keys = schema.keys()
  265. missing = list(set(required_keys) - set(test_keys))
  266. if len(missing) > 0:
  267. missingstr = (", ").join(map(str, missing))
  268. raise Exception(
  269. "benchmark_config.json for test %s is invalid, please amend by adding the following required keys: [%s]"
  270. % (test_name, missingstr))
  271. # Check the (all optional) test urls
  272. validate_urls(test_name, test_keys)
  273. # Check values of keys against schema
  274. for key in required_keys:
  275. val = test_keys.get(key, "").lower()
  276. has_predefined_acceptables = 'allowed' in schema[key]
  277. if has_predefined_acceptables:
  278. allowed = schema[key].get('allowed', [])
  279. acceptable_values, descriptors = zip(*allowed)
  280. acceptable_values = [a.lower() for a in acceptable_values]
  281. if val not in acceptable_values:
  282. msg = (
  283. "Invalid `%s` value specified for test \"%s\" in framework \"%s\"; suggestions:\n"
  284. % (key, test_name, test_keys['framework']))
  285. helpinfo = ('\n').join([
  286. " `%s` -- %s" % (v, desc)
  287. for (v, desc) in zip(acceptable_values, descriptors)
  288. ])
  289. fullerr = msg + helpinfo + "\n"
  290. raise Exception(fullerr)
  291. elif not has_predefined_acceptables and val == "":
  292. msg = (
  293. "Value for `%s` in test \"%s\" in framework \"%s\" was missing:\n"
  294. % (key, test_name, test_keys['framework']))
  295. helpinfo = " %s -- %s" % schema[key]['help']
  296. fullerr = msg + helpinfo + '\n'
  297. raise Exception(fullerr)
  298. def validate_urls(test_name, test_keys):
  299. """
  300. Separated from validate_test because urls are not required anywhere. We know a url is incorrect if it is
  301. empty or does not start with a "/" character. There is no validation done to ensure the url conforms to
  302. the suggested url specifications, although those suggestions are presented if a url fails validation here.
  303. """
  304. example_urls = {
  305. "json_url":
  306. "/json",
  307. "db_url":
  308. "/mysql/db",
  309. "query_url":
  310. "/mysql/queries?queries= or /mysql/queries/",
  311. "fortune_url":
  312. "/mysql/fortunes",
  313. "update_url":
  314. "/mysql/updates?queries= or /mysql/updates/",
  315. "plaintext_url":
  316. "/plaintext",
  317. "cached_query_url":
  318. "/mysql/cached_queries?queries= or /mysql/cached_queries"
  319. }
  320. for test_url in [
  321. "json_url", "db_url", "query_url", "fortune_url", "update_url",
  322. "plaintext_url", "cached_query_url"
  323. ]:
  324. key_value = test_keys.get(test_url, None)
  325. if key_value != None and not key_value.startswith('/'):
  326. errmsg = """`%s` field in test \"%s\" does not appear to be a valid url: \"%s\"\n
  327. Example `%s` url: \"%s\"
  328. """ % (test_url, test_name, key_value, test_url, example_urls[test_url])
  329. raise Exception(errmsg)