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