Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | # Copyright 2012 Hewlett-Packard Development Company, L.P. |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 | # not use this file except in compliance with the License. You may obtain |
| 7 | # a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 14 | # License for the specific language governing permissions and limitations |
| 15 | # under the License. |
| 16 | |
Christian Berendt | ffba5df | 2014-06-07 21:30:22 +0200 | [diff] [blame] | 17 | from six.moves import configparser as ConfigParser |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 18 | import gc |
| 19 | import hashlib |
| 20 | import json |
| 21 | import logging |
| 22 | import os |
| 23 | import pprint |
Christian Berendt | 12d4d72 | 2014-06-07 21:03:45 +0200 | [diff] [blame] | 24 | from six.moves import queue as Queue |
Morgan Fainberg | 293f7f8 | 2016-05-30 14:01:22 -0700 | [diff] [blame] | 25 | from six.moves import urllib |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 26 | import random |
| 27 | import re |
| 28 | import select |
| 29 | import shutil |
Monty Taylor | 74fa386 | 2016-06-02 07:39:49 +0300 | [diff] [blame] | 30 | from six.moves import reload_module |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 31 | import socket |
| 32 | import string |
| 33 | import subprocess |
| 34 | import swiftclient |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 35 | import tempfile |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 36 | import threading |
| 37 | import time |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 38 | |
| 39 | import git |
| 40 | import gear |
| 41 | import fixtures |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 42 | import statsd |
| 43 | import testtools |
Mike Heald | 8225f52 | 2014-11-21 09:52:33 +0000 | [diff] [blame] | 44 | from git import GitCommandError |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 45 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 46 | import zuul.connection.gerrit |
| 47 | import zuul.connection.smtp |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 48 | import zuul.scheduler |
| 49 | import zuul.webapp |
| 50 | import zuul.rpclistener |
Joshua Hesketh | 0c54b2a | 2016-04-11 21:23:33 +1000 | [diff] [blame] | 51 | import zuul.launcher.server |
| 52 | import zuul.launcher.client |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 53 | import zuul.lib.swift |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 54 | import zuul.lib.connections |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 55 | import zuul.merger.client |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 56 | import zuul.merger.merger |
| 57 | import zuul.merger.server |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 58 | import zuul.nodepool |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 59 | import zuul.reporter.gerrit |
| 60 | import zuul.reporter.smtp |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 61 | import zuul.source.gerrit |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 62 | import zuul.trigger.gerrit |
| 63 | import zuul.trigger.timer |
James E. Blair | c494d54 | 2014-08-06 09:23:52 -0700 | [diff] [blame] | 64 | import zuul.trigger.zuultrigger |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 65 | |
| 66 | FIXTURE_DIR = os.path.join(os.path.dirname(__file__), |
| 67 | 'fixtures') |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 68 | USE_TEMPDIR = True |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 69 | |
| 70 | logging.basicConfig(level=logging.DEBUG, |
| 71 | format='%(asctime)s %(name)-32s ' |
| 72 | '%(levelname)-8s %(message)s') |
| 73 | |
| 74 | |
| 75 | def repack_repo(path): |
| 76 | cmd = ['git', '--git-dir=%s/.git' % path, 'repack', '-afd'] |
| 77 | output = subprocess.Popen(cmd, close_fds=True, |
| 78 | stdout=subprocess.PIPE, |
| 79 | stderr=subprocess.PIPE) |
| 80 | out = output.communicate() |
| 81 | if output.returncode: |
| 82 | raise Exception("git repack returned %d" % output.returncode) |
| 83 | return out |
| 84 | |
| 85 | |
| 86 | def random_sha1(): |
| 87 | return hashlib.sha1(str(random.random())).hexdigest() |
| 88 | |
| 89 | |
James E. Blair | a190f3b | 2015-01-05 14:56:54 -0800 | [diff] [blame] | 90 | def iterate_timeout(max_seconds, purpose): |
| 91 | start = time.time() |
| 92 | count = 0 |
| 93 | while (time.time() < start + max_seconds): |
| 94 | count += 1 |
| 95 | yield count |
| 96 | time.sleep(0) |
| 97 | raise Exception("Timeout waiting for %s" % purpose) |
| 98 | |
| 99 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 100 | class ChangeReference(git.Reference): |
| 101 | _common_path_default = "refs/changes" |
| 102 | _points_to_commits_only = True |
| 103 | |
| 104 | |
| 105 | class FakeChange(object): |
| 106 | categories = {'APRV': ('Approved', -1, 1), |
| 107 | 'CRVW': ('Code-Review', -2, 2), |
| 108 | 'VRFY': ('Verified', -2, 2)} |
| 109 | |
| 110 | def __init__(self, gerrit, number, project, branch, subject, |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 111 | status='NEW', upstream_root=None, files={}): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 112 | self.gerrit = gerrit |
| 113 | self.reported = 0 |
| 114 | self.queried = 0 |
| 115 | self.patchsets = [] |
| 116 | self.number = number |
| 117 | self.project = project |
| 118 | self.branch = branch |
| 119 | self.subject = subject |
| 120 | self.latest_patchset = 0 |
| 121 | self.depends_on_change = None |
| 122 | self.needed_by_changes = [] |
| 123 | self.fail_merge = False |
| 124 | self.messages = [] |
| 125 | self.data = { |
| 126 | 'branch': branch, |
| 127 | 'comments': [], |
| 128 | 'commitMessage': subject, |
| 129 | 'createdOn': time.time(), |
| 130 | 'id': 'I' + random_sha1(), |
| 131 | 'lastUpdated': time.time(), |
| 132 | 'number': str(number), |
| 133 | 'open': status == 'NEW', |
| 134 | 'owner': {'email': 'user@example.com', |
| 135 | 'name': 'User Name', |
| 136 | 'username': 'username'}, |
| 137 | 'patchSets': self.patchsets, |
| 138 | 'project': project, |
| 139 | 'status': status, |
| 140 | 'subject': subject, |
| 141 | 'submitRecords': [], |
| 142 | 'url': 'https://hostname/%s' % number} |
| 143 | |
| 144 | self.upstream_root = upstream_root |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 145 | self.addPatchset(files=files) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 146 | self.data['submitRecords'] = self.getSubmitRecords() |
| 147 | self.open = status == 'NEW' |
| 148 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 149 | def addFakeChangeToRepo(self, msg, files, large): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 150 | path = os.path.join(self.upstream_root, self.project) |
| 151 | repo = git.Repo(path) |
| 152 | ref = ChangeReference.create(repo, '1/%s/%s' % (self.number, |
| 153 | self.latest_patchset), |
| 154 | 'refs/tags/init') |
| 155 | repo.head.reference = ref |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 156 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 157 | repo.git.clean('-x', '-f', '-d') |
| 158 | |
| 159 | path = os.path.join(self.upstream_root, self.project) |
| 160 | if not large: |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 161 | for fn, content in files.items(): |
| 162 | fn = os.path.join(path, fn) |
| 163 | with open(fn, 'w') as f: |
| 164 | f.write(content) |
| 165 | repo.index.add([fn]) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 166 | else: |
| 167 | for fni in range(100): |
| 168 | fn = os.path.join(path, str(fni)) |
| 169 | f = open(fn, 'w') |
| 170 | for ci in range(4096): |
| 171 | f.write(random.choice(string.printable)) |
| 172 | f.close() |
| 173 | repo.index.add([fn]) |
| 174 | |
| 175 | r = repo.index.commit(msg) |
| 176 | repo.head.reference = 'master' |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 177 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 178 | repo.git.clean('-x', '-f', '-d') |
| 179 | repo.heads['master'].checkout() |
| 180 | return r |
| 181 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 182 | def addPatchset(self, files=None, large=False): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 183 | self.latest_patchset += 1 |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 184 | if not files: |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 185 | fn = '%s-%s' % (self.branch.replace('/', '_'), self.number) |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 186 | data = ("test %s %s %s\n" % |
| 187 | (self.branch, self.number, self.latest_patchset)) |
| 188 | files = {fn: data} |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 189 | msg = self.subject + '-' + str(self.latest_patchset) |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 190 | c = self.addFakeChangeToRepo(msg, files, large) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 191 | ps_files = [{'file': '/COMMIT_MSG', |
| 192 | 'type': 'ADDED'}, |
| 193 | {'file': 'README', |
| 194 | 'type': 'MODIFIED'}] |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 195 | for f in files.keys(): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 196 | ps_files.append({'file': f, 'type': 'ADDED'}) |
| 197 | d = {'approvals': [], |
| 198 | 'createdOn': time.time(), |
| 199 | 'files': ps_files, |
| 200 | 'number': str(self.latest_patchset), |
| 201 | 'ref': 'refs/changes/1/%s/%s' % (self.number, |
| 202 | self.latest_patchset), |
| 203 | 'revision': c.hexsha, |
| 204 | 'uploader': {'email': 'user@example.com', |
| 205 | 'name': 'User name', |
| 206 | 'username': 'user'}} |
| 207 | self.data['currentPatchSet'] = d |
| 208 | self.patchsets.append(d) |
| 209 | self.data['submitRecords'] = self.getSubmitRecords() |
| 210 | |
| 211 | def getPatchsetCreatedEvent(self, patchset): |
| 212 | event = {"type": "patchset-created", |
| 213 | "change": {"project": self.project, |
| 214 | "branch": self.branch, |
| 215 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 216 | "number": str(self.number), |
| 217 | "subject": self.subject, |
| 218 | "owner": {"name": "User Name"}, |
| 219 | "url": "https://hostname/3"}, |
| 220 | "patchSet": self.patchsets[patchset - 1], |
| 221 | "uploader": {"name": "User Name"}} |
| 222 | return event |
| 223 | |
| 224 | def getChangeRestoredEvent(self): |
| 225 | event = {"type": "change-restored", |
| 226 | "change": {"project": self.project, |
| 227 | "branch": self.branch, |
| 228 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 229 | "number": str(self.number), |
| 230 | "subject": self.subject, |
| 231 | "owner": {"name": "User Name"}, |
| 232 | "url": "https://hostname/3"}, |
| 233 | "restorer": {"name": "User Name"}, |
Antoine Musso | bd86a31 | 2014-01-08 14:51:33 +0100 | [diff] [blame] | 234 | "patchSet": self.patchsets[-1], |
| 235 | "reason": ""} |
| 236 | return event |
| 237 | |
| 238 | def getChangeAbandonedEvent(self): |
| 239 | event = {"type": "change-abandoned", |
| 240 | "change": {"project": self.project, |
| 241 | "branch": self.branch, |
| 242 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 243 | "number": str(self.number), |
| 244 | "subject": self.subject, |
| 245 | "owner": {"name": "User Name"}, |
| 246 | "url": "https://hostname/3"}, |
| 247 | "abandoner": {"name": "User Name"}, |
| 248 | "patchSet": self.patchsets[-1], |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 249 | "reason": ""} |
| 250 | return event |
| 251 | |
| 252 | def getChangeCommentEvent(self, patchset): |
| 253 | event = {"type": "comment-added", |
| 254 | "change": {"project": self.project, |
| 255 | "branch": self.branch, |
| 256 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 257 | "number": str(self.number), |
| 258 | "subject": self.subject, |
| 259 | "owner": {"name": "User Name"}, |
| 260 | "url": "https://hostname/3"}, |
| 261 | "patchSet": self.patchsets[patchset - 1], |
| 262 | "author": {"name": "User Name"}, |
| 263 | "approvals": [{"type": "Code-Review", |
| 264 | "description": "Code-Review", |
| 265 | "value": "0"}], |
| 266 | "comment": "This is a comment"} |
| 267 | return event |
| 268 | |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 269 | def addApproval(self, category, value, username='reviewer_john', |
| 270 | granted_on=None, message=''): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 271 | if not granted_on: |
| 272 | granted_on = time.time() |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 273 | approval = { |
| 274 | 'description': self.categories[category][0], |
| 275 | 'type': category, |
| 276 | 'value': str(value), |
| 277 | 'by': { |
| 278 | 'username': username, |
| 279 | 'email': username + '@example.com', |
| 280 | }, |
| 281 | 'grantedOn': int(granted_on) |
| 282 | } |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 283 | for i, x in enumerate(self.patchsets[-1]['approvals'][:]): |
| 284 | if x['by']['username'] == username and x['type'] == category: |
| 285 | del self.patchsets[-1]['approvals'][i] |
| 286 | self.patchsets[-1]['approvals'].append(approval) |
| 287 | event = {'approvals': [approval], |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 288 | 'author': {'email': 'author@example.com', |
| 289 | 'name': 'Patchset Author', |
| 290 | 'username': 'author_phil'}, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 291 | 'change': {'branch': self.branch, |
| 292 | 'id': 'Iaa69c46accf97d0598111724a38250ae76a22c87', |
| 293 | 'number': str(self.number), |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 294 | 'owner': {'email': 'owner@example.com', |
| 295 | 'name': 'Change Owner', |
| 296 | 'username': 'owner_jane'}, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 297 | 'project': self.project, |
| 298 | 'subject': self.subject, |
| 299 | 'topic': 'master', |
| 300 | 'url': 'https://hostname/459'}, |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 301 | 'comment': message, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 302 | 'patchSet': self.patchsets[-1], |
| 303 | 'type': 'comment-added'} |
| 304 | self.data['submitRecords'] = self.getSubmitRecords() |
| 305 | return json.loads(json.dumps(event)) |
| 306 | |
| 307 | def getSubmitRecords(self): |
| 308 | status = {} |
| 309 | for cat in self.categories.keys(): |
| 310 | status[cat] = 0 |
| 311 | |
| 312 | for a in self.patchsets[-1]['approvals']: |
| 313 | cur = status[a['type']] |
| 314 | cat_min, cat_max = self.categories[a['type']][1:] |
| 315 | new = int(a['value']) |
| 316 | if new == cat_min: |
| 317 | cur = new |
| 318 | elif abs(new) > abs(cur): |
| 319 | cur = new |
| 320 | status[a['type']] = cur |
| 321 | |
| 322 | labels = [] |
| 323 | ok = True |
| 324 | for typ, cat in self.categories.items(): |
| 325 | cur = status[typ] |
| 326 | cat_min, cat_max = cat[1:] |
| 327 | if cur == cat_min: |
| 328 | value = 'REJECT' |
| 329 | ok = False |
| 330 | elif cur == cat_max: |
| 331 | value = 'OK' |
| 332 | else: |
| 333 | value = 'NEED' |
| 334 | ok = False |
| 335 | labels.append({'label': cat[0], 'status': value}) |
| 336 | if ok: |
| 337 | return [{'status': 'OK'}] |
| 338 | return [{'status': 'NOT_READY', |
| 339 | 'labels': labels}] |
| 340 | |
| 341 | def setDependsOn(self, other, patchset): |
| 342 | self.depends_on_change = other |
| 343 | d = {'id': other.data['id'], |
| 344 | 'number': other.data['number'], |
| 345 | 'ref': other.patchsets[patchset - 1]['ref'] |
| 346 | } |
| 347 | self.data['dependsOn'] = [d] |
| 348 | |
| 349 | other.needed_by_changes.append(self) |
| 350 | needed = other.data.get('neededBy', []) |
| 351 | d = {'id': self.data['id'], |
| 352 | 'number': self.data['number'], |
| 353 | 'ref': self.patchsets[patchset - 1]['ref'], |
| 354 | 'revision': self.patchsets[patchset - 1]['revision'] |
| 355 | } |
| 356 | needed.append(d) |
| 357 | other.data['neededBy'] = needed |
| 358 | |
| 359 | def query(self): |
| 360 | self.queried += 1 |
| 361 | d = self.data.get('dependsOn') |
| 362 | if d: |
| 363 | d = d[0] |
| 364 | if (self.depends_on_change.patchsets[-1]['ref'] == d['ref']): |
| 365 | d['isCurrentPatchSet'] = True |
| 366 | else: |
| 367 | d['isCurrentPatchSet'] = False |
| 368 | return json.loads(json.dumps(self.data)) |
| 369 | |
| 370 | def setMerged(self): |
| 371 | if (self.depends_on_change and |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 372 | self.depends_on_change.data['status'] != 'MERGED'): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 373 | return |
| 374 | if self.fail_merge: |
| 375 | return |
| 376 | self.data['status'] = 'MERGED' |
| 377 | self.open = False |
| 378 | |
| 379 | path = os.path.join(self.upstream_root, self.project) |
| 380 | repo = git.Repo(path) |
| 381 | repo.heads[self.branch].commit = \ |
| 382 | repo.commit(self.patchsets[-1]['revision']) |
| 383 | |
| 384 | def setReported(self): |
| 385 | self.reported += 1 |
| 386 | |
| 387 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 388 | class FakeGerritConnection(zuul.connection.gerrit.GerritConnection): |
| 389 | log = logging.getLogger("zuul.test.FakeGerritConnection") |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 390 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 391 | def __init__(self, connection_name, connection_config, |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 392 | changes_db=None, queues_db=None, upstream_root=None): |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 393 | super(FakeGerritConnection, self).__init__(connection_name, |
| 394 | connection_config) |
| 395 | |
| 396 | self.event_queue = queues_db |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 397 | self.fixture_dir = os.path.join(FIXTURE_DIR, 'gerrit') |
| 398 | self.change_number = 0 |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 399 | self.changes = changes_db |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 400 | self.queries = [] |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 401 | self.upstream_root = upstream_root |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 402 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 403 | def addFakeChange(self, project, branch, subject, status='NEW', |
| 404 | files=None): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 405 | self.change_number += 1 |
| 406 | c = FakeChange(self, self.change_number, project, branch, subject, |
| 407 | upstream_root=self.upstream_root, |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 408 | status=status, files=files) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 409 | self.changes[self.change_number] = c |
| 410 | return c |
| 411 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 412 | def review(self, project, changeid, message, action): |
| 413 | number, ps = changeid.split(',') |
| 414 | change = self.changes[int(number)] |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 415 | |
| 416 | # Add the approval back onto the change (ie simulate what gerrit would |
| 417 | # do). |
| 418 | # Usually when zuul leaves a review it'll create a feedback loop where |
| 419 | # zuul's review enters another gerrit event (which is then picked up by |
| 420 | # zuul). However, we can't mimic this behaviour (by adding this |
| 421 | # approval event into the queue) as it stops jobs from checking what |
| 422 | # happens before this event is triggered. If a job needs to see what |
| 423 | # happens they can add their own verified event into the queue. |
| 424 | # Nevertheless, we can update change with the new review in gerrit. |
| 425 | |
| 426 | for cat in ['CRVW', 'VRFY', 'APRV']: |
| 427 | if cat in action: |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 428 | change.addApproval(cat, action[cat], username=self.user) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 429 | |
| 430 | if 'label' in action: |
| 431 | parts = action['label'].split('=') |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 432 | change.addApproval(parts[0], parts[2], username=self.user) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 433 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 434 | change.messages.append(message) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 435 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 436 | if 'submit' in action: |
| 437 | change.setMerged() |
| 438 | if message: |
| 439 | change.setReported() |
| 440 | |
| 441 | def query(self, number): |
| 442 | change = self.changes.get(int(number)) |
| 443 | if change: |
| 444 | return change.query() |
| 445 | return {} |
| 446 | |
James E. Blair | c494d54 | 2014-08-06 09:23:52 -0700 | [diff] [blame] | 447 | def simpleQuery(self, query): |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 448 | self.log.debug("simpleQuery: %s" % query) |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 449 | self.queries.append(query) |
James E. Blair | 5ee2425 | 2014-12-30 10:12:29 -0800 | [diff] [blame] | 450 | if query.startswith('change:'): |
| 451 | # Query a specific changeid |
| 452 | changeid = query[len('change:'):] |
| 453 | l = [change.query() for change in self.changes.values() |
| 454 | if change.data['id'] == changeid] |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 455 | elif query.startswith('message:'): |
| 456 | # Query the content of a commit message |
| 457 | msg = query[len('message:'):].strip() |
| 458 | l = [change.query() for change in self.changes.values() |
| 459 | if msg in change.data['commitMessage']] |
James E. Blair | 5ee2425 | 2014-12-30 10:12:29 -0800 | [diff] [blame] | 460 | else: |
| 461 | # Query all open changes |
| 462 | l = [change.query() for change in self.changes.values()] |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 463 | return l |
James E. Blair | c494d54 | 2014-08-06 09:23:52 -0700 | [diff] [blame] | 464 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 465 | def _start_watcher_thread(self, *args, **kw): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 466 | pass |
| 467 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 468 | def getGitUrl(self, project): |
| 469 | return os.path.join(self.upstream_root, project.name) |
| 470 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 471 | |
| 472 | class BuildHistory(object): |
| 473 | def __init__(self, **kw): |
| 474 | self.__dict__.update(kw) |
| 475 | |
| 476 | def __repr__(self): |
| 477 | return ("<Completed build, result: %s name: %s #%s changes: %s>" % |
| 478 | (self.result, self.name, self.number, self.changes)) |
| 479 | |
| 480 | |
| 481 | class FakeURLOpener(object): |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 482 | def __init__(self, upstream_root, url): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 483 | self.upstream_root = upstream_root |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 484 | self.url = url |
| 485 | |
| 486 | def read(self): |
Morgan Fainberg | 293f7f8 | 2016-05-30 14:01:22 -0700 | [diff] [blame] | 487 | res = urllib.parse.urlparse(self.url) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 488 | path = res.path |
| 489 | project = '/'.join(path.split('/')[2:-2]) |
| 490 | ret = '001e# service=git-upload-pack\n' |
| 491 | ret += ('000000a31270149696713ba7e06f1beb760f20d359c4abed HEAD\x00' |
| 492 | 'multi_ack thin-pack side-band side-band-64k ofs-delta ' |
| 493 | 'shallow no-progress include-tag multi_ack_detailed no-done\n') |
| 494 | path = os.path.join(self.upstream_root, project) |
| 495 | repo = git.Repo(path) |
| 496 | for ref in repo.refs: |
| 497 | r = ref.object.hexsha + ' ' + ref.path + '\n' |
| 498 | ret += '%04x%s' % (len(r) + 4, r) |
| 499 | ret += '0000' |
| 500 | return ret |
| 501 | |
| 502 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 503 | class FakeStatsd(threading.Thread): |
| 504 | def __init__(self): |
| 505 | threading.Thread.__init__(self) |
| 506 | self.daemon = True |
| 507 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 508 | self.sock.bind(('', 0)) |
| 509 | self.port = self.sock.getsockname()[1] |
| 510 | self.wake_read, self.wake_write = os.pipe() |
| 511 | self.stats = [] |
| 512 | |
| 513 | def run(self): |
| 514 | while True: |
| 515 | poll = select.poll() |
| 516 | poll.register(self.sock, select.POLLIN) |
| 517 | poll.register(self.wake_read, select.POLLIN) |
| 518 | ret = poll.poll() |
| 519 | for (fd, event) in ret: |
| 520 | if fd == self.sock.fileno(): |
| 521 | data = self.sock.recvfrom(1024) |
| 522 | if not data: |
| 523 | return |
| 524 | self.stats.append(data[0]) |
| 525 | if fd == self.wake_read: |
| 526 | return |
| 527 | |
| 528 | def stop(self): |
| 529 | os.write(self.wake_write, '1\n') |
| 530 | |
| 531 | |
| 532 | class FakeBuild(threading.Thread): |
| 533 | log = logging.getLogger("zuul.test") |
| 534 | |
| 535 | def __init__(self, worker, job, number, node): |
| 536 | threading.Thread.__init__(self) |
| 537 | self.daemon = True |
| 538 | self.worker = worker |
| 539 | self.job = job |
| 540 | self.name = job.name.split(':')[1] |
| 541 | self.number = number |
| 542 | self.node = node |
| 543 | self.parameters = json.loads(job.arguments) |
| 544 | self.unique = self.parameters['ZUUL_UUID'] |
| 545 | self.wait_condition = threading.Condition() |
| 546 | self.waiting = False |
| 547 | self.aborted = False |
| 548 | self.created = time.time() |
| 549 | self.description = '' |
| 550 | self.run_error = False |
| 551 | |
| 552 | def release(self): |
| 553 | self.wait_condition.acquire() |
| 554 | self.wait_condition.notify() |
| 555 | self.waiting = False |
| 556 | self.log.debug("Build %s released" % self.unique) |
| 557 | self.wait_condition.release() |
| 558 | |
| 559 | def isWaiting(self): |
| 560 | self.wait_condition.acquire() |
| 561 | if self.waiting: |
| 562 | ret = True |
| 563 | else: |
| 564 | ret = False |
| 565 | self.wait_condition.release() |
| 566 | return ret |
| 567 | |
| 568 | def _wait(self): |
| 569 | self.wait_condition.acquire() |
| 570 | self.waiting = True |
| 571 | self.log.debug("Build %s waiting" % self.unique) |
| 572 | self.wait_condition.wait() |
| 573 | self.wait_condition.release() |
| 574 | |
| 575 | def run(self): |
| 576 | data = { |
| 577 | 'url': 'https://server/job/%s/%s/' % (self.name, self.number), |
| 578 | 'name': self.name, |
| 579 | 'number': self.number, |
| 580 | 'manager': self.worker.worker_id, |
| 581 | 'worker_name': 'My Worker', |
| 582 | 'worker_hostname': 'localhost', |
| 583 | 'worker_ips': ['127.0.0.1', '192.168.1.1'], |
| 584 | 'worker_fqdn': 'zuul.example.org', |
| 585 | 'worker_program': 'FakeBuilder', |
| 586 | 'worker_version': 'v1.1', |
| 587 | 'worker_extra': {'something': 'else'} |
| 588 | } |
| 589 | |
| 590 | self.log.debug('Running build %s' % self.unique) |
| 591 | |
| 592 | self.job.sendWorkData(json.dumps(data)) |
| 593 | self.log.debug('Sent WorkData packet with %s' % json.dumps(data)) |
| 594 | self.job.sendWorkStatus(0, 100) |
| 595 | |
| 596 | if self.worker.hold_jobs_in_build: |
| 597 | self.log.debug('Holding build %s' % self.unique) |
| 598 | self._wait() |
| 599 | self.log.debug("Build %s continuing" % self.unique) |
| 600 | |
| 601 | self.worker.lock.acquire() |
| 602 | |
| 603 | result = 'SUCCESS' |
| 604 | if (('ZUUL_REF' in self.parameters) and |
| 605 | self.worker.shouldFailTest(self.name, |
| 606 | self.parameters['ZUUL_REF'])): |
| 607 | result = 'FAILURE' |
| 608 | if self.aborted: |
| 609 | result = 'ABORTED' |
| 610 | |
| 611 | if self.run_error: |
| 612 | work_fail = True |
| 613 | result = 'RUN_ERROR' |
| 614 | else: |
| 615 | data['result'] = result |
Timothy Chavez | b233208 | 2015-08-07 20:08:04 -0500 | [diff] [blame] | 616 | data['node_labels'] = ['bare-necessities'] |
| 617 | data['node_name'] = 'foo' |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 618 | work_fail = False |
| 619 | |
| 620 | changes = None |
| 621 | if 'ZUUL_CHANGE_IDS' in self.parameters: |
| 622 | changes = self.parameters['ZUUL_CHANGE_IDS'] |
| 623 | |
| 624 | self.worker.build_history.append( |
| 625 | BuildHistory(name=self.name, number=self.number, |
| 626 | result=result, changes=changes, node=self.node, |
| 627 | uuid=self.unique, description=self.description, |
James E. Blair | 456f2fb | 2016-02-09 09:29:33 -0800 | [diff] [blame] | 628 | parameters=self.parameters, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 629 | pipeline=self.parameters['ZUUL_PIPELINE']) |
| 630 | ) |
| 631 | |
| 632 | self.job.sendWorkData(json.dumps(data)) |
| 633 | if work_fail: |
| 634 | self.job.sendWorkFail() |
| 635 | else: |
| 636 | self.job.sendWorkComplete(json.dumps(data)) |
| 637 | del self.worker.gearman_jobs[self.job.unique] |
| 638 | self.worker.running_builds.remove(self) |
| 639 | self.worker.lock.release() |
| 640 | |
| 641 | |
Joshua Hesketh | 0c54b2a | 2016-04-11 21:23:33 +1000 | [diff] [blame] | 642 | class RecordingLaunchServer(zuul.launcher.server.LaunchServer): |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 643 | def __init__(self, *args, **kw): |
| 644 | super(RecordingLaunchServer, self).__init__(*args, **kw) |
| 645 | self.job_history = [] |
| 646 | |
| 647 | def launch(self, job): |
| 648 | self.job_history.append(job) |
| 649 | job.data = [] |
| 650 | |
| 651 | def sendWorkComplete(data=b''): |
| 652 | job.data.append(data) |
| 653 | gear.WorkerJob.sendWorkComplete(job, data) |
| 654 | |
| 655 | job.sendWorkComplete = sendWorkComplete |
| 656 | super(RecordingLaunchServer, self).launch(job) |
| 657 | |
| 658 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 659 | class FakeWorker(gear.Worker): |
| 660 | def __init__(self, worker_id, test): |
| 661 | super(FakeWorker, self).__init__(worker_id) |
| 662 | self.gearman_jobs = {} |
| 663 | self.build_history = [] |
| 664 | self.running_builds = [] |
| 665 | self.build_counter = 0 |
| 666 | self.fail_tests = {} |
| 667 | self.test = test |
| 668 | |
| 669 | self.hold_jobs_in_build = False |
| 670 | self.lock = threading.Lock() |
| 671 | self.__work_thread = threading.Thread(target=self.work) |
| 672 | self.__work_thread.daemon = True |
| 673 | self.__work_thread.start() |
| 674 | |
| 675 | def handleJob(self, job): |
| 676 | parts = job.name.split(":") |
| 677 | cmd = parts[0] |
| 678 | name = parts[1] |
| 679 | if len(parts) > 2: |
| 680 | node = parts[2] |
| 681 | else: |
| 682 | node = None |
| 683 | if cmd == 'build': |
| 684 | self.handleBuild(job, name, node) |
| 685 | elif cmd == 'stop': |
| 686 | self.handleStop(job, name) |
| 687 | elif cmd == 'set_description': |
| 688 | self.handleSetDescription(job, name) |
| 689 | |
| 690 | def handleBuild(self, job, name, node): |
| 691 | build = FakeBuild(self, job, self.build_counter, node) |
| 692 | job.build = build |
| 693 | self.gearman_jobs[job.unique] = job |
| 694 | self.build_counter += 1 |
| 695 | |
| 696 | self.running_builds.append(build) |
| 697 | build.start() |
| 698 | |
| 699 | def handleStop(self, job, name): |
| 700 | self.log.debug("handle stop") |
| 701 | parameters = json.loads(job.arguments) |
| 702 | name = parameters['name'] |
| 703 | number = parameters['number'] |
| 704 | for build in self.running_builds: |
| 705 | if build.name == name and build.number == number: |
| 706 | build.aborted = True |
| 707 | build.release() |
| 708 | job.sendWorkComplete() |
| 709 | return |
| 710 | job.sendWorkFail() |
| 711 | |
| 712 | def handleSetDescription(self, job, name): |
| 713 | self.log.debug("handle set description") |
| 714 | parameters = json.loads(job.arguments) |
| 715 | name = parameters['name'] |
| 716 | number = parameters['number'] |
| 717 | descr = parameters['html_description'] |
| 718 | for build in self.running_builds: |
| 719 | if build.name == name and build.number == number: |
| 720 | build.description = descr |
| 721 | job.sendWorkComplete() |
| 722 | return |
| 723 | for build in self.build_history: |
| 724 | if build.name == name and build.number == number: |
| 725 | build.description = descr |
| 726 | job.sendWorkComplete() |
| 727 | return |
| 728 | job.sendWorkFail() |
| 729 | |
| 730 | def work(self): |
| 731 | while self.running: |
| 732 | try: |
| 733 | job = self.getJob() |
| 734 | except gear.InterruptedError: |
| 735 | continue |
| 736 | try: |
| 737 | self.handleJob(job) |
| 738 | except: |
| 739 | self.log.exception("Worker exception:") |
| 740 | |
| 741 | def addFailTest(self, name, change): |
| 742 | l = self.fail_tests.get(name, []) |
| 743 | l.append(change) |
| 744 | self.fail_tests[name] = l |
| 745 | |
| 746 | def shouldFailTest(self, name, ref): |
| 747 | l = self.fail_tests.get(name, []) |
| 748 | for change in l: |
| 749 | if self.test.ref_has_change(ref, change): |
| 750 | return True |
| 751 | return False |
| 752 | |
| 753 | def release(self, regex=None): |
| 754 | builds = self.running_builds[:] |
| 755 | self.log.debug("releasing build %s (%s)" % (regex, |
| 756 | len(self.running_builds))) |
| 757 | for build in builds: |
| 758 | if not regex or re.match(regex, build.name): |
| 759 | self.log.debug("releasing build %s" % |
| 760 | (build.parameters['ZUUL_UUID'])) |
| 761 | build.release() |
| 762 | else: |
| 763 | self.log.debug("not releasing build %s" % |
| 764 | (build.parameters['ZUUL_UUID'])) |
| 765 | self.log.debug("done releasing builds %s (%s)" % |
| 766 | (regex, len(self.running_builds))) |
| 767 | |
| 768 | |
| 769 | class FakeGearmanServer(gear.Server): |
| 770 | def __init__(self): |
| 771 | self.hold_jobs_in_queue = False |
| 772 | super(FakeGearmanServer, self).__init__(0) |
| 773 | |
| 774 | def getJobForConnection(self, connection, peek=False): |
| 775 | for queue in [self.high_queue, self.normal_queue, self.low_queue]: |
| 776 | for job in queue: |
| 777 | if not hasattr(job, 'waiting'): |
| 778 | if job.name.startswith('build:'): |
| 779 | job.waiting = self.hold_jobs_in_queue |
| 780 | else: |
| 781 | job.waiting = False |
| 782 | if job.waiting: |
| 783 | continue |
| 784 | if job.name in connection.functions: |
| 785 | if not peek: |
| 786 | queue.remove(job) |
| 787 | connection.related_jobs[job.handle] = job |
| 788 | job.worker_connection = connection |
| 789 | job.running = True |
| 790 | return job |
| 791 | return None |
| 792 | |
| 793 | def release(self, regex=None): |
| 794 | released = False |
| 795 | qlen = (len(self.high_queue) + len(self.normal_queue) + |
| 796 | len(self.low_queue)) |
| 797 | self.log.debug("releasing queued job %s (%s)" % (regex, qlen)) |
| 798 | for job in self.getQueue(): |
| 799 | cmd, name = job.name.split(':') |
| 800 | if cmd != 'build': |
| 801 | continue |
| 802 | if not regex or re.match(regex, name): |
| 803 | self.log.debug("releasing queued job %s" % |
| 804 | job.unique) |
| 805 | job.waiting = False |
| 806 | released = True |
| 807 | else: |
| 808 | self.log.debug("not releasing queued job %s" % |
| 809 | job.unique) |
| 810 | if released: |
| 811 | self.wakeConnections() |
| 812 | qlen = (len(self.high_queue) + len(self.normal_queue) + |
| 813 | len(self.low_queue)) |
| 814 | self.log.debug("done releasing queued jobs %s (%s)" % (regex, qlen)) |
| 815 | |
| 816 | |
| 817 | class FakeSMTP(object): |
| 818 | log = logging.getLogger('zuul.FakeSMTP') |
| 819 | |
| 820 | def __init__(self, messages, server, port): |
| 821 | self.server = server |
| 822 | self.port = port |
| 823 | self.messages = messages |
| 824 | |
| 825 | def sendmail(self, from_email, to_email, msg): |
| 826 | self.log.info("Sending email from %s, to %s, with msg %s" % ( |
| 827 | from_email, to_email, msg)) |
| 828 | |
| 829 | headers = msg.split('\n\n', 1)[0] |
| 830 | body = msg.split('\n\n', 1)[1] |
| 831 | |
| 832 | self.messages.append(dict( |
| 833 | from_email=from_email, |
| 834 | to_email=to_email, |
| 835 | msg=msg, |
| 836 | headers=headers, |
| 837 | body=body, |
| 838 | )) |
| 839 | |
| 840 | return True |
| 841 | |
| 842 | def quit(self): |
| 843 | return True |
| 844 | |
| 845 | |
| 846 | class FakeSwiftClientConnection(swiftclient.client.Connection): |
| 847 | def post_account(self, headers): |
| 848 | # Do nothing |
| 849 | pass |
| 850 | |
| 851 | def get_auth(self): |
| 852 | # Returns endpoint and (unused) auth token |
| 853 | endpoint = os.path.join('https://storage.example.org', 'V1', |
| 854 | 'AUTH_account') |
| 855 | return endpoint, '' |
| 856 | |
| 857 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 858 | class BaseTestCase(testtools.TestCase): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 859 | log = logging.getLogger("zuul.test") |
| 860 | |
| 861 | def setUp(self): |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 862 | super(BaseTestCase, self).setUp() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 863 | test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) |
| 864 | try: |
| 865 | test_timeout = int(test_timeout) |
| 866 | except ValueError: |
| 867 | # If timeout value is invalid do not set a timeout. |
| 868 | test_timeout = 0 |
| 869 | if test_timeout > 0: |
| 870 | self.useFixture(fixtures.Timeout(test_timeout, gentle=False)) |
| 871 | |
| 872 | if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or |
| 873 | os.environ.get('OS_STDOUT_CAPTURE') == '1'): |
| 874 | stdout = self.useFixture(fixtures.StringStream('stdout')).stream |
| 875 | self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) |
| 876 | if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or |
| 877 | os.environ.get('OS_STDERR_CAPTURE') == '1'): |
| 878 | stderr = self.useFixture(fixtures.StringStream('stderr')).stream |
| 879 | self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) |
| 880 | if (os.environ.get('OS_LOG_CAPTURE') == 'True' or |
| 881 | os.environ.get('OS_LOG_CAPTURE') == '1'): |
| 882 | self.useFixture(fixtures.FakeLogger( |
| 883 | level=logging.DEBUG, |
| 884 | format='%(asctime)s %(name)-32s ' |
| 885 | '%(levelname)-8s %(message)s')) |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 886 | |
Morgan Fainberg | d34e0b4 | 2016-06-09 19:10:38 -0700 | [diff] [blame] | 887 | # NOTE(notmorgan): Extract logging overrides for specific libraries |
| 888 | # from the OS_LOG_DEFAULTS env and create FakeLogger fixtures for |
| 889 | # each. This is used to limit the output during test runs from |
| 890 | # libraries that zuul depends on such as gear. |
| 891 | log_defaults_from_env = os.environ.get('OS_LOG_DEFAULTS') |
| 892 | |
| 893 | if log_defaults_from_env: |
| 894 | for default in log_defaults_from_env.split(','): |
| 895 | try: |
| 896 | name, level_str = default.split('=', 1) |
| 897 | level = getattr(logging, level_str, logging.DEBUG) |
| 898 | self.useFixture(fixtures.FakeLogger( |
| 899 | name=name, |
| 900 | level=level, |
| 901 | format='%(asctime)s %(name)-32s ' |
| 902 | '%(levelname)-8s %(message)s')) |
| 903 | except ValueError: |
| 904 | # NOTE(notmorgan): Invalid format of the log default, |
| 905 | # skip and don't try and apply a logger for the |
| 906 | # specified module |
| 907 | pass |
| 908 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 909 | |
| 910 | class ZuulTestCase(BaseTestCase): |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 911 | config_file = 'zuul.conf' |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 912 | |
| 913 | def setUp(self): |
| 914 | super(ZuulTestCase, self).setUp() |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 915 | if USE_TEMPDIR: |
| 916 | tmp_root = self.useFixture(fixtures.TempDir( |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 917 | rootdir=os.environ.get("ZUUL_TEST_ROOT")) |
| 918 | ).path |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 919 | else: |
| 920 | tmp_root = os.environ.get("ZUUL_TEST_ROOT") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 921 | self.test_root = os.path.join(tmp_root, "zuul-test") |
| 922 | self.upstream_root = os.path.join(self.test_root, "upstream") |
| 923 | self.git_root = os.path.join(self.test_root, "git") |
James E. Blair | ce8a213 | 2016-05-19 15:21:52 -0700 | [diff] [blame] | 924 | self.state_root = os.path.join(self.test_root, "lib") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 925 | |
| 926 | if os.path.exists(self.test_root): |
| 927 | shutil.rmtree(self.test_root) |
| 928 | os.makedirs(self.test_root) |
| 929 | os.makedirs(self.upstream_root) |
James E. Blair | ce8a213 | 2016-05-19 15:21:52 -0700 | [diff] [blame] | 930 | os.makedirs(self.state_root) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 931 | |
| 932 | # Make per test copy of Configuration. |
| 933 | self.setup_config() |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 934 | self.config.set('zuul', 'tenant_config', |
Joshua Hesketh | acccffc | 2015-03-31 23:38:17 +1100 | [diff] [blame] | 935 | os.path.join(FIXTURE_DIR, |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 936 | self.config.get('zuul', 'tenant_config'))) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 937 | self.config.set('merger', 'git_dir', self.git_root) |
James E. Blair | ce8a213 | 2016-05-19 15:21:52 -0700 | [diff] [blame] | 938 | self.config.set('zuul', 'state_dir', self.state_root) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 939 | |
| 940 | # For each project in config: |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 941 | # TODOv3(jeblair): remove these and replace with new git |
| 942 | # filesystem fixtures |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 943 | self.init_repo("org/project3") |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 944 | self.init_repo("org/project4") |
James E. Blair | bce35e1 | 2014-08-21 14:31:17 -0700 | [diff] [blame] | 945 | self.init_repo("org/project5") |
| 946 | self.init_repo("org/project6") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 947 | self.init_repo("org/one-job-project") |
| 948 | self.init_repo("org/nonvoting-project") |
| 949 | self.init_repo("org/templated-project") |
| 950 | self.init_repo("org/layered-project") |
| 951 | self.init_repo("org/node-project") |
| 952 | self.init_repo("org/conflict-project") |
| 953 | self.init_repo("org/noop-project") |
| 954 | self.init_repo("org/experimental-project") |
Evgeny Antyshev | d6e546c | 2015-06-11 15:13:57 +0000 | [diff] [blame] | 955 | self.init_repo("org/no-jobs-project") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 956 | |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 957 | self.setup_repos() |
| 958 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 959 | self.statsd = FakeStatsd() |
Ian Wienand | ff977bf | 2015-09-30 15:38:47 +1000 | [diff] [blame] | 960 | # note, use 127.0.0.1 rather than localhost to avoid getting ipv6 |
| 961 | # see: https://github.com/jsocol/pystatsd/issues/61 |
| 962 | os.environ['STATSD_HOST'] = '127.0.0.1' |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 963 | os.environ['STATSD_PORT'] = str(self.statsd.port) |
| 964 | self.statsd.start() |
| 965 | # the statsd client object is configured in the statsd module import |
Monty Taylor | 74fa386 | 2016-06-02 07:39:49 +0300 | [diff] [blame] | 966 | reload_module(statsd) |
| 967 | reload_module(zuul.scheduler) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 968 | |
| 969 | self.gearman_server = FakeGearmanServer() |
| 970 | |
| 971 | self.config.set('gearman', 'port', str(self.gearman_server.port)) |
| 972 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 973 | zuul.source.gerrit.GerritSource.replication_timeout = 1.5 |
| 974 | zuul.source.gerrit.GerritSource.replication_retry_interval = 0.5 |
| 975 | zuul.connection.gerrit.GerritEventConnector.delay = 0.0 |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 976 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 977 | self.sched = zuul.scheduler.Scheduler(self.config) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 978 | |
| 979 | self.useFixture(fixtures.MonkeyPatch('swiftclient.client.Connection', |
| 980 | FakeSwiftClientConnection)) |
| 981 | self.swift = zuul.lib.swift.Swift(self.config) |
| 982 | |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 983 | self.event_queues = [ |
| 984 | self.sched.result_event_queue, |
| 985 | self.sched.trigger_event_queue |
| 986 | ] |
| 987 | |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 988 | self.configure_connections() |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 989 | self.sched.registerConnections(self.connections) |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 990 | |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 991 | self.ansible_server = RecordingLaunchServer( |
| 992 | self.config, self.connections) |
| 993 | self.ansible_server.start() |
| 994 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 995 | def URLOpenerFactory(*args, **kw): |
Morgan Fainberg | 293f7f8 | 2016-05-30 14:01:22 -0700 | [diff] [blame] | 996 | if isinstance(args[0], urllib.request.Request): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 997 | return old_urlopen(*args, **kw) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 998 | return FakeURLOpener(self.upstream_root, *args, **kw) |
| 999 | |
Morgan Fainberg | 293f7f8 | 2016-05-30 14:01:22 -0700 | [diff] [blame] | 1000 | old_urlopen = urllib.request.urlopen |
| 1001 | urllib.request.urlopen = URLOpenerFactory |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1002 | |
Joshua Hesketh | 0c54b2a | 2016-04-11 21:23:33 +1000 | [diff] [blame] | 1003 | self.launcher = zuul.launcher.client.LaunchClient( |
James E. Blair | 8293847 | 2016-01-11 14:38:13 -0800 | [diff] [blame] | 1004 | self.config, self.sched, self.swift) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1005 | self.merge_client = zuul.merger.client.MergeClient( |
| 1006 | self.config, self.sched) |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 1007 | self.nodepool = zuul.nodepool.Nodepool(self.sched) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1008 | |
| 1009 | self.sched.setLauncher(self.launcher) |
| 1010 | self.sched.setMerger(self.merge_client) |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 1011 | self.sched.setNodepool(self.nodepool) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1012 | |
Paul Belanger | 88ef0ea | 2015-12-23 11:57:02 -0500 | [diff] [blame] | 1013 | self.webapp = zuul.webapp.WebApp( |
| 1014 | self.sched, port=0, listen_address='127.0.0.1') |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1015 | self.rpc = zuul.rpclistener.RPCListener(self.config, self.sched) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1016 | |
| 1017 | self.sched.start() |
| 1018 | self.sched.reconfigure(self.config) |
| 1019 | self.sched.resume() |
| 1020 | self.webapp.start() |
| 1021 | self.rpc.start() |
| 1022 | self.launcher.gearman.waitForServer() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1023 | |
| 1024 | self.addCleanup(self.assertFinalState) |
| 1025 | self.addCleanup(self.shutdown) |
| 1026 | |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 1027 | def configure_connections(self): |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1028 | # Register connections from the config |
| 1029 | self.smtp_messages = [] |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1030 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1031 | def FakeSMTPFactory(*args, **kw): |
| 1032 | args = [self.smtp_messages] + list(args) |
| 1033 | return FakeSMTP(*args, **kw) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1034 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1035 | self.useFixture(fixtures.MonkeyPatch('smtplib.SMTP', FakeSMTPFactory)) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1036 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1037 | # Set a changes database so multiple FakeGerrit's can report back to |
| 1038 | # a virtual canonical database given by the configured hostname |
| 1039 | self.gerrit_changes_dbs = {} |
| 1040 | self.gerrit_queues_dbs = {} |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 1041 | self.connections = zuul.lib.connections.ConnectionRegistry() |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1042 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1043 | for section_name in self.config.sections(): |
| 1044 | con_match = re.match(r'^connection ([\'\"]?)(.*)(\1)$', |
| 1045 | section_name, re.I) |
| 1046 | if not con_match: |
| 1047 | continue |
| 1048 | con_name = con_match.group(2) |
| 1049 | con_config = dict(self.config.items(section_name)) |
| 1050 | |
| 1051 | if 'driver' not in con_config: |
| 1052 | raise Exception("No driver specified for connection %s." |
| 1053 | % con_name) |
| 1054 | |
| 1055 | con_driver = con_config['driver'] |
| 1056 | |
| 1057 | # TODO(jhesketh): load the required class automatically |
| 1058 | if con_driver == 'gerrit': |
Joshua Hesketh | acccffc | 2015-03-31 23:38:17 +1100 | [diff] [blame] | 1059 | if con_config['server'] not in self.gerrit_changes_dbs.keys(): |
| 1060 | self.gerrit_changes_dbs[con_config['server']] = {} |
| 1061 | if con_config['server'] not in self.gerrit_queues_dbs.keys(): |
| 1062 | self.gerrit_queues_dbs[con_config['server']] = \ |
| 1063 | Queue.Queue() |
| 1064 | self.event_queues.append( |
| 1065 | self.gerrit_queues_dbs[con_config['server']]) |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1066 | self.connections.connections[con_name] = FakeGerritConnection( |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1067 | con_name, con_config, |
Joshua Hesketh | acccffc | 2015-03-31 23:38:17 +1100 | [diff] [blame] | 1068 | changes_db=self.gerrit_changes_dbs[con_config['server']], |
| 1069 | queues_db=self.gerrit_queues_dbs[con_config['server']], |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1070 | upstream_root=self.upstream_root |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1071 | ) |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1072 | setattr(self, 'fake_' + con_name, |
| 1073 | self.connections.connections[con_name]) |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1074 | elif con_driver == 'smtp': |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1075 | self.connections.connections[con_name] = \ |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1076 | zuul.connection.smtp.SMTPConnection(con_name, con_config) |
| 1077 | else: |
| 1078 | raise Exception("Unknown driver, %s, for connection %s" |
| 1079 | % (con_config['driver'], con_name)) |
| 1080 | |
| 1081 | # If the [gerrit] or [smtp] sections still exist, load them in as a |
| 1082 | # connection named 'gerrit' or 'smtp' respectfully |
| 1083 | |
| 1084 | if 'gerrit' in self.config.sections(): |
| 1085 | self.gerrit_changes_dbs['gerrit'] = {} |
| 1086 | self.gerrit_queues_dbs['gerrit'] = Queue.Queue() |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1087 | self.event_queues.append(self.gerrit_queues_dbs['gerrit']) |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1088 | self.connections.connections['gerrit'] = FakeGerritConnection( |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1089 | '_legacy_gerrit', dict(self.config.items('gerrit')), |
| 1090 | changes_db=self.gerrit_changes_dbs['gerrit'], |
| 1091 | queues_db=self.gerrit_queues_dbs['gerrit']) |
| 1092 | |
| 1093 | if 'smtp' in self.config.sections(): |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1094 | self.connections.connections['smtp'] = \ |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1095 | zuul.connection.smtp.SMTPConnection( |
| 1096 | '_legacy_smtp', dict(self.config.items('smtp'))) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1097 | |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1098 | def setup_config(self): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1099 | """Per test config object. Override to set different config.""" |
| 1100 | self.config = ConfigParser.ConfigParser() |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1101 | self.config.read(os.path.join(FIXTURE_DIR, self.config_file)) |
James E. Blair | 2a629ec | 2015-12-22 15:32:02 -0800 | [diff] [blame] | 1102 | if hasattr(self, 'tenant_config_file'): |
| 1103 | self.config.set('zuul', 'tenant_config', self.tenant_config_file) |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1104 | git_path = os.path.join( |
| 1105 | os.path.dirname( |
| 1106 | os.path.join(FIXTURE_DIR, self.tenant_config_file)), |
| 1107 | 'git') |
| 1108 | if os.path.exists(git_path): |
| 1109 | for reponame in os.listdir(git_path): |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 1110 | project = reponame.replace('_', '/') |
| 1111 | self.copyDirToRepo(project, |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1112 | os.path.join(git_path, reponame)) |
| 1113 | |
| 1114 | def copyDirToRepo(self, project, source_path): |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 1115 | self.init_repo(project) |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1116 | |
| 1117 | files = {} |
| 1118 | for (dirpath, dirnames, filenames) in os.walk(source_path): |
| 1119 | for filename in filenames: |
| 1120 | test_tree_filepath = os.path.join(dirpath, filename) |
| 1121 | common_path = os.path.commonprefix([test_tree_filepath, |
| 1122 | source_path]) |
| 1123 | relative_filepath = test_tree_filepath[len(common_path) + 1:] |
| 1124 | with open(test_tree_filepath, 'r') as f: |
| 1125 | content = f.read() |
| 1126 | files[relative_filepath] = content |
| 1127 | self.addCommitToRepo(project, 'add content from fixture', |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 1128 | files, branch='master', tag='init') |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1129 | |
| 1130 | def setup_repos(self): |
| 1131 | """Subclasses can override to manipulate repos before tests""" |
| 1132 | pass |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1133 | |
| 1134 | def assertFinalState(self): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1135 | # Make sure that git.Repo objects have been garbage collected. |
| 1136 | repos = [] |
| 1137 | gc.collect() |
| 1138 | for obj in gc.get_objects(): |
| 1139 | if isinstance(obj, git.Repo): |
| 1140 | repos.append(obj) |
| 1141 | self.assertEqual(len(repos), 0) |
| 1142 | self.assertEmptyQueues() |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1143 | ipm = zuul.manager.independent.IndependentPipelineManager |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1144 | for tenant in self.sched.abide.tenants.values(): |
| 1145 | for pipeline in tenant.layout.pipelines.values(): |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1146 | if isinstance(pipeline.manager, ipm): |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1147 | self.assertEqual(len(pipeline.queues), 0) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1148 | |
| 1149 | def shutdown(self): |
| 1150 | self.log.debug("Shutting down after tests") |
| 1151 | self.launcher.stop() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1152 | self.merge_client.stop() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1153 | self.sched.stop() |
| 1154 | self.sched.join() |
| 1155 | self.statsd.stop() |
| 1156 | self.statsd.join() |
| 1157 | self.webapp.stop() |
| 1158 | self.webapp.join() |
| 1159 | self.rpc.stop() |
| 1160 | self.rpc.join() |
| 1161 | self.gearman_server.shutdown() |
| 1162 | threads = threading.enumerate() |
| 1163 | if len(threads) > 1: |
| 1164 | self.log.error("More than one thread is running: %s" % threads) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1165 | |
| 1166 | def init_repo(self, project): |
| 1167 | parts = project.split('/') |
| 1168 | path = os.path.join(self.upstream_root, *parts[:-1]) |
| 1169 | if not os.path.exists(path): |
| 1170 | os.makedirs(path) |
| 1171 | path = os.path.join(self.upstream_root, project) |
| 1172 | repo = git.Repo.init(path) |
| 1173 | |
Morgan Fainberg | 78c301a | 2016-07-14 13:47:01 -0700 | [diff] [blame] | 1174 | with repo.config_writer() as config_writer: |
| 1175 | config_writer.set_value('user', 'email', 'user@example.com') |
| 1176 | config_writer.set_value('user', 'name', 'User Name') |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1177 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1178 | repo.index.commit('initial commit') |
| 1179 | master = repo.create_head('master') |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1180 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1181 | repo.head.reference = master |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 1182 | zuul.merger.merger.reset_repo_to_head(repo) |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1183 | repo.git.clean('-x', '-f', '-d') |
| 1184 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1185 | def create_branch(self, project, branch): |
| 1186 | path = os.path.join(self.upstream_root, project) |
| 1187 | repo = git.Repo.init(path) |
| 1188 | fn = os.path.join(path, 'README') |
| 1189 | |
| 1190 | branch_head = repo.create_head(branch) |
| 1191 | repo.head.reference = branch_head |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1192 | f = open(fn, 'a') |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1193 | f.write("test %s\n" % branch) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1194 | f.close() |
| 1195 | repo.index.add([fn]) |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1196 | repo.index.commit('%s commit' % branch) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1197 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1198 | repo.head.reference = repo.heads['master'] |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 1199 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1200 | repo.git.clean('-x', '-f', '-d') |
| 1201 | |
Sachi King | 9f16d52 | 2016-03-16 12:20:45 +1100 | [diff] [blame] | 1202 | def create_commit(self, project): |
| 1203 | path = os.path.join(self.upstream_root, project) |
| 1204 | repo = git.Repo(path) |
| 1205 | repo.head.reference = repo.heads['master'] |
| 1206 | file_name = os.path.join(path, 'README') |
| 1207 | with open(file_name, 'a') as f: |
| 1208 | f.write('creating fake commit\n') |
| 1209 | repo.index.add([file_name]) |
| 1210 | commit = repo.index.commit('Creating a fake commit') |
| 1211 | return commit.hexsha |
| 1212 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1213 | def ref_has_change(self, ref, change): |
| 1214 | path = os.path.join(self.git_root, change.project) |
| 1215 | repo = git.Repo(path) |
Mike Heald | 8225f52 | 2014-11-21 09:52:33 +0000 | [diff] [blame] | 1216 | try: |
| 1217 | for commit in repo.iter_commits(ref): |
| 1218 | if commit.message.strip() == ('%s-1' % change.subject): |
| 1219 | return True |
| 1220 | except GitCommandError: |
| 1221 | pass |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1222 | return False |
| 1223 | |
| 1224 | def job_has_changes(self, *args): |
| 1225 | job = args[0] |
| 1226 | commits = args[1:] |
| 1227 | if isinstance(job, FakeBuild): |
| 1228 | parameters = job.parameters |
| 1229 | else: |
| 1230 | parameters = json.loads(job.arguments) |
| 1231 | project = parameters['ZUUL_PROJECT'] |
| 1232 | path = os.path.join(self.git_root, project) |
| 1233 | repo = git.Repo(path) |
| 1234 | ref = parameters['ZUUL_REF'] |
| 1235 | sha = parameters['ZUUL_COMMIT'] |
| 1236 | repo_messages = [c.message.strip() for c in repo.iter_commits(ref)] |
| 1237 | repo_shas = [c.hexsha for c in repo.iter_commits(ref)] |
| 1238 | commit_messages = ['%s-1' % commit.subject for commit in commits] |
| 1239 | self.log.debug("Checking if job %s has changes; commit_messages %s;" |
| 1240 | " repo_messages %s; sha %s" % (job, commit_messages, |
| 1241 | repo_messages, sha)) |
| 1242 | for msg in commit_messages: |
| 1243 | if msg not in repo_messages: |
| 1244 | self.log.debug(" messages do not match") |
| 1245 | return False |
| 1246 | if repo_shas[0] != sha: |
| 1247 | self.log.debug(" sha does not match") |
| 1248 | return False |
| 1249 | self.log.debug(" OK") |
| 1250 | return True |
| 1251 | |
James E. Blair | b8c1647 | 2015-05-05 14:55:26 -0700 | [diff] [blame] | 1252 | def orderedRelease(self): |
| 1253 | # Run one build at a time to ensure non-race order: |
| 1254 | while len(self.builds): |
| 1255 | self.release(self.builds[0]) |
| 1256 | self.waitUntilSettled() |
| 1257 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1258 | def release(self, job): |
| 1259 | if isinstance(job, FakeBuild): |
| 1260 | job.release() |
| 1261 | else: |
| 1262 | job.waiting = False |
| 1263 | self.log.debug("Queued job %s released" % job.unique) |
| 1264 | self.gearman_server.wakeConnections() |
| 1265 | |
| 1266 | def getParameter(self, job, name): |
| 1267 | if isinstance(job, FakeBuild): |
| 1268 | return job.parameters[name] |
| 1269 | else: |
| 1270 | parameters = json.loads(job.arguments) |
| 1271 | return parameters[name] |
| 1272 | |
| 1273 | def resetGearmanServer(self): |
| 1274 | self.worker.setFunctions([]) |
| 1275 | while True: |
| 1276 | done = True |
| 1277 | for connection in self.gearman_server.active_connections: |
| 1278 | if (connection.functions and |
| 1279 | connection.client_id not in ['Zuul RPC Listener', |
| 1280 | 'Zuul Merger']): |
| 1281 | done = False |
| 1282 | if done: |
| 1283 | break |
| 1284 | time.sleep(0) |
| 1285 | self.gearman_server.functions = set() |
| 1286 | self.rpc.register() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1287 | |
| 1288 | def haveAllBuildsReported(self): |
| 1289 | # See if Zuul is waiting on a meta job to complete |
| 1290 | if self.launcher.meta_jobs: |
| 1291 | return False |
| 1292 | # Find out if every build that the worker has completed has been |
| 1293 | # reported back to Zuul. If it hasn't then that means a Gearman |
| 1294 | # event is still in transit and the system is not stable. |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1295 | for job in self.ansible_server.job_history: |
| 1296 | zbuild = self.launcher.builds.get(job.unique) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1297 | if not zbuild: |
| 1298 | # It has already been reported |
| 1299 | continue |
| 1300 | # It hasn't been reported yet. |
| 1301 | return False |
| 1302 | # Make sure that none of the worker connections are in GRAB_WAIT |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1303 | for connection in self.ansible_server.worker.active_connections: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1304 | if connection.state == 'GRAB_WAIT': |
| 1305 | return False |
| 1306 | return True |
| 1307 | |
| 1308 | def areAllBuildsWaiting(self): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1309 | builds = self.launcher.builds.values() |
| 1310 | for build in builds: |
| 1311 | client_job = None |
| 1312 | for conn in self.launcher.gearman.active_connections: |
| 1313 | for j in conn.related_jobs.values(): |
| 1314 | if j.unique == build.uuid: |
| 1315 | client_job = j |
| 1316 | break |
| 1317 | if not client_job: |
| 1318 | self.log.debug("%s is not known to the gearman client" % |
| 1319 | build) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1320 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1321 | if not client_job.handle: |
| 1322 | self.log.debug("%s has no handle" % client_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1323 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1324 | server_job = self.gearman_server.jobs.get(client_job.handle) |
| 1325 | if not server_job: |
| 1326 | self.log.debug("%s is not known to the gearman server" % |
| 1327 | client_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1328 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1329 | if not hasattr(server_job, 'waiting'): |
| 1330 | self.log.debug("%s is being enqueued" % server_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1331 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1332 | if server_job.waiting: |
| 1333 | continue |
James E. Blair | bbda470 | 2016-03-09 15:19:56 -0800 | [diff] [blame] | 1334 | if build.number is None: |
| 1335 | self.log.debug("%s has not reported start" % build) |
| 1336 | return False |
| 1337 | if False: # worker_job.build.isWaiting(): |
| 1338 | # TODOv3: when we grow the ability to have fake |
| 1339 | # ansible jobs wait, check for that here. |
| 1340 | continue |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1341 | else: |
James E. Blair | bbda470 | 2016-03-09 15:19:56 -0800 | [diff] [blame] | 1342 | self.log.debug("%s is running" % build) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1343 | return False |
| 1344 | return True |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1345 | |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1346 | def eventQueuesEmpty(self): |
| 1347 | for queue in self.event_queues: |
| 1348 | yield queue.empty() |
| 1349 | |
| 1350 | def eventQueuesJoin(self): |
| 1351 | for queue in self.event_queues: |
| 1352 | queue.join() |
| 1353 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1354 | def waitUntilSettled(self): |
| 1355 | self.log.debug("Waiting until settled...") |
| 1356 | start = time.time() |
| 1357 | while True: |
| 1358 | if time.time() - start > 10: |
James E. Blair | 622c968 | 2016-06-09 08:14:53 -0700 | [diff] [blame] | 1359 | self.log.debug("Queue status:") |
| 1360 | for queue in self.event_queues: |
| 1361 | self.log.debug(" %s: %s" % (queue, queue.empty())) |
| 1362 | self.log.debug("All builds waiting: %s" % |
| 1363 | (self.areAllBuildsWaiting(),)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1364 | raise Exception("Timeout waiting for Zuul to settle") |
| 1365 | # Make sure no new events show up while we're checking |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1366 | # have all build states propogated to zuul? |
| 1367 | if self.haveAllBuildsReported(): |
| 1368 | # Join ensures that the queue is empty _and_ events have been |
| 1369 | # processed |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1370 | self.eventQueuesJoin() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1371 | self.sched.run_handler_lock.acquire() |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 1372 | if (not self.merge_client.jobs and |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1373 | all(self.eventQueuesEmpty()) and |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1374 | self.haveAllBuildsReported() and |
| 1375 | self.areAllBuildsWaiting()): |
| 1376 | self.sched.run_handler_lock.release() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1377 | self.log.debug("...settled.") |
| 1378 | return |
| 1379 | self.sched.run_handler_lock.release() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1380 | self.sched.wake_event.wait(0.1) |
| 1381 | |
| 1382 | def countJobResults(self, jobs, result): |
| 1383 | jobs = filter(lambda x: x.result == result, jobs) |
| 1384 | return len(jobs) |
| 1385 | |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1386 | def getJobFromHistory(self, name, project=None): |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1387 | history = self.ansible_server.job_history |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1388 | for job in history: |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1389 | params = json.loads(job.arguments) |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1390 | if (params['job'] == name and |
| 1391 | (project is None or params['ZUUL_PROJECT'] == project)): |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1392 | result = json.loads(job.data[-1]) |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1393 | ret = BuildHistory(job=job, |
| 1394 | name=params['job'], |
| 1395 | result=result['result']) |
| 1396 | return ret |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1397 | raise Exception("Unable to find job %s in history" % name) |
| 1398 | |
| 1399 | def assertEmptyQueues(self): |
| 1400 | # Make sure there are no orphaned jobs |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1401 | for tenant in self.sched.abide.tenants.values(): |
| 1402 | for pipeline in tenant.layout.pipelines.values(): |
| 1403 | for queue in pipeline.queues: |
| 1404 | if len(queue.queue) != 0: |
Joshua Hesketh | 0aa7e8b | 2016-07-14 00:12:25 +1000 | [diff] [blame] | 1405 | print('pipeline %s queue %s contents %s' % ( |
| 1406 | pipeline.name, queue.name, queue.queue)) |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1407 | self.assertEqual(len(queue.queue), 0, |
| 1408 | "Pipelines queues should be empty") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1409 | |
| 1410 | def assertReportedStat(self, key, value=None, kind=None): |
| 1411 | start = time.time() |
| 1412 | while time.time() < (start + 5): |
| 1413 | for stat in self.statsd.stats: |
| 1414 | pprint.pprint(self.statsd.stats) |
| 1415 | k, v = stat.split(':') |
| 1416 | if key == k: |
| 1417 | if value is None and kind is None: |
| 1418 | return |
| 1419 | elif value: |
| 1420 | if value == v: |
| 1421 | return |
| 1422 | elif kind: |
| 1423 | if v.endswith('|' + kind): |
| 1424 | return |
| 1425 | time.sleep(0.1) |
| 1426 | |
| 1427 | pprint.pprint(self.statsd.stats) |
| 1428 | raise Exception("Key %s not found in reported stats" % key) |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1429 | |
| 1430 | def getPipeline(self, name): |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 1431 | return self.sched.abide.tenants.values()[0].layout.pipelines.get(name) |
| 1432 | |
| 1433 | def updateConfigLayout(self, path): |
| 1434 | root = os.path.join(self.test_root, "config") |
| 1435 | os.makedirs(root) |
| 1436 | f = tempfile.NamedTemporaryFile(dir=root, delete=False) |
| 1437 | f.write(""" |
| 1438 | tenants: |
| 1439 | - name: openstack |
| 1440 | include: |
| 1441 | - %s |
| 1442 | """ % os.path.abspath(path)) |
| 1443 | f.close() |
| 1444 | self.config.set('zuul', 'tenant_config', f.name) |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 1445 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 1446 | def addCommitToRepo(self, project, message, files, |
| 1447 | branch='master', tag=None): |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 1448 | path = os.path.join(self.upstream_root, project) |
| 1449 | repo = git.Repo(path) |
| 1450 | repo.head.reference = branch |
| 1451 | zuul.merger.merger.reset_repo_to_head(repo) |
| 1452 | for fn, content in files.items(): |
| 1453 | fn = os.path.join(path, fn) |
| 1454 | with open(fn, 'w') as f: |
| 1455 | f.write(content) |
| 1456 | repo.index.add([fn]) |
| 1457 | commit = repo.index.commit(message) |
| 1458 | repo.heads[branch].commit = commit |
| 1459 | repo.head.reference = branch |
| 1460 | repo.git.clean('-x', '-f', '-d') |
| 1461 | repo.heads[branch].checkout() |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame^] | 1462 | if tag: |
| 1463 | repo.create_tag(tag) |