metadata.py 16 KB

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