metadata.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. ]
  15. def __init__(self, benchmarker=None):
  16. self.benchmarker = benchmarker
  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. log("Error loading config: {!s}".format(config_file_name),
  86. color=Fore.RED)
  87. raise Exception("Error loading config file")
  88. # Find all tests in the config file
  89. config_tests = self.parse_config(config,
  90. 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(self.benchmarker.config.test,
  112. self.benchmarker.config.exclude)
  113. def gather_frameworks(self, include=None, exclude=None):
  114. '''
  115. Return a dictionary mapping frameworks->[test1,test2,test3]
  116. for quickly grabbing all tests in a grouped manner.
  117. Args have the same meaning as gather_tests
  118. '''
  119. tests = self.gather_tests(include, exclude)
  120. frameworks = dict()
  121. for test in tests:
  122. if test.framework not in frameworks:
  123. frameworks[test.framework] = []
  124. frameworks[test.framework].append(test)
  125. return frameworks
  126. def has_file(self, test_dir, filename):
  127. '''
  128. Returns True if the file exists in the test dir
  129. '''
  130. path = test_dir
  131. if not self.benchmarker.config.lang_root in path:
  132. path = os.path.join(self.benchmarker.config.lang_root, path)
  133. return os.path.isfile("{!s}/{!s}".format(path, filename))
  134. @staticmethod
  135. def test_order(type_name):
  136. """
  137. This sort ordering is set up specifically to return the length
  138. of the test name. There were SO many problems involved with
  139. 'plaintext' being run first (rather, just not last) that we
  140. needed to ensure that it was run last for every framework.
  141. """
  142. return len(type_name)
  143. def parse_config(self, config, directory):
  144. """
  145. Parses a config file into a list of FrameworkTest objects
  146. """
  147. from toolset.benchmark.framework_test import FrameworkTest
  148. tests = []
  149. # The config object can specify multiple tests
  150. # Loop over them and parse each into a FrameworkTest
  151. for test in config['tests']:
  152. tests_to_run = [name for (name, keys) in test.iteritems()]
  153. if "default" not in tests_to_run:
  154. log("Framework %s does not define a default test in benchmark_config.json"
  155. % config['framework'],
  156. 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,
  162. directory)
  163. # Map test type to a parsed FrameworkTestType object
  164. runTests = dict()
  165. for type_name, type_obj in self.benchmarker.config.types.iteritems(
  166. ):
  167. try:
  168. # Makes a FrameWorkTestType object using some of the keys in config
  169. # e.g. JsonTestType uses "json_url"
  170. runTests[type_name] = type_obj.copy().parse(test_keys)
  171. except AttributeError:
  172. # This is quite common - most tests don't support all types
  173. # Quitely log it and move on (debug logging is on in travis and this causes
  174. # ~1500 lines of debug, so I'm totally ignoring it for now
  175. # log("Missing arguments for test type %s for framework test %s" % (type_name, test_name))
  176. pass
  177. # We need to sort by test_type to run
  178. sortedTestKeys = sorted(
  179. runTests.keys(), key=Metadata.test_order)
  180. sortedRunTests = OrderedDict()
  181. for sortedTestKey in sortedTestKeys:
  182. sortedRunTests[sortedTestKey] = runTests[sortedTestKey]
  183. # Prefix all test names with framework except 'default' test
  184. # Done at the end so we may still refer to the primary test as `default` in benchmark config error messages
  185. if test_name == 'default':
  186. test_name = config['framework']
  187. else:
  188. test_name = "%s-%s" % (config['framework'], test_name)
  189. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  190. tests.append(
  191. FrameworkTest(test_name, directory, self.benchmarker,
  192. sortedRunTests, test_keys))
  193. return tests
  194. def list_test_metadata(self):
  195. '''
  196. Prints the metadata for all the available tests
  197. '''
  198. all_tests = self.gather_tests()
  199. all_tests_json = json.dumps(map(lambda test: {
  200. "name": test.name,
  201. "approach": test.approach,
  202. "classification": test.classification,
  203. "database": test.database,
  204. "framework": test.framework,
  205. "language": test.language,
  206. "orm": test.orm,
  207. "platform": test.platform,
  208. "webserver": test.webserver,
  209. "os": test.os,
  210. "database_os": test.database_os,
  211. "display_name": test.display_name,
  212. "notes": test.notes,
  213. "versus": test.versus
  214. }, all_tests))
  215. with open(
  216. os.path.join(self.benchmarker.results.directory,
  217. "test_metadata.json"), "w") as f:
  218. f.write(all_tests_json)
  219. @staticmethod
  220. def validate_test(test_name, test_keys, directory):
  221. """
  222. Validate and normalizes benchmark config values for this test based on a schema
  223. """
  224. recommended_lang = directory.split('/')[-2]
  225. windows_url = "https://github.com/TechEmpower/FrameworkBenchmarks/issues/1038"
  226. schema = {
  227. 'language': {
  228. # Language is the only key right now with no 'allowed' key that can't
  229. # have a "None" value
  230. 'required':
  231. True,
  232. 'help': ('language',
  233. 'The language of the framework used, suggestion: %s' %
  234. recommended_lang)
  235. },
  236. 'webserver': {
  237. 'help':
  238. ('webserver',
  239. 'Name of the webserver also referred to as the "front-end server"'
  240. )
  241. },
  242. 'classification': {
  243. 'allowed': [('Fullstack', '...'), ('Micro', '...'),
  244. ('Platform', '...')]
  245. },
  246. 'database': {
  247. 'allowed':
  248. Metadata.supported_dbs +
  249. [('None',
  250. 'No database was used for these tests, as is the case with Json Serialization and Plaintext'
  251. )]
  252. },
  253. 'approach': {
  254. 'allowed': [('Realistic', '...'), ('Stripped', '...')]
  255. },
  256. 'orm': {
  257. 'required_with':
  258. 'database',
  259. 'allowed':
  260. [('Full',
  261. 'Has a full suite of features like lazy loading, caching, multiple language support, sometimes pre-configured with scripts.'
  262. ),
  263. ('Micro',
  264. 'Has basic database driver capabilities such as establishing a connection and sending queries.'
  265. ),
  266. ('Raw',
  267. 'Tests that do not use an ORM will be classified as "raw" meaning they use the platform\'s raw database connectivity.'
  268. )]
  269. },
  270. 'platform': {
  271. 'help':
  272. ('platform',
  273. 'Name of the platform this framework runs on, e.g. Node.js, PyPy, hhvm, JRuby ...'
  274. )
  275. },
  276. 'framework': {
  277. # Guaranteed to be here and correct at this point
  278. # key is left here to produce the set of required keys
  279. },
  280. 'os': {
  281. 'allowed':
  282. [('Linux',
  283. 'Our best-supported host OS, it is recommended that you build your tests for Linux hosts'
  284. ),
  285. ('Windows',
  286. 'TFB is not fully-compatible on windows, contribute towards our work on compatibility: %s'
  287. % windows_url)]
  288. },
  289. 'database_os': {
  290. 'required_with':
  291. 'database',
  292. 'allowed':
  293. [('Linux',
  294. 'Our best-supported host OS, it is recommended that you build your tests for Linux hosts'
  295. ),
  296. ('Windows',
  297. 'TFB is not fully-compatible on windows, contribute towards our work on compatibility: %s'
  298. % windows_url)]
  299. }
  300. }
  301. # Check the (all optional) test urls
  302. Metadata.validate_urls(test_name, test_keys)
  303. def get_test_val(k):
  304. return test_keys.get(k, "none").lower()
  305. def throw_incorrect_key(k):
  306. msg = (
  307. "Invalid `%s` value specified for test \"%s\" in framework \"%s\"; suggestions:\n"
  308. % (k, test_name, test_keys['framework']))
  309. helpinfo = ('\n').join([
  310. " `%s` -- %s" % (v, desc)
  311. for (v, desc) in zip(acceptable_values, descriptors)
  312. ])
  313. fullerr = msg + helpinfo + "\n"
  314. raise Exception(fullerr)
  315. # Check values of keys against schema
  316. for key in schema.keys():
  317. val = get_test_val(key)
  318. test_keys[key] = val
  319. if val == "none":
  320. # incorrect if key requires a value other than none
  321. if schema[key].get('required', False):
  322. throw_incorrect_key(key)
  323. # certain keys are only required if another key is not none
  324. if 'required_with' in schema[key]:
  325. if get_test_val(schema[key]['required_with']) == "none":
  326. continue
  327. else:
  328. throw_incorrect_key(key)
  329. # if we're here, the key needs to be one of the "allowed" values
  330. if 'allowed' in schema[key]:
  331. allowed = schema[key].get('allowed', [])
  332. acceptable_values, descriptors = zip(*allowed)
  333. acceptable_values = [a.lower() for a in acceptable_values]
  334. if val not in acceptable_values:
  335. throw_incorrect_key(key)
  336. return test_keys
  337. @staticmethod
  338. def validate_urls(test_name, test_keys):
  339. """
  340. Separated from validate_test because urls are not required anywhere. We know a url is incorrect if it is
  341. empty or does not start with a "/" character. There is no validation done to ensure the url conforms to
  342. the suggested url specifications, although those suggestions are presented if a url fails validation here.
  343. """
  344. example_urls = {
  345. "json_url":
  346. "/json",
  347. "db_url":
  348. "/mysql/db",
  349. "query_url":
  350. "/mysql/queries?queries= or /mysql/queries/",
  351. "fortune_url":
  352. "/mysql/fortunes",
  353. "update_url":
  354. "/mysql/updates?queries= or /mysql/updates/",
  355. "plaintext_url":
  356. "/plaintext",
  357. "cached_query_url":
  358. "/mysql/cached_queries?queries= or /mysql/cached_queries"
  359. }
  360. for test_url in [
  361. "json_url", "db_url", "query_url", "fortune_url", "update_url",
  362. "plaintext_url", "cached_query_url"
  363. ]:
  364. key_value = test_keys.get(test_url, None)
  365. if key_value is not None and not key_value.startswith('/'):
  366. errmsg = """`%s` field in test \"%s\" does not appear to be a valid url: \"%s\"\n
  367. Example `%s` url: \"%s\"
  368. """ % (test_url, test_name, key_value, test_url,
  369. example_urls[test_url])
  370. raise Exception(errmsg)