The Gatekeeper, or a project gating system
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

176 lines
6.3 KiB

  1. # Copyright 2011 OpenStack, LLC.
  2. # Copyright 2012 Hewlett-Packard Development Company, L.P.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. import os
  16. import git
  17. import time
  18. import logging
  19. import urllib
  20. from zuul.connection import BaseConnection
  21. from zuul.driver.git.gitmodel import GitTriggerEvent
  22. from zuul.driver.git.gitwatcher import GitWatcher
  23. from zuul.model import Ref, Branch
  24. class GitConnection(BaseConnection):
  25. driver_name = 'git'
  26. log = logging.getLogger("zuul.connection.git")
  27. def __init__(self, driver, connection_name, connection_config):
  28. super(GitConnection, self).__init__(driver, connection_name,
  29. connection_config)
  30. if 'baseurl' not in self.connection_config:
  31. raise Exception('baseurl is required for git connections in '
  32. '%s' % self.connection_name)
  33. self.watcher_thread = None
  34. self.baseurl = self.connection_config.get('baseurl')
  35. self.poll_timeout = float(
  36. self.connection_config.get('poll_delay', 3600 * 2))
  37. self.canonical_hostname = self.connection_config.get(
  38. 'canonical_hostname')
  39. if not self.canonical_hostname:
  40. r = urllib.parse.urlparse(self.baseurl)
  41. if r.hostname:
  42. self.canonical_hostname = r.hostname
  43. else:
  44. self.canonical_hostname = 'localhost'
  45. self.projects = {}
  46. self._change_cache = {}
  47. def toDict(self):
  48. d = super().toDict()
  49. d.update({
  50. "baseurl": self.baseurl,
  51. "canonical_hostname": self.canonical_hostname,
  52. })
  53. return d
  54. def getProject(self, name):
  55. return self.projects.get(name)
  56. def addProject(self, project):
  57. self.projects[project.name] = project
  58. def getChangeFilesUpdated(self, project_name, branch, tosha):
  59. job = self.sched.merger.getFilesChanges(
  60. self.connection_name, project_name, branch, tosha)
  61. self.log.debug("Waiting for fileschanges job %s" % job)
  62. job.wait()
  63. if not job.updated:
  64. raise Exception("Fileschanges job %s failed" % job)
  65. self.log.debug("Fileschanges job %s got changes on files %s" %
  66. (job, job.files))
  67. return job.files
  68. def lsRemote(self, project):
  69. refs = {}
  70. client = git.cmd.Git()
  71. output = client.ls_remote(
  72. "--heads", "--tags",
  73. os.path.join(self.baseurl, project))
  74. for line in output.splitlines():
  75. sha, ref = line.split('\t')
  76. if ref.startswith('refs/'):
  77. refs[ref] = sha
  78. return refs
  79. def maintainCache(self, relevant):
  80. remove = {}
  81. for branch, refschange in self._change_cache.items():
  82. for ref, change in refschange.items():
  83. if change not in relevant:
  84. remove.setdefault(branch, []).append(ref)
  85. for branch, refs in remove.items():
  86. for ref in refs:
  87. del self._change_cache[branch][ref]
  88. if not self._change_cache[branch]:
  89. del self._change_cache[branch]
  90. def getChange(self, event, refresh=False):
  91. if event.ref and event.ref.startswith('refs/heads/'):
  92. branch = event.ref[len('refs/heads/'):]
  93. change = self._change_cache.get(branch, {}).get(event.newrev)
  94. if change:
  95. return change
  96. project = self.getProject(event.project_name)
  97. change = Branch(project)
  98. change.branch = branch
  99. for attr in ('ref', 'oldrev', 'newrev'):
  100. setattr(change, attr, getattr(event, attr))
  101. change.url = ""
  102. change.files = self.getChangeFilesUpdated(
  103. event.project_name, change.branch, event.oldrev)
  104. self._change_cache.setdefault(branch, {})[event.newrev] = change
  105. elif event.ref:
  106. # catch-all ref (ie, not a branch or head)
  107. project = self.getProject(event.project_name)
  108. change = Ref(project)
  109. for attr in ('ref', 'oldrev', 'newrev'):
  110. setattr(change, attr, getattr(event, attr))
  111. change.url = ""
  112. else:
  113. self.log.warning("Unable to get change for %s" % (event,))
  114. change = None
  115. return change
  116. def getProjectBranches(self, project, tenant):
  117. refs = self.lsRemote(project.name)
  118. branches = [ref[len('refs/heads/'):] for ref in
  119. refs if ref.startswith('refs/heads/')]
  120. return branches
  121. def getGitUrl(self, project):
  122. return os.path.join(self.baseurl, project.name)
  123. def watcherCallback(self, data):
  124. event = GitTriggerEvent()
  125. event.type = 'ref-updated'
  126. event.timestamp = time.time()
  127. event.project_hostname = self.canonical_hostname
  128. event.project_name = data['project']
  129. for attr in ('ref', 'oldrev', 'newrev', 'branch_created',
  130. 'branch_deleted', 'branch_updated'):
  131. if attr in data:
  132. setattr(event, attr, data[attr])
  133. # Force changes cache update before passing
  134. # the event to the scheduler
  135. self.getChange(event)
  136. self.logEvent(event)
  137. # Pass the event to the scheduler
  138. self.sched.addEvent(event)
  139. def onLoad(self):
  140. self.log.debug("Starting Git Watcher")
  141. self._start_watcher_thread()
  142. def onStop(self):
  143. self.log.debug("Stopping Git Watcher")
  144. self._stop_watcher_thread()
  145. def _stop_watcher_thread(self):
  146. if self.watcher_thread:
  147. self.watcher_thread.stop()
  148. self.watcher_thread.join()
  149. def _start_watcher_thread(self):
  150. self.watcher_thread = GitWatcher(
  151. self,
  152. self.baseurl,
  153. self.poll_timeout,
  154. self.watcherCallback)
  155. self.watcher_thread.start()