run-ci.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. #!/usr/bin/env python
  2. import subprocess
  3. import os
  4. import sys
  5. import glob
  6. import json
  7. import traceback
  8. import re
  9. import logging
  10. log = logging.getLogger('run-ci')
  11. import time
  12. import threading
  13. from benchmark import framework_test
  14. from benchmark.utils import gather_tests
  15. from benchmark.utils import header
  16. # Cross-platform colored text
  17. from colorama import Fore, Back, Style
  18. # Needed for various imports
  19. sys.path.append('.')
  20. sys.path.append('toolset/setup/linux')
  21. sys.path.append('toolset/benchmark')
  22. from setup.linux import setup_util
  23. class CIRunnner:
  24. '''
  25. Manages running TFB on the Travis Continuous Integration system.
  26. Makes a best effort to avoid wasting time and resources by running
  27. useless jobs.
  28. Only verifies the first test in each directory
  29. '''
  30. SUPPORTED_DATABASES = "mysql postgres mongodb cassandra sqlite none".split()
  31. def __init__(self, mode, testdir=None):
  32. '''
  33. mode = [cisetup|prereq|install|verify] for what we want to do
  34. testdir = framework directory we are running
  35. '''
  36. self.directory = testdir
  37. self.mode = mode
  38. if mode == "cisetup":
  39. logging.basicConfig(level=logging.DEBUG)
  40. else:
  41. logging.basicConfig(level=logging.INFO)
  42. try:
  43. # NOTE: THIS IS VERY TRICKY TO GET RIGHT!
  44. #
  45. # Our goal: Look at the files changed and determine if we need to
  46. # run a verification for this folder. For a pull request, we want to
  47. # see the list of files changed by any commit in that PR. For a
  48. # push to master, we want to see a list of files changed by the pushed
  49. # commits. If this list of files contains the current directory, or
  50. # contains the toolset/ directory, then we need to run a verification
  51. #
  52. # If modifying, please consider:
  53. # - the commit range for a pull request is the first PR commit to
  54. # the github auto-merge commit
  55. # - the commits in the commit range may include merge commits
  56. # other than the auto-merge commit. An git log with -m
  57. # will know that *all* the files in the merge were changed,
  58. # but that is not the changeset that we care about
  59. # - git diff shows differences, but we care about git log, which
  60. # shows information on what was changed during commits
  61. # - master can (and will!) move during a build. This is one
  62. # of the biggest problems with using git diff - master will
  63. # be updated, and those updates will include changes to toolset,
  64. # and suddenly every job in the build will start to run instead
  65. # of fast-failing
  66. # - commit_range is not set if there was only one commit pushed,
  67. # so be sure to test for that on both master and PR
  68. # - commit_range and commit are set very differently for pushes
  69. # to an owned branch versus pushes to a pull request, test
  70. # - For merge commits, the TRAVIS_COMMIT and TRAVIS_COMMIT_RANGE
  71. # will become invalid if additional commits are pushed while a job is
  72. # building. See https://github.com/travis-ci/travis-ci/issues/2666
  73. # - If you're really insane, consider that the last commit in a
  74. # pull request could have been a merge commit. This means that
  75. # the github auto-merge commit could have more than two parents
  76. # - Travis cannot really support rebasing onto an owned branch, the
  77. # commit_range they provide will include commits that are non-existant
  78. # in the repo cloned on the workers. See https://github.com/travis-ci/travis-ci/issues/2668
  79. #
  80. # - TEST ALL THESE OPTIONS:
  81. # - On a branch you own (e.g. your fork's master)
  82. # - single commit
  83. # - multiple commits pushed at once
  84. # - commit+push, then commit+push again before the first
  85. # build has finished. Verify all jobs in the first build
  86. # used the correct commit range
  87. # - multiple commits, including a merge commit. Verify that
  88. # the unrelated merge commit changes are not counted as
  89. # changes the user made
  90. # - On a pull request
  91. # - repeat all above variations
  92. #
  93. #
  94. # ==== CURRENT SOLUTION FOR PRs ====
  95. #
  96. # For pull requests, we will examine Github's automerge commit to see
  97. # what files would be touched if we merged this into the current master.
  98. # You can't trust the travis variables here, as the automerge commit can
  99. # be different for jobs on the same build. See https://github.com/travis-ci/travis-ci/issues/2666
  100. # We instead use the FETCH_HEAD, which will always point to the SHA of
  101. # the lastest merge commit. However, if we only used FETCH_HEAD than any
  102. # new commits to a pull request would instantly start affecting currently
  103. # running jobs and the the list of changed files may become incorrect for
  104. # those affected jobs. The solution is to walk backward from the FETCH_HEAD
  105. # to the last commit in the pull request. Based on how github currently
  106. # does the automerge, this is the second parent of FETCH_HEAD, and
  107. # therefore we use FETCH_HEAD^2 below
  108. #
  109. # This may not work perfectly in situations where the user had advanced
  110. # merging happening in their PR. We correctly handle them merging in
  111. # from upstream, but if they do wild stuff then this will likely break
  112. # on that. However, it will also likely break by seeing a change in
  113. # toolset and triggering a full run when a partial run would be
  114. # acceptable
  115. #
  116. # ==== CURRENT SOLUTION FOR OWNED BRANCHES (e.g. master) ====
  117. #
  118. # This one is fairly simple. Find the commit or commit range, and
  119. # examine the log of files changes. If you encounter any merges,
  120. # then fully explode the two parent commits that made the merge
  121. # and look for the files changed there. This is an aggressive
  122. # strategy to ensure that commits to master are always tested
  123. # well
  124. log.debug("TRAVIS_COMMIT_RANGE: %s", os.environ['TRAVIS_COMMIT_RANGE'])
  125. log.debug("TRAVIS_COMMIT : %s", os.environ['TRAVIS_COMMIT'])
  126. is_PR = (os.environ['TRAVIS_PULL_REQUEST'] != "false")
  127. if is_PR:
  128. log.debug('I am testing a pull request')
  129. first_commit = os.environ['TRAVIS_COMMIT_RANGE'].split('...')[0]
  130. last_commit = subprocess.check_output("git rev-list -n 1 FETCH_HEAD^2", shell=True).rstrip('\n')
  131. log.debug("Guessing that first commit in PR is : %s", first_commit)
  132. log.debug("Guessing that final commit in PR is : %s", last_commit)
  133. if first_commit == "":
  134. # Travis-CI is not yet passing a commit range for pull requests
  135. # so we must use the automerge's changed file list. This has the
  136. # negative effect that new pushes to the PR will immediately
  137. # start affecting any new jobs, regardless of the build they are on
  138. log.debug("No first commit, using Github's automerge commit")
  139. self.commit_range = "--first-parent -1 -m FETCH_HEAD"
  140. elif first_commit == last_commit:
  141. # There is only one commit in the pull request so far,
  142. # or Travis-CI is not yet passing the commit range properly
  143. # for pull requests. We examine just the one commit using -1
  144. #
  145. # On the oddball chance that it's a merge commit, we pray
  146. # it's a merge from upstream and also pass --first-parent
  147. log.debug("Only one commit in range, examining %s", last_commit)
  148. self.commit_range = "-m --first-parent -1 %s" % last_commit
  149. else:
  150. # In case they merged in upstream, we only care about the first
  151. # parent. For crazier merges, we hope
  152. self.commit_range = "--first-parent %s...%s" % (first_commit, last_commit)
  153. if not is_PR:
  154. log.debug('I am not testing a pull request')
  155. # If more than one commit was pushed, examine everything including
  156. # all details on all merges
  157. self.commit_range = "-m %s" % os.environ['TRAVIS_COMMIT_RANGE']
  158. # If only one commit was pushed, examine that one. If it was a
  159. # merge be sure to show all details
  160. if self.commit_range == "":
  161. self.commit_range = "-m -1 %s" % os.environ['TRAVIS_COMMIT']
  162. except KeyError:
  163. log.warning("I should only be used for automated integration tests e.g. Travis-CI")
  164. log.warning("Were you looking for run-tests.py?")
  165. self.commit_range = "-m HEAD^...HEAD"
  166. #
  167. # Find the one test from benchmark_config that we are going to run
  168. #
  169. tests = gather_tests()
  170. self.fwroot = setup_util.get_fwroot()
  171. target_dir = self.fwroot + '/frameworks/' + testdir
  172. log.debug("Target directory is %s", target_dir)
  173. dirtests = [t for t in tests if t.directory == target_dir]
  174. # Travis-CI is linux only
  175. osvalidtests = [t for t in dirtests if t.os.lower() == "linux"
  176. and (t.database_os.lower() == "linux" or t.database_os.lower() == "none")]
  177. # Our Travis-CI only has some databases supported
  178. validtests = [t for t in osvalidtests if t.database.lower() in self.SUPPORTED_DATABASES]
  179. supported_databases = ','.join(self.SUPPORTED_DATABASES)
  180. log.info("Found %s usable tests (%s valid for linux, %s valid for linux and {%s}) in directory '%s'",
  181. len(dirtests), len(osvalidtests), len(validtests), supported_databases, '$FWROOT/frameworks/' + testdir)
  182. if len(validtests) == 0:
  183. log.critical("Found no test that is possible to run in Travis-CI! Aborting!")
  184. if len(osvalidtests) != 0:
  185. log.critical("Note: Found these tests that could run in Travis-CI if more databases were supported")
  186. log.critical("Note: %s", osvalidtests)
  187. databases_needed = [t.database for t in osvalidtests]
  188. databases_needed = list(set(databases_needed))
  189. log.critical("Note: Here are the needed databases:")
  190. log.critical("Note: %s", databases_needed)
  191. sys.exit(1)
  192. self.names = [t.name for t in validtests]
  193. log.info("Using tests %s to verify directory %s", self.names, '$FWROOT/frameworks/' + testdir)
  194. def _should_run(self):
  195. '''
  196. Decides if the current framework test should be tested.
  197. Examines git commits included in the latest push to see if any files relevant to
  198. this framework were changed.
  199. If you do rewrite history (e.g. rebase) then it's up to you to ensure that both
  200. old and new (e.g. old...new) are available in the public repository. For simple
  201. rebase onto the public master this is not a problem, only more complex rebases
  202. may have issues
  203. '''
  204. # Don't use git diff multiple times, it's mega slow sometimes\
  205. # Put flag on filesystem so that future calls to run-ci see it too
  206. if os.path.isfile('.run-ci.should_run'):
  207. return True
  208. if os.path.isfile('.run-ci.should_not_run'):
  209. return False
  210. def touch(fname):
  211. open(fname, 'a').close()
  212. log.debug("Using commit range `%s`", self.commit_range)
  213. log.debug("Running `git log --name-only --pretty=\"format:\" %s`" % self.commit_range)
  214. changes = ""
  215. try:
  216. changes = subprocess.check_output("git log --name-only --pretty=\"format:\" %s" % self.commit_range, shell=True)
  217. except subprocess.CalledProcessError, e:
  218. log.error("Got errors when using git to detect your changes, assuming that we must run this verification!")
  219. log.error("Error was: %s", e.output)
  220. log.error("Did you rebase a branch? If so, you can safely disregard this error, it's a Travis limitation")
  221. return True
  222. changes = os.linesep.join([s for s in changes.splitlines() if s]) # drop empty lines
  223. if len(changes.splitlines()) > 1000:
  224. log.debug("Change list is >1000 lines, uploading to sprunge.us instead of printing to console")
  225. url = subprocess.check_output("git log --name-only %s | curl -F 'sprunge=<-' http://sprunge.us" % self.commit_range, shell=True)
  226. log.debug("Uploaded to %s", url)
  227. else:
  228. log.debug("Result:\n%s", changes)
  229. # Look for changes to core TFB framework code
  230. if re.search(r'^toolset/', changes, re.M) is not None:
  231. log.info("Found changes to core framework code")
  232. touch('.run-ci.should_run')
  233. return True
  234. # Look for changes relevant to this test
  235. if re.search("^frameworks/%s/" % re.escape(self.directory), changes, re.M) is None:
  236. log.info("No changes found for directory %s", self.directory)
  237. touch('.run-ci.should_not_run')
  238. return False
  239. log.info("Changes found for directory %s", self.directory)
  240. touch('.run-ci.should_run')
  241. return True
  242. def run(self):
  243. ''' Do the requested command using TFB '''
  244. if not self._should_run():
  245. log.info("I found no changes to `%s` or `toolset/`, aborting verification", self.directory)
  246. return 0
  247. if self.mode == 'cisetup':
  248. self.run_travis_setup()
  249. return 0
  250. names = ' '.join(self.names)
  251. command = 'toolset/run-tests.py '
  252. if self.mode == 'prereq':
  253. command = command + "--install server --install-only --test ''"
  254. elif self.mode == 'install':
  255. command = command + "--install server --install-only --test %s" % names
  256. elif self.mode == 'verify':
  257. command = command + "--mode verify --test %s" % names
  258. else:
  259. log.critical('Unknown mode passed')
  260. return 1
  261. # Run the command
  262. log.info("Running mode %s with commmand %s", self.mode, command)
  263. try:
  264. p = subprocess.Popen(command, shell=True)
  265. p.wait()
  266. return p.returncode
  267. except subprocess.CalledProcessError:
  268. log.critical("Subprocess Error")
  269. print traceback.format_exc()
  270. return 1
  271. except Exception as err:
  272. log.critical("Exception from running+wait on subprocess")
  273. log.error(err.child_traceback)
  274. return 1
  275. def run_travis_setup(self):
  276. log.info("Setting up Travis-CI")
  277. script = '''
  278. export DEBIAN_FRONTEND=noninteractive
  279. # Turn on command tracing
  280. set -x
  281. # Setup Apt For MongoDB
  282. # Due to TechEmpower/FrameworkBenchmarks#989 and travis-ci/travis-ci#2655,
  283. # we put this into a loop
  284. until timeout 15s sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10; do echo 'Waiting for apt-key' ; done
  285. echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
  286. # Setup apt for Apache Cassandra
  287. until timeout 15s sudo apt-key adv --keyserver pgp.mit.edu --recv 4BD736A82B5C1B00; do echo 'Waiting for apt-key' ; done
  288. sudo apt-add-repository 'deb http://www.apache.org/dist/cassandra/debian 20x main'
  289. # Run installation
  290. sudo apt-get -q update
  291. sudo apt-get -q -y install -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
  292. mongodb-org \
  293. cassandra \
  294. openssh-server
  295. # Run as travis user (who already has passwordless sudo)
  296. ssh-keygen -f /home/travis/.ssh/id_rsa -N '' -t rsa
  297. cat /home/travis/.ssh/id_rsa.pub > /home/travis/.ssh/authorized_keys
  298. chmod 600 /home/travis/.ssh/authorized_keys
  299. # =============Setup Databases===========================
  300. # NOTE: Do not run `--install database` in travis-ci!
  301. # It changes DB configuration files and will break everything
  302. # =======================================================
  303. # Setup MySQL
  304. echo "Populating MySQL database"
  305. mysql -uroot < config/create.sql
  306. # Setup Postgres
  307. echo "Populating Postgres database"
  308. psql --version
  309. sudo useradd benchmarkdbuser -p benchmarkdbpass
  310. sudo -u postgres psql template1 < config/create-postgres-database.sql
  311. sudo -u benchmarkdbuser psql hello_world < config/create-postgres.sql
  312. # Setup Apache Cassandra
  313. echo "Populating Apache Cassandra database"
  314. until nc -z localhost 9160 ; do echo Waiting for Cassandra; sleep 1; done
  315. cat config/cassandra/cleanup-keyspace.cql | sudo cqlsh
  316. python config/cassandra/db-data-gen.py > config/cassandra/tfb-data.cql
  317. sudo cqlsh -f config/cassandra/create-keyspace.cql
  318. sudo cqlsh -f config/cassandra/tfb-data.cql
  319. # Setup MongoDB
  320. echo "Populating MongoDB database"
  321. until nc -z localhost 27017 ; do echo Waiting for MongoDB; sleep 1; done
  322. mongod --version
  323. mongo < config/create.js
  324. '''
  325. def sh(command):
  326. log.info("Running `%s`", command)
  327. subprocess.check_call(command, shell=True)
  328. for command in script.split('\n'):
  329. command = command.lstrip()
  330. if command != "" and command[0] != '#':
  331. sh(command.lstrip())
  332. if __name__ == "__main__":
  333. args = sys.argv[1:]
  334. usage = '''Usage: toolset/run-ci.py [cisetup|prereq|install|verify] <framework-directory>
  335. run-ci.py selects one test from <framework-directory>/benchark_config, and
  336. automates a number of calls into run-tests.py specific to the selected test.
  337. It is guaranteed to always select the same test from the benchark_config, so
  338. multiple runs with the same <framework-directory> reference the same test.
  339. The name of the selected test will be printed to standard output.
  340. cisetup - configure the Travis-CI environment for our test suite
  341. prereq - trigger standard prerequisite installation
  342. install - trigger server installation for the selected test_directory
  343. verify - run a verification on the selected test using `--mode verify`
  344. run-ci.py expects to be run inside the Travis-CI build environment, and
  345. will expect environment variables such as $TRAVIS_BUILD'''
  346. if len(args) != 2:
  347. print usage
  348. sys.exit(1)
  349. mode = args[0]
  350. testdir = args[1]
  351. if len(args) == 2 and (mode == "install"
  352. or mode == "verify"
  353. or mode == 'prereq'
  354. or mode == 'cisetup'):
  355. runner = CIRunnner(mode, testdir)
  356. else:
  357. print usage
  358. sys.exit(1)
  359. retcode = 0
  360. try:
  361. retcode = runner.run()
  362. except KeyError as ke:
  363. log.warning("Environment key missing, are you running inside Travis-CI?")
  364. print traceback.format_exc()
  365. retcode = 1
  366. except:
  367. log.critical("Unknown error")
  368. print traceback.format_exc()
  369. retcode = 1
  370. finally: # Ensure that logs are printed
  371. # Only print logs if we ran a verify
  372. if mode != 'verify':
  373. sys.exit(retcode)
  374. # Only print logs if we actually did something
  375. if os.path.isfile('.run-ci.should_not_run'):
  376. sys.exit(retcode)
  377. log.error("Running inside Travis-CI, so I will print err and out to console...")
  378. for name in runner.names:
  379. log.error("Test %s", name)
  380. try:
  381. log.error("Here is ERR:")
  382. with open("results/ec2/latest/logs/%s/err.txt" % name, 'r') as err:
  383. for line in err:
  384. log.info(line.rstrip('\n'))
  385. except IOError:
  386. log.error("No ERR file found")
  387. try:
  388. log.error("Here is OUT:")
  389. with open("results/ec2/latest/logs/%s/out.txt" % name, 'r') as out:
  390. for line in out:
  391. log.info(line.rstrip('\n'))
  392. except IOError:
  393. log.error("No OUT file found")
  394. log.error("Running inside Travis-CI, so I will print a copy of the verification summary")
  395. results = None
  396. try:
  397. with open('results/ec2/latest/results.json', 'r') as f:
  398. results = json.load(f)
  399. except IOError:
  400. log.critical("No results.json found, unable to print verification summary")
  401. sys.exit(retcode)
  402. target_dir = setup_util.get_fwroot() + '/frameworks/' + testdir
  403. dirtests = [t for t in gather_tests() if t.directory == target_dir]
  404. # Normally you don't have to use Fore.* before each line, but
  405. # Travis-CI seems to reset color codes on newline (see travis-ci/travis-ci#2692)
  406. # or stream flush, so we have to ensure that the color code is printed repeatedly
  407. prefix = Fore.CYAN
  408. for line in header("Verification Summary", top='=', bottom='').split('\n'):
  409. print prefix + line
  410. for test in dirtests:
  411. print prefix + "| Test: %s" % test.name
  412. if test.name not in runner.names:
  413. print prefix + "| " + Fore.YELLOW + "Unable to verify in Travis-CI"
  414. elif test.name in results['verify'].keys():
  415. for test_type, result in results['verify'][test.name].iteritems():
  416. if result.upper() == "PASS":
  417. color = Fore.GREEN
  418. elif result.upper() == "WARN":
  419. color = Fore.YELLOW
  420. else:
  421. color = Fore.RED
  422. print prefix + "| " + test_type.ljust(11) + ' : ' + color + result.upper()
  423. else:
  424. print prefix + "| " + Fore.RED + "NO RESULTS (Did framework launch?)"
  425. print prefix + header('', top='', bottom='=') + Style.RESET_ALL
  426. sys.exit(retcode)
  427. # vim: set sw=2 ts=2 expandtab