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