metadata.py 17 KB

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