run-tests.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. import subprocess
  11. from pprint import pprint
  12. from benchmark.benchmarker import Benchmarker
  13. from setup.linux.unbuffered import Unbuffered
  14. from setup.linux import setup_util
  15. from ast import literal_eval
  16. # Enable cross-platform colored output
  17. from colorama import init
  18. init()
  19. class StoreSeqAction(argparse.Action):
  20. '''Helper class for parsing a sequence from the command line'''
  21. def __init__(self, option_strings, dest, nargs=None, **kwargs):
  22. super(StoreSeqAction, self).__init__(option_strings, dest, type=str, **kwargs)
  23. def __call__(self, parser, namespace, values, option_string=None):
  24. setattr(namespace, self.dest, self.parse_seq(values))
  25. def parse_seq(self, argument):
  26. result = argument.split(',')
  27. sequences = [x for x in result if ":" in x]
  28. for sequence in sequences:
  29. try:
  30. (start,step,end) = sequence.split(':')
  31. except ValueError:
  32. print " Invalid: %s" % sequence
  33. print " Requires start:step:end, e.g. 1:2:10"
  34. raise
  35. result.remove(sequence)
  36. result = result + range(int(start), int(end), int(step))
  37. return [abs(int(item)) for item in result]
  38. ###################################################################################################
  39. # Main
  40. ###################################################################################################
  41. def main(argv=None):
  42. ''' Runs the program. There are three ways to pass arguments
  43. 1) environment variables TFB_*
  44. 2) configuration file benchmark.cfg
  45. 3) command line flags
  46. In terms of precedence, 3 > 2 > 1, so config file trumps environment variables
  47. but command line flags have the final say
  48. '''
  49. # Do argv default this way, as doing it in the functional declaration sets it at compile time
  50. if argv is None:
  51. argv = sys.argv
  52. # Enable unbuffered output so messages will appear in the proper order with subprocess output.
  53. sys.stdout=Unbuffered(sys.stdout)
  54. # Update python environment
  55. # 1) Ensure the current directory (which should be the benchmark home directory) is in the path so that the tests can be imported.
  56. sys.path.append('.')
  57. # 2) Ensure toolset/setup/linux is in the path so that the tests can "import setup_util".
  58. sys.path.append('toolset/setup/linux')
  59. # Update environment for shell scripts
  60. os.environ['FWROOT'] = setup_util.get_fwroot()
  61. os.environ['IROOT'] = os.environ['FWROOT'] + '/installs'
  62. # 'Ubuntu', '14.04', 'trusty' respectively
  63. os.environ['TFB_DISTRIB_ID'], os.environ['TFB_DISTRIB_RELEASE'], os.environ['TFB_DISTRIB_CODENAME'] = platform.linux_distribution()
  64. print "FWROOT is %s"%os.environ['FWROOT']
  65. conf_parser = argparse.ArgumentParser(
  66. description=__doc__,
  67. formatter_class=argparse.RawDescriptionHelpFormatter,
  68. add_help=False)
  69. conf_parser.add_argument('--conf_file', default='benchmark.cfg', metavar='FILE', 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. try:
  72. with open (args.conf_file):
  73. config = ConfigParser.SafeConfigParser()
  74. config.read([os.getcwd() + '/' + args.conf_file])
  75. defaults = dict(config.items("Defaults"))
  76. # Convert strings into proper python types
  77. for k,v in defaults.iteritems():
  78. try:
  79. defaults[k] = literal_eval(v)
  80. except Exception:
  81. pass
  82. except IOError:
  83. if args.conf_file != 'benchmark.cfg':
  84. print 'Configuration file not found!'
  85. defaults = { "client-host":"localhost"}
  86. ##########################################################
  87. # Set up default values
  88. ##########################################################
  89. serverHost = os.environ.get('TFB_SERVER_HOST')
  90. clientHost = os.environ.get('TFB_CLIENT_HOST')
  91. clientUser = os.environ.get('TFB_CLIENT_USER')
  92. clientIden = os.environ.get('TFB_CLIENT_IDENTITY_FILE')
  93. runnerUser = os.environ.get('TFB_RUNNER_USER')
  94. databaHost = os.getenv('TFB_DATABASE_HOST', clientHost)
  95. databaUser = os.getenv('TFB_DATABASE_USER', clientUser)
  96. dbIdenFile = os.getenv('TFB_DATABASE_IDENTITY_FILE', clientIden)
  97. maxThreads = 8
  98. try:
  99. maxThreads = multiprocessing.cpu_count()
  100. except Exception:
  101. pass
  102. ##########################################################
  103. # Set up argument parser
  104. ##########################################################
  105. parser = argparse.ArgumentParser(description="Install or run the Framework Benchmarks test suite.",
  106. parents=[conf_parser],
  107. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  108. epilog='''If an argument includes (type int-sequence), then it accepts integer lists in multiple forms.
  109. Using a single number e.g. 5 will create a list [5]. Using commas will create a list containing those
  110. values e.g. 1,3,6 creates [1, 3, 6]. Using three colon-separated numbers of start:step:end will create a
  111. list, using the semantics of python's range function, e.g. 1:3:15 creates [1, 4, 7, 10, 13] while
  112. 0:1:5 creates [0, 1, 2, 3, 4]
  113. ''')
  114. # SSH options
  115. parser.add_argument('-s', '--server-host', default=serverHost, help='The application server.')
  116. parser.add_argument('-c', '--client-host', default=clientHost, help='The client / load generation server.')
  117. parser.add_argument('-u', '--client-user', default=clientUser, help='The username to use for SSH to the client instance.')
  118. parser.add_argument('-i', '--client-identity-file', dest='client_identity_file', default=clientIden,
  119. help='The key to use for SSH to the client instance.')
  120. parser.add_argument('-d', '--database-host', default=databaHost,
  121. help='The database server. If not provided, defaults to the value of --client-host.')
  122. parser.add_argument('--database-user', default=databaUser,
  123. help='The username to use for SSH to the database instance. If not provided, defaults to the value of --client-user.')
  124. parser.add_argument('--database-identity-file', default=dbIdenFile, dest='database_identity_file',
  125. help='The key to use for SSH to the database instance. If not provided, defaults to the value of --client-identity-file.')
  126. # Install options
  127. parser.add_argument('--clean', action='store_true', default=False, help='Removes the results directory')
  128. parser.add_argument('--clean-all', action='store_true', dest='clean_all', default=False, help='Removes the results and installs directories')
  129. # Test options
  130. parser.add_argument('--test', nargs='+', help='names of tests to run')
  131. parser.add_argument('--test-dir', nargs='+', dest='test_dir', help='name of framework directory containing all tests to run')
  132. parser.add_argument('--exclude', nargs='+', help='names of tests to exclude')
  133. parser.add_argument('--type', choices=['all', 'json', 'db', 'query', 'fortune', 'update', 'plaintext'], default='all', help='which type of test to run')
  134. parser.add_argument('-m', '--mode', choices=['benchmark', 'verify'], default='benchmark', help='verify mode will only start up the tests, curl the urls and shutdown')
  135. parser.add_argument('--list-tests', action='store_true', default=False, help='lists all the known tests that can run')
  136. parser.add_argument('--list-test-metadata', action='store_true', default=False, help='writes all the test metadata as a JSON file in the results directory')
  137. parser.add_argument('--os', choices=['linux', 'windows'], default='linux', help='The operating system of the application/framework server (the one running' +
  138. 'this binary')
  139. parser.add_argument('--database-os', choices=['linux', 'windows'], default='linux', help='The operating system of the database server.')
  140. # Benchmark options
  141. 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)
  142. 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)
  143. 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)
  144. parser.add_argument('--duration', default=15, help='Time in seconds that each test should run for.')
  145. 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.')
  146. # Misc Options
  147. parser.add_argument('--parse', help='Parses the results of the given timestamp and merges that with the latest results')
  148. parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Causes the configuration to print before any other commands are executed.')
  149. parser.add_argument('--clear-tmp', action='store_true', default=False, help='Clears files written to /tmp after each framework\'s tests complete.')
  150. parser.set_defaults(**defaults) # Must do this after add, or each option's default will override the configuration file default
  151. args = parser.parse_args(remaining_argv)
  152. # Verify and massage options
  153. if args.client_user is None:
  154. print 'Usernames (e.g. --client-user, and --database-user) are required!'
  155. print 'The system will SSH into the client and the database for the install stage'
  156. print 'Aborting'
  157. exit(1)
  158. if args.database_user is None:
  159. args.database_user = args.client_user
  160. if args.database_host is None:
  161. args.database_host = args.client_host
  162. if args.verbose:
  163. print 'Configuration options: '
  164. pprint(vars(args))
  165. benchmarker = Benchmarker(vars(args))
  166. # Run the benchmarker in the specified mode
  167. # Do not use benchmarker variables for these checks,
  168. # they are either str or bool based on the python version
  169. if args.list_tests:
  170. benchmarker.run_list_tests()
  171. elif args.list_test_metadata:
  172. benchmarker.run_list_test_metadata()
  173. elif args.parse != None:
  174. benchmarker.parse_timestamp()
  175. else:
  176. return benchmarker.run()
  177. if __name__ == "__main__":
  178. sys.exit(main())