run-ci.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 elasticsearch sqlite redis none".split()
  31. def __init__(self, mode, testdir=None):
  32. '''
  33. mode = [verify] for what we want to do
  34. testdir = framework directory we are running
  35. '''
  36. self.directory = testdir
  37. self.mode = mode
  38. logging.basicConfig(level=logging.INFO)
  39. try:
  40. # NOTE: THIS IS VERY TRICKY TO GET RIGHT!
  41. #
  42. # Our goal: Look at the files changed and determine if we need to
  43. # run a verification for this folder. For a pull request, we want to
  44. # see the list of files changed by any commit in that PR. For a
  45. # push to master, we want to see a list of files changed by the pushed
  46. # commits. If this list of files contains the current directory, or
  47. # contains the toolset/ directory, then we need to run a verification
  48. #
  49. # If modifying, please consider:
  50. # - the commit range for a pull request is the first PR commit to
  51. # the github auto-merge commit
  52. # - the commits in the commit range may include merge commits
  53. # other than the auto-merge commit. An git log with -m
  54. # will know that *all* the files in the merge were changed,
  55. # but that is not the changeset that we care about
  56. # - git diff shows differences, but we care about git log, which
  57. # shows information on what was changed during commits
  58. # - master can (and will!) move during a build. This is one
  59. # of the biggest problems with using git diff - master will
  60. # be updated, and those updates will include changes to toolset,
  61. # and suddenly every job in the build will start to run instead
  62. # of fast-failing
  63. # - commit_range is not set if there was only one commit pushed,
  64. # so be sure to test for that on both master and PR
  65. # - commit_range and commit are set very differently for pushes
  66. # to an owned branch versus pushes to a pull request, test
  67. # - For merge commits, the TRAVIS_COMMIT and TRAVIS_COMMIT_RANGE
  68. # will become invalid if additional commits are pushed while a job is
  69. # building. See https://github.com/travis-ci/travis-ci/issues/2666
  70. # - If you're really insane, consider that the last commit in a
  71. # pull request could have been a merge commit. This means that
  72. # the github auto-merge commit could have more than two parents
  73. # - Travis cannot really support rebasing onto an owned branch, the
  74. # commit_range they provide will include commits that are non-existant
  75. # in the repo cloned on the workers. See https://github.com/travis-ci/travis-ci/issues/2668
  76. #
  77. # - TEST ALL THESE OPTIONS:
  78. # - On a branch you own (e.g. your fork's master)
  79. # - single commit
  80. # - multiple commits pushed at once
  81. # - commit+push, then commit+push again before the first
  82. # build has finished. Verify all jobs in the first build
  83. # used the correct commit range
  84. # - multiple commits, including a merge commit. Verify that
  85. # the unrelated merge commit changes are not counted as
  86. # changes the user made
  87. # - On a pull request
  88. # - repeat all above variations
  89. #
  90. #
  91. # ==== CURRENT SOLUTION FOR PRs ====
  92. #
  93. # For pull requests, we will examine Github's automerge commit to see
  94. # what files would be touched if we merged this into the current master.
  95. # You can't trust the travis variables here, as the automerge commit can
  96. # be different for jobs on the same build. See https://github.com/travis-ci/travis-ci/issues/2666
  97. # We instead use the FETCH_HEAD, which will always point to the SHA of
  98. # the lastest merge commit. However, if we only used FETCH_HEAD than any
  99. # new commits to a pull request would instantly start affecting currently
  100. # running jobs and the the list of changed files may become incorrect for
  101. # those affected jobs. The solution is to walk backward from the FETCH_HEAD
  102. # to the last commit in the pull request. Based on how github currently
  103. # does the automerge, this is the second parent of FETCH_HEAD, and
  104. # therefore we use FETCH_HEAD^2 below
  105. #
  106. # This may not work perfectly in situations where the user had advanced
  107. # merging happening in their PR. We correctly handle them merging in
  108. # from upstream, but if they do wild stuff then this will likely break
  109. # on that. However, it will also likely break by seeing a change in
  110. # toolset and triggering a full run when a partial run would be
  111. # acceptable
  112. #
  113. # ==== CURRENT SOLUTION FOR OWNED BRANCHES (e.g. master) ====
  114. #
  115. # This one is fairly simple. Find the commit or commit range, and
  116. # examine the log of files changes. If you encounter any merges,
  117. # then fully explode the two parent commits that made the merge
  118. # and look for the files changed there. This is an aggressive
  119. # strategy to ensure that commits to master are always tested
  120. # well
  121. log.debug("TRAVIS_COMMIT_RANGE: %s", os.environ['TRAVIS_COMMIT_RANGE'])
  122. log.debug("TRAVIS_COMMIT : %s", os.environ['TRAVIS_COMMIT'])
  123. is_PR = (os.environ['TRAVIS_PULL_REQUEST'] != "false")
  124. if is_PR:
  125. log.debug('I am testing a pull request')
  126. first_commit = os.environ['TRAVIS_COMMIT_RANGE'].split('...')[0]
  127. last_commit = subprocess.check_output("git rev-list -n 1 FETCH_HEAD^2", shell=True).rstrip('\n')
  128. log.debug("Guessing that first commit in PR is : %s", first_commit)
  129. log.debug("Guessing that final commit in PR is : %s", last_commit)
  130. if first_commit == "":
  131. # Travis-CI is not yet passing a commit range for pull requests
  132. # so we must use the automerge's changed file list. This has the
  133. # negative effect that new pushes to the PR will immediately
  134. # start affecting any new jobs, regardless of the build they are on
  135. log.debug("No first commit, using Github's automerge commit")
  136. self.commit_range = "--first-parent -1 -m FETCH_HEAD"
  137. elif first_commit == last_commit:
  138. # There is only one commit in the pull request so far,
  139. # or Travis-CI is not yet passing the commit range properly
  140. # for pull requests. We examine just the one commit using -1
  141. #
  142. # On the oddball chance that it's a merge commit, we pray
  143. # it's a merge from upstream and also pass --first-parent
  144. log.debug("Only one commit in range, examining %s", last_commit)
  145. self.commit_range = "-m --first-parent -1 %s" % last_commit
  146. else:
  147. # In case they merged in upstream, we only care about the first
  148. # parent. For crazier merges, we hope
  149. self.commit_range = "--first-parent %s...%s" % (first_commit, last_commit)
  150. if not is_PR:
  151. log.debug('I am not testing a pull request')
  152. # Three main scenarios to consider
  153. # - 1 One non-merge commit pushed to master
  154. # - 2 One merge commit pushed to master (e.g. a PR was merged).
  155. # This is an example of merging a topic branch
  156. # - 3 Multiple commits pushed to master
  157. #
  158. # 1 and 2 are actually handled the same way, by showing the
  159. # changes being brought into to master when that one commit
  160. # was merged. Fairly simple, `git log -1 COMMIT`. To handle
  161. # the potential merge of a topic branch you also include
  162. # `--first-parent -m`.
  163. #
  164. # 3 needs to be handled by comparing all merge children for
  165. # the entire commit range. The best solution here would *not*
  166. # use --first-parent because there is no guarantee that it
  167. # reflects changes brought into master. Unfortunately we have
  168. # no good method inside Travis-CI to easily differentiate
  169. # scenario 1/2 from scenario 3, so I cannot handle them all
  170. # separately. 1/2 are the most common cases, 3 with a range
  171. # of non-merge commits is the next most common, and 3 with
  172. # a range including merge commits is the least common, so I
  173. # am choosing to make our Travis-CI setup potential not work
  174. # properly on the least common case by always using
  175. # --first-parent
  176. # Handle 3
  177. # Note: Also handles 2 because Travis-CI sets COMMIT_RANGE for
  178. # merged PR commits
  179. self.commit_range = "--first-parent -m %s" % os.environ['TRAVIS_COMMIT_RANGE']
  180. # Handle 1
  181. if self.commit_range == "":
  182. self.commit_range = "--first-parent -m -1 %s" % os.environ['TRAVIS_COMMIT']
  183. except KeyError:
  184. log.warning("I should only be used for automated integration tests e.g. Travis-CI")
  185. log.warning("Were you looking for run-tests.py?")
  186. self.commit_range = "-m HEAD^...HEAD"
  187. #
  188. # Find the one test from benchmark_config.json that we are going to run
  189. #
  190. tests = gather_tests()
  191. self.fwroot = setup_util.get_fwroot()
  192. target_dir = self.fwroot + '/frameworks/' + testdir
  193. log.debug("Target directory is %s", target_dir)
  194. dirtests = [t for t in tests if t.directory == target_dir]
  195. # Travis-CI is linux only
  196. osvalidtests = [t for t in dirtests if t.os.lower() == "linux"
  197. and (t.database_os.lower() == "linux" or t.database_os.lower() == "none")]
  198. # Our Travis-CI only has some databases supported
  199. validtests = [t for t in osvalidtests if t.database.lower() in self.SUPPORTED_DATABASES]
  200. supported_databases = ','.join(self.SUPPORTED_DATABASES)
  201. log.info("Found %s usable tests (%s valid for linux, %s valid for linux and {%s}) in directory '%s'",
  202. len(dirtests), len(osvalidtests), len(validtests), supported_databases, '$FWROOT/frameworks/' + testdir)
  203. if len(validtests) == 0:
  204. log.critical("Found no test that is possible to run in Travis-CI! Aborting!")
  205. if len(osvalidtests) != 0:
  206. log.critical("Note: Found these tests that could run in Travis-CI if more databases were supported")
  207. log.critical("Note: %s", osvalidtests)
  208. databases_needed = [t.database for t in osvalidtests]
  209. databases_needed = list(set(databases_needed))
  210. log.critical("Note: Here are the needed databases:")
  211. log.critical("Note: %s", databases_needed)
  212. sys.exit(1)
  213. self.names = [t.name for t in validtests]
  214. log.info("Using tests %s to verify directory %s", self.names, '$FWROOT/frameworks/' + testdir)
  215. def _should_run(self):
  216. '''
  217. Decides if the current framework test should be tested.
  218. Examines git commits included in the latest push to see if any files relevant to
  219. this framework were changed.
  220. If you do rewrite history (e.g. rebase) then it's up to you to ensure that both
  221. old and new (e.g. old...new) are available in the public repository. For simple
  222. rebase onto the public master this is not a problem, only more complex rebases
  223. may have issues
  224. '''
  225. # Don't use git diff multiple times, it's mega slow sometimes\
  226. # Put flag on filesystem so that future calls to run-ci see it too
  227. if os.path.isfile('.run-ci.should_run'):
  228. return True
  229. if os.path.isfile('.run-ci.should_not_run'):
  230. return False
  231. def touch(fname):
  232. open(fname, 'a').close()
  233. log.debug("Using commit range `%s`", self.commit_range)
  234. log.debug("Running `git log --name-only --pretty=\"format:\" %s`" % self.commit_range)
  235. changes = ""
  236. try:
  237. changes = subprocess.check_output("git log --name-only --pretty=\"format:\" %s" % self.commit_range, shell=True)
  238. except subprocess.CalledProcessError, e:
  239. log.error("Got errors when using git to detect your changes, assuming that we must run this verification!")
  240. log.error("Error was: %s", e.output)
  241. log.error("Did you rebase a branch? If so, you can safely disregard this error, it's a Travis limitation")
  242. return True
  243. changes = os.linesep.join([s for s in changes.splitlines() if s]) # drop empty lines
  244. if len(changes.splitlines()) > 1000:
  245. log.debug("Change list is >1000 lines, uploading to sprunge.us instead of printing to console")
  246. url = subprocess.check_output("git log --name-only %s | curl -F 'sprunge=<-' http://sprunge.us" % self.commit_range, shell=True)
  247. log.debug("Uploaded to %s", url)
  248. else:
  249. log.debug("Result:\n%s", changes)
  250. # Look for changes to core TFB framework code
  251. if re.search(r'^toolset/', changes, re.M) is not None:
  252. log.info("Found changes to core framework code")
  253. touch('.run-ci.should_run')
  254. return True
  255. # Look for changes relevant to this test
  256. if re.search("^frameworks/%s/" % re.escape(self.directory), changes, re.M) is None:
  257. log.info("No changes found for directory %s", self.directory)
  258. touch('.run-ci.should_not_run')
  259. return False
  260. log.info("Changes found for directory %s", self.directory)
  261. touch('.run-ci.should_run')
  262. return True
  263. def run(self):
  264. ''' Do the requested command using TFB '''
  265. if not self._should_run():
  266. log.info("I found no changes to `%s` or `toolset/`, aborting verification", self.directory)
  267. return 0
  268. # Do full setup now that we've verified that there's work to do
  269. try:
  270. p = subprocess.Popen("config/travis_setup.sh", shell=True)
  271. p.wait()
  272. except subprocess.CalledProcessError:
  273. log.critical("Subprocess Error")
  274. print trackback.format_exc()
  275. return 1
  276. except Exception as err:
  277. log.critical("Exception from running and waiting on subprocess to set up Travis environment")
  278. log.error(err.child_traceback)
  279. return 1
  280. names = ' '.join(self.names)
  281. # Assume mode is verify
  282. command = "toolset/run-tests.py --mode verify --test %s" % names
  283. # Run the command
  284. log.info("Running mode %s with commmand %s", self.mode, command)
  285. try:
  286. p = subprocess.Popen(command, shell=True)
  287. p.wait()
  288. return p.returncode
  289. except subprocess.CalledProcessError:
  290. log.critical("Subprocess Error")
  291. print traceback.format_exc()
  292. return 1
  293. except Exception as err:
  294. log.critical("Exception from running+wait on subprocess")
  295. log.error(err.child_traceback)
  296. return 1
  297. if __name__ == "__main__":
  298. args = sys.argv[1:]
  299. usage = '''Usage: toolset/run-ci.py [verify] <framework-directory>
  300. run-ci.py selects one test from <framework-directory>/benchark_config, and
  301. automates a number of calls into run-tests.py specific to the selected test.
  302. It is guaranteed to always select the same test from the benchark_config, so
  303. multiple runs with the same <framework-directory> reference the same test.
  304. The name of the selected test will be printed to standard output.
  305. verify - run a verification on the selected test using `--mode verify`
  306. run-ci.py expects to be run inside the Travis-CI build environment, and
  307. will expect environment variables such as $TRAVIS_BUILD'''
  308. if len(args) != 2:
  309. print usage
  310. sys.exit(1)
  311. mode = args[0]
  312. testdir = args[1]
  313. if len(args) == 2 and (mode == 'verify'):
  314. runner = CIRunnner(mode, testdir)
  315. else:
  316. print usage
  317. sys.exit(1)
  318. retcode = 0
  319. try:
  320. retcode = runner.run()
  321. except KeyError as ke:
  322. log.warning("Environment key missing, are you running inside Travis-CI?")
  323. print traceback.format_exc()
  324. retcode = 1
  325. except Exception:
  326. log.critical("Unknown error")
  327. print traceback.format_exc()
  328. retcode = 1
  329. finally:
  330. sys.exit(retcode)
  331. # vim: set sw=2 ts=2 expandtab