metadata_helper.py 14 KB

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