run-tests.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #!/usr/bin/env python
  2. import argparse
  3. import ConfigParser
  4. import sys
  5. import os
  6. import platform
  7. import multiprocessing
  8. import itertools
  9. import copy
  10. from benchmark.benchmarker import Benchmarker
  11. from setup.linux.unbuffered import Unbuffered
  12. from setup.linux import setup_util
  13. from ast import literal_eval
  14. # Enable cross-platform colored output
  15. from colorama import init
  16. init()
  17. class StoreSeqAction(argparse.Action):
  18. '''Helper class for parsing a sequence from the command line'''
  19. def __init__(self, option_strings, dest, nargs=None, **kwargs):
  20. super(StoreSeqAction, self).__init__(option_strings, dest, type=str, **kwargs)
  21. def __call__(self, parser, namespace, values, option_string=None):
  22. setattr(namespace, self.dest, self.parse_seq(values))
  23. def parse_seq(self, argument):
  24. result = argument.split(',')
  25. sequences = [x for x in result if ":" in x]
  26. for sequence in sequences:
  27. try:
  28. (start,step,end) = sequence.split(':')
  29. except ValueError:
  30. print(" Invalid: {!s}".format(sequence))
  31. print(" Requires start:step:end, e.g. 1:2:10")
  32. raise
  33. result.remove(sequence)
  34. result = result + range(int(start), int(end), int(step))
  35. return [abs(int(item)) for item in result]
  36. ###################################################################################################
  37. # Main
  38. ###################################################################################################
  39. def main(argv=None):
  40. ''' Runs the program. There are three ways to pass arguments
  41. 1) environment variables TFB_*
  42. 2) configuration file benchmark.cfg
  43. 3) command line flags
  44. In terms of precedence, 3 > 2 > 1, so config file trumps environment variables
  45. but command line flags have the final say
  46. '''
  47. # Do argv default this way, as doing it in the functional declaration sets it at compile time
  48. if argv is None:
  49. argv = sys.argv
  50. # Enable unbuffered output so messages will appear in the proper order with subprocess output.
  51. sys.stdout=Unbuffered(sys.stdout)
  52. # Update python environment
  53. # 1) Ensure the current directory (which should be the benchmark home directory) is in the path so that the tests can be imported.
  54. sys.path.append('.')
  55. # 2) Ensure toolset/setup/linux is in the path so that the tests can "import setup_util".
  56. sys.path.append('toolset/setup/linux')
  57. # Update environment for shell scripts
  58. os.environ['FWROOT'] = setup_util.get_fwroot()
  59. os.environ['IROOT'] = os.environ['FWROOT'] + '/installs'
  60. # 'Ubuntu', '14.04', 'trusty' respectively
  61. os.environ['TFB_DISTRIB_ID'], os.environ['TFB_DISTRIB_RELEASE'], os.environ['TFB_DISTRIB_CODENAME'] = platform.linux_distribution()
  62. print("FWROOT is {!s}.".format(os.environ['FWROOT']))
  63. conf_parser = argparse.ArgumentParser(
  64. description=__doc__,
  65. formatter_class=argparse.RawDescriptionHelpFormatter,
  66. add_help=False)
  67. conf_parser.add_argument(
  68. '--conf_file', default='benchmark.cfg', metavar='FILE',
  69. help='Optional configuration file to provide argument defaults. All config options can be overridden using the command line.')
  70. args, remaining_argv = conf_parser.parse_known_args()
  71. defaults = {}
  72. try:
  73. if not os.path.exists(os.path.join(os.environ['FWROOT'], args.conf_file)) and not os.path.exists(os.path.join(os.environ['FWROOT'] + 'benchmark.cfg')):
  74. print("No config file found. Aborting!")
  75. exit(1)
  76. with open (os.path.join(os.environ['FWROOT'], args.conf_file)):
  77. config = ConfigParser.SafeConfigParser()
  78. config.read([os.path.join(os.environ['FWROOT'], args.conf_file)])
  79. defaults.update(dict(config.items("Defaults")))
  80. # Convert strings into proper python types
  81. for k, v in defaults.iteritems():
  82. try:
  83. defaults[k] = literal_eval(v)
  84. except Exception:
  85. pass
  86. except IOError:
  87. print("Configuration file not found!")
  88. exit(1)
  89. ##########################################################
  90. # Set up default values
  91. ##########################################################
  92. # Verify and massage options
  93. if defaults['client_user'] is None or defaults['client_host'] is None:
  94. print("client_user and client_host are required!")
  95. print("Please check your configuration file.")
  96. print("Aborting!")
  97. exit(1)
  98. if defaults['database_user'] is None:
  99. defaults['database_user'] = defaults['client_user']
  100. if defaults['database_host'] is None:
  101. defaults['database_host'] = defaults['client_host']
  102. if defaults['server_host'] is None:
  103. defaults['server_host'] = defaults['client_host']
  104. maxThreads = 8
  105. try:
  106. maxThreads = multiprocessing.cpu_count()
  107. except Exception:
  108. pass
  109. ##########################################################
  110. # Set up argument parser
  111. ##########################################################
  112. parser = argparse.ArgumentParser(description="Install or run the Framework Benchmarks test suite.",
  113. parents=[conf_parser],
  114. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  115. epilog='''If an argument includes (type int-sequence), then it accepts integer lists in multiple forms.
  116. Using a single number e.g. 5 will create a list [5]. Using commas will create a list containing those
  117. values e.g. 1,3,6 creates [1, 3, 6]. Using three colon-separated numbers of start:step:end will create a
  118. list, using the semantics of python's range function, e.g. 1:3:15 creates [1, 4, 7, 10, 13] while
  119. 0:1:5 creates [0, 1, 2, 3, 4]
  120. ''')
  121. # Install options
  122. parser.add_argument('--clean', action='store_true', default=False, help='Removes the results directory')
  123. parser.add_argument('--clean-all', action='store_true', dest='clean_all', default=False, help='Removes the results and installs directories')
  124. # Test options
  125. parser.add_argument('--test', nargs='+', help='names of tests to run')
  126. parser.add_argument('--test-dir', nargs='+', dest='test_dir', help='name of framework directory containing all tests to run')
  127. parser.add_argument('--exclude', nargs='+', help='names of tests to exclude')
  128. parser.add_argument('--type', choices=['all', 'json', 'db', 'query', 'fortune', 'update', 'plaintext'], default='all', help='which type of test to run')
  129. parser.add_argument('-m', '--mode', choices=['benchmark', 'verify'], default='benchmark', help='verify mode will only start up the tests, curl the urls and shutdown')
  130. parser.add_argument('--list-tests', action='store_true', default=False, help='lists all the known tests that can run')
  131. # Benchmark options
  132. parser.add_argument('--concurrency-levels', default=[8, 16, 32, 64, 128, 256], help='Runs wrk benchmarker with different concurrency value (type int-sequence)', action=StoreSeqAction)
  133. parser.add_argument('--query-levels', default=[1, 5,10,15,20], help='Database queries requested per HTTP connection, used during query test (type int-sequence)', action=StoreSeqAction)
  134. parser.add_argument('--threads', default=maxThreads, help='Run wrk benchmarker with this many threads. This should probably be the number of cores for your client system', type=int)
  135. parser.add_argument('--duration', default=15, help='Time in seconds that each test should run for.')
  136. parser.add_argument('--sleep', type=int, default=60, help='the amount of time to sleep after starting each test to allow the server to start up.')
  137. # Misc Options
  138. parser.add_argument('--parse', help='Parses the results of the given timestamp and merges that with the latest results')
  139. parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Causes the configuration to print before any other commands are executed.')
  140. parser.add_argument('--clear-tmp', action='store_true', default=False, help='Clears files written to /tmp after each framework\'s tests complete.')
  141. parser.set_defaults(**defaults) # Must do this after add, or each option's default will override the configuration file default
  142. args = parser.parse_args(remaining_argv)
  143. benchmarker = Benchmarker(vars(args))
  144. # Run the benchmarker in the specified mode
  145. # Do not use benchmarker variables for these checks,
  146. # they are either str or bool based on the python version
  147. if args.list_tests:
  148. benchmarker.run_list_tests()
  149. elif args.parse != None:
  150. benchmarker.parse_timestamp()
  151. else:
  152. return benchmarker.run()
  153. if __name__ == "__main__":
  154. sys.exit(main())