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. |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 4 | # Copyright 2016 Red Hat, Inc. |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 5 | # |
| 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 7 | # not use this file except in compliance with the License. You may obtain |
| 8 | # a copy of the License at |
| 9 | # |
| 10 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | # |
| 12 | # Unless required by applicable law or agreed to in writing, software |
| 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 15 | # License for the specific language governing permissions and limitations |
| 16 | # under the License. |
| 17 | |
Christian Berendt | ffba5df | 2014-06-07 21:30:22 +0200 | [diff] [blame] | 18 | from six.moves import configparser as ConfigParser |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 19 | import gc |
| 20 | import hashlib |
| 21 | import json |
| 22 | import logging |
| 23 | import os |
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 |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 31 | from six import StringIO |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 32 | import socket |
| 33 | import string |
| 34 | import subprocess |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 35 | import sys |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 36 | import tempfile |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 37 | import threading |
| 38 | import time |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 39 | import uuid |
| 40 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 41 | |
| 42 | import git |
| 43 | import gear |
| 44 | import fixtures |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 45 | import kazoo.client |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 46 | import kazoo.exceptions |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 47 | import pymysql |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 48 | import statsd |
| 49 | import testtools |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 50 | import testtools.content |
| 51 | import testtools.content_type |
Clint Byrum | 3343e3e | 2016-11-15 16:05:03 -0800 | [diff] [blame] | 52 | from git.exc import NoSuchPathError |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 53 | import yaml |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 54 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 55 | import zuul.driver.gerrit.gerritsource as gerritsource |
| 56 | import zuul.driver.gerrit.gerritconnection as gerritconnection |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 57 | import zuul.scheduler |
| 58 | import zuul.webapp |
| 59 | import zuul.rpclistener |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 60 | import zuul.executor.server |
| 61 | import zuul.executor.client |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 62 | import zuul.lib.connections |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 63 | import zuul.merger.client |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 64 | import zuul.merger.merger |
| 65 | import zuul.merger.server |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 66 | import zuul.nodepool |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 67 | import zuul.zk |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 68 | |
| 69 | FIXTURE_DIR = os.path.join(os.path.dirname(__file__), |
| 70 | 'fixtures') |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 71 | |
| 72 | KEEP_TEMPDIRS = bool(os.environ.get('KEEP_TEMPDIRS', False)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 73 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 74 | |
| 75 | def repack_repo(path): |
| 76 | cmd = ['git', '--git-dir=%s/.git' % path, 'repack', '-afd'] |
| 77 | output = subprocess.Popen(cmd, close_fds=True, |
| 78 | stdout=subprocess.PIPE, |
| 79 | stderr=subprocess.PIPE) |
| 80 | out = output.communicate() |
| 81 | if output.returncode: |
| 82 | raise Exception("git repack returned %d" % output.returncode) |
| 83 | return out |
| 84 | |
| 85 | |
| 86 | def random_sha1(): |
| 87 | return hashlib.sha1(str(random.random())).hexdigest() |
| 88 | |
| 89 | |
James E. Blair | a190f3b | 2015-01-05 14:56:54 -0800 | [diff] [blame] | 90 | def iterate_timeout(max_seconds, purpose): |
| 91 | start = time.time() |
| 92 | count = 0 |
| 93 | while (time.time() < start + max_seconds): |
| 94 | count += 1 |
| 95 | yield count |
| 96 | time.sleep(0) |
| 97 | raise Exception("Timeout waiting for %s" % purpose) |
| 98 | |
| 99 | |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 100 | def simple_layout(path): |
| 101 | """Specify a layout file for use by a test method. |
| 102 | |
| 103 | :arg str path: The path to the layout file. |
| 104 | |
| 105 | Some tests require only a very simple configuration. For those, |
| 106 | establishing a complete config directory hierachy is too much |
| 107 | work. In those cases, you can add a simple zuul.yaml file to the |
| 108 | test fixtures directory (in fixtures/layouts/foo.yaml) and use |
| 109 | this decorator to indicate the test method should use that rather |
| 110 | than the tenant config file specified by the test class. |
| 111 | |
| 112 | The decorator will cause that layout file to be added to a |
| 113 | config-project called "common-config" and each "project" instance |
| 114 | referenced in the layout file will have a git repo automatically |
| 115 | initialized. |
| 116 | """ |
| 117 | |
| 118 | def decorator(test): |
| 119 | test.__simple_layout__ = path |
| 120 | return test |
| 121 | return decorator |
| 122 | |
| 123 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 124 | class ChangeReference(git.Reference): |
| 125 | _common_path_default = "refs/changes" |
| 126 | _points_to_commits_only = True |
| 127 | |
| 128 | |
| 129 | class FakeChange(object): |
James E. Blair | 8b5408c | 2016-08-08 15:37:46 -0700 | [diff] [blame] | 130 | categories = {'approved': ('Approved', -1, 1), |
| 131 | 'code-review': ('Code-Review', -2, 2), |
| 132 | 'verified': ('Verified', -2, 2)} |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 133 | |
| 134 | def __init__(self, gerrit, number, project, branch, subject, |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 135 | status='NEW', upstream_root=None, files={}): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 136 | self.gerrit = gerrit |
| 137 | self.reported = 0 |
| 138 | self.queried = 0 |
| 139 | self.patchsets = [] |
| 140 | self.number = number |
| 141 | self.project = project |
| 142 | self.branch = branch |
| 143 | self.subject = subject |
| 144 | self.latest_patchset = 0 |
| 145 | self.depends_on_change = None |
| 146 | self.needed_by_changes = [] |
| 147 | self.fail_merge = False |
| 148 | self.messages = [] |
| 149 | self.data = { |
| 150 | 'branch': branch, |
| 151 | 'comments': [], |
| 152 | 'commitMessage': subject, |
| 153 | 'createdOn': time.time(), |
| 154 | 'id': 'I' + random_sha1(), |
| 155 | 'lastUpdated': time.time(), |
| 156 | 'number': str(number), |
| 157 | 'open': status == 'NEW', |
| 158 | 'owner': {'email': 'user@example.com', |
| 159 | 'name': 'User Name', |
| 160 | 'username': 'username'}, |
| 161 | 'patchSets': self.patchsets, |
| 162 | 'project': project, |
| 163 | 'status': status, |
| 164 | 'subject': subject, |
| 165 | 'submitRecords': [], |
| 166 | 'url': 'https://hostname/%s' % number} |
| 167 | |
| 168 | self.upstream_root = upstream_root |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 169 | self.addPatchset(files=files) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 170 | self.data['submitRecords'] = self.getSubmitRecords() |
| 171 | self.open = status == 'NEW' |
| 172 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 173 | def addFakeChangeToRepo(self, msg, files, large): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 174 | path = os.path.join(self.upstream_root, self.project) |
| 175 | repo = git.Repo(path) |
| 176 | ref = ChangeReference.create(repo, '1/%s/%s' % (self.number, |
| 177 | self.latest_patchset), |
| 178 | 'refs/tags/init') |
| 179 | repo.head.reference = ref |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 180 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 181 | repo.git.clean('-x', '-f', '-d') |
| 182 | |
| 183 | path = os.path.join(self.upstream_root, self.project) |
| 184 | if not large: |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 185 | for fn, content in files.items(): |
| 186 | fn = os.path.join(path, fn) |
| 187 | with open(fn, 'w') as f: |
| 188 | f.write(content) |
| 189 | repo.index.add([fn]) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 190 | else: |
| 191 | for fni in range(100): |
| 192 | fn = os.path.join(path, str(fni)) |
| 193 | f = open(fn, 'w') |
| 194 | for ci in range(4096): |
| 195 | f.write(random.choice(string.printable)) |
| 196 | f.close() |
| 197 | repo.index.add([fn]) |
| 198 | |
| 199 | r = repo.index.commit(msg) |
| 200 | repo.head.reference = 'master' |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 201 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 202 | repo.git.clean('-x', '-f', '-d') |
| 203 | repo.heads['master'].checkout() |
| 204 | return r |
| 205 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 206 | def addPatchset(self, files=None, large=False): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 207 | self.latest_patchset += 1 |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 208 | if not files: |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 209 | fn = '%s-%s' % (self.branch.replace('/', '_'), self.number) |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 210 | data = ("test %s %s %s\n" % |
| 211 | (self.branch, self.number, self.latest_patchset)) |
| 212 | files = {fn: data} |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 213 | msg = self.subject + '-' + str(self.latest_patchset) |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 214 | c = self.addFakeChangeToRepo(msg, files, large) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 215 | ps_files = [{'file': '/COMMIT_MSG', |
| 216 | 'type': 'ADDED'}, |
| 217 | {'file': 'README', |
| 218 | 'type': 'MODIFIED'}] |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 219 | for f in files.keys(): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 220 | ps_files.append({'file': f, 'type': 'ADDED'}) |
| 221 | d = {'approvals': [], |
| 222 | 'createdOn': time.time(), |
| 223 | 'files': ps_files, |
| 224 | 'number': str(self.latest_patchset), |
| 225 | 'ref': 'refs/changes/1/%s/%s' % (self.number, |
| 226 | self.latest_patchset), |
| 227 | 'revision': c.hexsha, |
| 228 | 'uploader': {'email': 'user@example.com', |
| 229 | 'name': 'User name', |
| 230 | 'username': 'user'}} |
| 231 | self.data['currentPatchSet'] = d |
| 232 | self.patchsets.append(d) |
| 233 | self.data['submitRecords'] = self.getSubmitRecords() |
| 234 | |
| 235 | def getPatchsetCreatedEvent(self, patchset): |
| 236 | event = {"type": "patchset-created", |
| 237 | "change": {"project": self.project, |
| 238 | "branch": self.branch, |
| 239 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 240 | "number": str(self.number), |
| 241 | "subject": self.subject, |
| 242 | "owner": {"name": "User Name"}, |
| 243 | "url": "https://hostname/3"}, |
| 244 | "patchSet": self.patchsets[patchset - 1], |
| 245 | "uploader": {"name": "User Name"}} |
| 246 | return event |
| 247 | |
| 248 | def getChangeRestoredEvent(self): |
| 249 | event = {"type": "change-restored", |
| 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 | "restorer": {"name": "User Name"}, |
Antoine Musso | bd86a31 | 2014-01-08 14:51:33 +0100 | [diff] [blame] | 258 | "patchSet": self.patchsets[-1], |
| 259 | "reason": ""} |
| 260 | return event |
| 261 | |
| 262 | def getChangeAbandonedEvent(self): |
| 263 | event = {"type": "change-abandoned", |
| 264 | "change": {"project": self.project, |
| 265 | "branch": self.branch, |
| 266 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 267 | "number": str(self.number), |
| 268 | "subject": self.subject, |
| 269 | "owner": {"name": "User Name"}, |
| 270 | "url": "https://hostname/3"}, |
| 271 | "abandoner": {"name": "User Name"}, |
| 272 | "patchSet": self.patchsets[-1], |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 273 | "reason": ""} |
| 274 | return event |
| 275 | |
| 276 | def getChangeCommentEvent(self, patchset): |
| 277 | event = {"type": "comment-added", |
| 278 | "change": {"project": self.project, |
| 279 | "branch": self.branch, |
| 280 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 281 | "number": str(self.number), |
| 282 | "subject": self.subject, |
| 283 | "owner": {"name": "User Name"}, |
| 284 | "url": "https://hostname/3"}, |
| 285 | "patchSet": self.patchsets[patchset - 1], |
| 286 | "author": {"name": "User Name"}, |
James E. Blair | 8b5408c | 2016-08-08 15:37:46 -0700 | [diff] [blame] | 287 | "approvals": [{"type": "code-review", |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 288 | "description": "Code-Review", |
| 289 | "value": "0"}], |
| 290 | "comment": "This is a comment"} |
| 291 | return event |
| 292 | |
James E. Blair | c2a5ed7 | 2017-02-20 14:12:01 -0500 | [diff] [blame] | 293 | def getChangeMergedEvent(self): |
| 294 | event = {"submitter": {"name": "Jenkins", |
| 295 | "username": "jenkins"}, |
| 296 | "newRev": "29ed3b5f8f750a225c5be70235230e3a6ccb04d9", |
| 297 | "patchSet": self.patchsets[-1], |
| 298 | "change": self.data, |
| 299 | "type": "change-merged", |
| 300 | "eventCreatedOn": 1487613810} |
| 301 | return event |
| 302 | |
James E. Blair | 8cce42e | 2016-10-18 08:18:36 -0700 | [diff] [blame] | 303 | def getRefUpdatedEvent(self): |
| 304 | path = os.path.join(self.upstream_root, self.project) |
| 305 | repo = git.Repo(path) |
| 306 | oldrev = repo.heads[self.branch].commit.hexsha |
| 307 | |
| 308 | event = { |
| 309 | "type": "ref-updated", |
| 310 | "submitter": { |
| 311 | "name": "User Name", |
| 312 | }, |
| 313 | "refUpdate": { |
| 314 | "oldRev": oldrev, |
| 315 | "newRev": self.patchsets[-1]['revision'], |
| 316 | "refName": self.branch, |
| 317 | "project": self.project, |
| 318 | } |
| 319 | } |
| 320 | return event |
| 321 | |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 322 | def addApproval(self, category, value, username='reviewer_john', |
| 323 | granted_on=None, message=''): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 324 | if not granted_on: |
| 325 | granted_on = time.time() |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 326 | approval = { |
| 327 | 'description': self.categories[category][0], |
| 328 | 'type': category, |
| 329 | 'value': str(value), |
| 330 | 'by': { |
| 331 | 'username': username, |
| 332 | 'email': username + '@example.com', |
| 333 | }, |
| 334 | 'grantedOn': int(granted_on) |
| 335 | } |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 336 | for i, x in enumerate(self.patchsets[-1]['approvals'][:]): |
| 337 | if x['by']['username'] == username and x['type'] == category: |
| 338 | del self.patchsets[-1]['approvals'][i] |
| 339 | self.patchsets[-1]['approvals'].append(approval) |
| 340 | event = {'approvals': [approval], |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 341 | 'author': {'email': 'author@example.com', |
| 342 | 'name': 'Patchset Author', |
| 343 | 'username': 'author_phil'}, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 344 | 'change': {'branch': self.branch, |
| 345 | 'id': 'Iaa69c46accf97d0598111724a38250ae76a22c87', |
| 346 | 'number': str(self.number), |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 347 | 'owner': {'email': 'owner@example.com', |
| 348 | 'name': 'Change Owner', |
| 349 | 'username': 'owner_jane'}, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 350 | 'project': self.project, |
| 351 | 'subject': self.subject, |
| 352 | 'topic': 'master', |
| 353 | 'url': 'https://hostname/459'}, |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 354 | 'comment': message, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 355 | 'patchSet': self.patchsets[-1], |
| 356 | 'type': 'comment-added'} |
| 357 | self.data['submitRecords'] = self.getSubmitRecords() |
| 358 | return json.loads(json.dumps(event)) |
| 359 | |
| 360 | def getSubmitRecords(self): |
| 361 | status = {} |
| 362 | for cat in self.categories.keys(): |
| 363 | status[cat] = 0 |
| 364 | |
| 365 | for a in self.patchsets[-1]['approvals']: |
| 366 | cur = status[a['type']] |
| 367 | cat_min, cat_max = self.categories[a['type']][1:] |
| 368 | new = int(a['value']) |
| 369 | if new == cat_min: |
| 370 | cur = new |
| 371 | elif abs(new) > abs(cur): |
| 372 | cur = new |
| 373 | status[a['type']] = cur |
| 374 | |
| 375 | labels = [] |
| 376 | ok = True |
| 377 | for typ, cat in self.categories.items(): |
| 378 | cur = status[typ] |
| 379 | cat_min, cat_max = cat[1:] |
| 380 | if cur == cat_min: |
| 381 | value = 'REJECT' |
| 382 | ok = False |
| 383 | elif cur == cat_max: |
| 384 | value = 'OK' |
| 385 | else: |
| 386 | value = 'NEED' |
| 387 | ok = False |
| 388 | labels.append({'label': cat[0], 'status': value}) |
| 389 | if ok: |
| 390 | return [{'status': 'OK'}] |
| 391 | return [{'status': 'NOT_READY', |
| 392 | 'labels': labels}] |
| 393 | |
| 394 | def setDependsOn(self, other, patchset): |
| 395 | self.depends_on_change = other |
| 396 | d = {'id': other.data['id'], |
| 397 | 'number': other.data['number'], |
| 398 | 'ref': other.patchsets[patchset - 1]['ref'] |
| 399 | } |
| 400 | self.data['dependsOn'] = [d] |
| 401 | |
| 402 | other.needed_by_changes.append(self) |
| 403 | needed = other.data.get('neededBy', []) |
| 404 | d = {'id': self.data['id'], |
| 405 | 'number': self.data['number'], |
| 406 | 'ref': self.patchsets[patchset - 1]['ref'], |
| 407 | 'revision': self.patchsets[patchset - 1]['revision'] |
| 408 | } |
| 409 | needed.append(d) |
| 410 | other.data['neededBy'] = needed |
| 411 | |
| 412 | def query(self): |
| 413 | self.queried += 1 |
| 414 | d = self.data.get('dependsOn') |
| 415 | if d: |
| 416 | d = d[0] |
| 417 | if (self.depends_on_change.patchsets[-1]['ref'] == d['ref']): |
| 418 | d['isCurrentPatchSet'] = True |
| 419 | else: |
| 420 | d['isCurrentPatchSet'] = False |
| 421 | return json.loads(json.dumps(self.data)) |
| 422 | |
| 423 | def setMerged(self): |
| 424 | if (self.depends_on_change and |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 425 | self.depends_on_change.data['status'] != 'MERGED'): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 426 | return |
| 427 | if self.fail_merge: |
| 428 | return |
| 429 | self.data['status'] = 'MERGED' |
| 430 | self.open = False |
| 431 | |
| 432 | path = os.path.join(self.upstream_root, self.project) |
| 433 | repo = git.Repo(path) |
| 434 | repo.heads[self.branch].commit = \ |
| 435 | repo.commit(self.patchsets[-1]['revision']) |
| 436 | |
| 437 | def setReported(self): |
| 438 | self.reported += 1 |
| 439 | |
| 440 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 441 | class FakeGerritConnection(gerritconnection.GerritConnection): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 442 | """A Fake Gerrit connection for use in tests. |
| 443 | |
| 444 | This subclasses |
| 445 | :py:class:`~zuul.connection.gerrit.GerritConnection` to add the |
| 446 | ability for tests to add changes to the fake Gerrit it represents. |
| 447 | """ |
| 448 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 449 | log = logging.getLogger("zuul.test.FakeGerritConnection") |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 450 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 451 | def __init__(self, driver, connection_name, connection_config, |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 452 | changes_db=None, upstream_root=None): |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 453 | super(FakeGerritConnection, self).__init__(driver, connection_name, |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 454 | connection_config) |
| 455 | |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 456 | self.event_queue = Queue.Queue() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 457 | self.fixture_dir = os.path.join(FIXTURE_DIR, 'gerrit') |
| 458 | self.change_number = 0 |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 459 | self.changes = changes_db |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 460 | self.queries = [] |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 461 | self.upstream_root = upstream_root |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 462 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 463 | def addFakeChange(self, project, branch, subject, status='NEW', |
| 464 | files=None): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 465 | """Add a change to the fake Gerrit.""" |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 466 | self.change_number += 1 |
| 467 | c = FakeChange(self, self.change_number, project, branch, subject, |
| 468 | upstream_root=self.upstream_root, |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 469 | status=status, files=files) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 470 | self.changes[self.change_number] = c |
| 471 | return c |
| 472 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 473 | def review(self, project, changeid, message, action): |
| 474 | number, ps = changeid.split(',') |
| 475 | change = self.changes[int(number)] |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 476 | |
| 477 | # Add the approval back onto the change (ie simulate what gerrit would |
| 478 | # do). |
| 479 | # Usually when zuul leaves a review it'll create a feedback loop where |
| 480 | # zuul's review enters another gerrit event (which is then picked up by |
| 481 | # zuul). However, we can't mimic this behaviour (by adding this |
| 482 | # approval event into the queue) as it stops jobs from checking what |
| 483 | # happens before this event is triggered. If a job needs to see what |
| 484 | # happens they can add their own verified event into the queue. |
| 485 | # Nevertheless, we can update change with the new review in gerrit. |
| 486 | |
James E. Blair | 8b5408c | 2016-08-08 15:37:46 -0700 | [diff] [blame] | 487 | for cat in action.keys(): |
| 488 | if cat != 'submit': |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 489 | change.addApproval(cat, action[cat], username=self.user) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 490 | |
James E. Blair | 8b5408c | 2016-08-08 15:37:46 -0700 | [diff] [blame] | 491 | # TODOv3(jeblair): can this be removed? |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 492 | if 'label' in action: |
| 493 | parts = action['label'].split('=') |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 494 | change.addApproval(parts[0], parts[2], username=self.user) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 495 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 496 | change.messages.append(message) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 497 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 498 | if 'submit' in action: |
| 499 | change.setMerged() |
| 500 | if message: |
| 501 | change.setReported() |
| 502 | |
| 503 | def query(self, number): |
| 504 | change = self.changes.get(int(number)) |
| 505 | if change: |
| 506 | return change.query() |
| 507 | return {} |
| 508 | |
James E. Blair | c494d54 | 2014-08-06 09:23:52 -0700 | [diff] [blame] | 509 | def simpleQuery(self, query): |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 510 | self.log.debug("simpleQuery: %s" % query) |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 511 | self.queries.append(query) |
James E. Blair | 5ee2425 | 2014-12-30 10:12:29 -0800 | [diff] [blame] | 512 | if query.startswith('change:'): |
| 513 | # Query a specific changeid |
| 514 | changeid = query[len('change:'):] |
| 515 | l = [change.query() for change in self.changes.values() |
| 516 | if change.data['id'] == changeid] |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 517 | elif query.startswith('message:'): |
| 518 | # Query the content of a commit message |
| 519 | msg = query[len('message:'):].strip() |
| 520 | l = [change.query() for change in self.changes.values() |
| 521 | if msg in change.data['commitMessage']] |
James E. Blair | 5ee2425 | 2014-12-30 10:12:29 -0800 | [diff] [blame] | 522 | else: |
| 523 | # Query all open changes |
| 524 | l = [change.query() for change in self.changes.values()] |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 525 | return l |
James E. Blair | c494d54 | 2014-08-06 09:23:52 -0700 | [diff] [blame] | 526 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 527 | def _start_watcher_thread(self, *args, **kw): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 528 | pass |
| 529 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 530 | def getGitUrl(self, project): |
| 531 | return os.path.join(self.upstream_root, project.name) |
| 532 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 533 | |
| 534 | class BuildHistory(object): |
| 535 | def __init__(self, **kw): |
| 536 | self.__dict__.update(kw) |
| 537 | |
| 538 | def __repr__(self): |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 539 | return ("<Completed build, result: %s name: %s uuid: %s changes: %s>" % |
| 540 | (self.result, self.name, self.uuid, self.changes)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 541 | |
| 542 | |
| 543 | class FakeURLOpener(object): |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 544 | def __init__(self, upstream_root, url): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 545 | self.upstream_root = upstream_root |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 546 | self.url = url |
| 547 | |
| 548 | def read(self): |
Morgan Fainberg | 293f7f8 | 2016-05-30 14:01:22 -0700 | [diff] [blame] | 549 | res = urllib.parse.urlparse(self.url) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 550 | path = res.path |
| 551 | project = '/'.join(path.split('/')[2:-2]) |
| 552 | ret = '001e# service=git-upload-pack\n' |
| 553 | ret += ('000000a31270149696713ba7e06f1beb760f20d359c4abed HEAD\x00' |
| 554 | 'multi_ack thin-pack side-band side-band-64k ofs-delta ' |
| 555 | 'shallow no-progress include-tag multi_ack_detailed no-done\n') |
| 556 | path = os.path.join(self.upstream_root, project) |
| 557 | repo = git.Repo(path) |
| 558 | for ref in repo.refs: |
| 559 | r = ref.object.hexsha + ' ' + ref.path + '\n' |
| 560 | ret += '%04x%s' % (len(r) + 4, r) |
| 561 | ret += '0000' |
| 562 | return ret |
| 563 | |
| 564 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 565 | class FakeStatsd(threading.Thread): |
| 566 | def __init__(self): |
| 567 | threading.Thread.__init__(self) |
| 568 | self.daemon = True |
| 569 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 570 | self.sock.bind(('', 0)) |
| 571 | self.port = self.sock.getsockname()[1] |
| 572 | self.wake_read, self.wake_write = os.pipe() |
| 573 | self.stats = [] |
| 574 | |
| 575 | def run(self): |
| 576 | while True: |
| 577 | poll = select.poll() |
| 578 | poll.register(self.sock, select.POLLIN) |
| 579 | poll.register(self.wake_read, select.POLLIN) |
| 580 | ret = poll.poll() |
| 581 | for (fd, event) in ret: |
| 582 | if fd == self.sock.fileno(): |
| 583 | data = self.sock.recvfrom(1024) |
| 584 | if not data: |
| 585 | return |
| 586 | self.stats.append(data[0]) |
| 587 | if fd == self.wake_read: |
| 588 | return |
| 589 | |
| 590 | def stop(self): |
| 591 | os.write(self.wake_write, '1\n') |
| 592 | |
| 593 | |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 594 | class FakeBuild(object): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 595 | log = logging.getLogger("zuul.test") |
| 596 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 597 | def __init__(self, executor_server, job): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 598 | self.daemon = True |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 599 | self.executor_server = executor_server |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 600 | self.job = job |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 601 | self.jobdir = None |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 602 | self.uuid = job.unique |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 603 | self.parameters = json.loads(job.arguments) |
James E. Blair | 34776ee | 2016-08-25 13:53:54 -0700 | [diff] [blame] | 604 | # TODOv3(jeblair): self.node is really "the image of the node |
| 605 | # assigned". We should rename it (self.node_image?) if we |
| 606 | # keep using it like this, or we may end up exposing more of |
| 607 | # the complexity around multi-node jobs here |
| 608 | # (self.nodes[0].image?) |
| 609 | self.node = None |
| 610 | if len(self.parameters.get('nodes')) == 1: |
| 611 | self.node = self.parameters['nodes'][0]['image'] |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 612 | self.unique = self.parameters['ZUUL_UUID'] |
Jamie Lennox | d2e3733 | 2016-12-05 15:26:19 +1100 | [diff] [blame] | 613 | self.pipeline = self.parameters['ZUUL_PIPELINE'] |
| 614 | self.project = self.parameters['ZUUL_PROJECT'] |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 615 | self.name = self.parameters['job'] |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 616 | self.wait_condition = threading.Condition() |
| 617 | self.waiting = False |
| 618 | self.aborted = False |
Paul Belanger | 71d9817 | 2016-11-08 10:56:31 -0500 | [diff] [blame] | 619 | self.requeue = False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 620 | self.created = time.time() |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 621 | self.changes = None |
| 622 | if 'ZUUL_CHANGE_IDS' in self.parameters: |
| 623 | self.changes = self.parameters['ZUUL_CHANGE_IDS'] |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 624 | |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 625 | def __repr__(self): |
| 626 | waiting = '' |
| 627 | if self.waiting: |
| 628 | waiting = ' [waiting]' |
Jamie Lennox | d2e3733 | 2016-12-05 15:26:19 +1100 | [diff] [blame] | 629 | return '<FakeBuild %s:%s %s%s>' % (self.pipeline, self.name, |
| 630 | self.changes, waiting) |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 631 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 632 | def release(self): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 633 | """Release this build.""" |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 634 | self.wait_condition.acquire() |
| 635 | self.wait_condition.notify() |
| 636 | self.waiting = False |
| 637 | self.log.debug("Build %s released" % self.unique) |
| 638 | self.wait_condition.release() |
| 639 | |
| 640 | def isWaiting(self): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 641 | """Return whether this build is being held. |
| 642 | |
| 643 | :returns: Whether the build is being held. |
| 644 | :rtype: bool |
| 645 | """ |
| 646 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 647 | self.wait_condition.acquire() |
| 648 | if self.waiting: |
| 649 | ret = True |
| 650 | else: |
| 651 | ret = False |
| 652 | self.wait_condition.release() |
| 653 | return ret |
| 654 | |
| 655 | def _wait(self): |
| 656 | self.wait_condition.acquire() |
| 657 | self.waiting = True |
| 658 | self.log.debug("Build %s waiting" % self.unique) |
| 659 | self.wait_condition.wait() |
| 660 | self.wait_condition.release() |
| 661 | |
| 662 | def run(self): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 663 | self.log.debug('Running build %s' % self.unique) |
| 664 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 665 | if self.executor_server.hold_jobs_in_build: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 666 | self.log.debug('Holding build %s' % self.unique) |
| 667 | self._wait() |
| 668 | self.log.debug("Build %s continuing" % self.unique) |
| 669 | |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 670 | result = (RecordingAnsibleJob.RESULT_NORMAL, 0) # Success |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 671 | if (('ZUUL_REF' in self.parameters) and self.shouldFail()): |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 672 | result = (RecordingAnsibleJob.RESULT_NORMAL, 1) # Failure |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 673 | if self.aborted: |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 674 | result = (RecordingAnsibleJob.RESULT_ABORTED, None) |
Paul Belanger | 71d9817 | 2016-11-08 10:56:31 -0500 | [diff] [blame] | 675 | if self.requeue: |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 676 | result = (RecordingAnsibleJob.RESULT_UNREACHABLE, None) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 677 | |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 678 | return result |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 679 | |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 680 | def shouldFail(self): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 681 | changes = self.executor_server.fail_tests.get(self.name, []) |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 682 | for change in changes: |
| 683 | if self.hasChanges(change): |
| 684 | return True |
| 685 | return False |
| 686 | |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 687 | def hasChanges(self, *changes): |
| 688 | """Return whether this build has certain changes in its git repos. |
| 689 | |
| 690 | :arg FakeChange changes: One or more changes (varargs) that |
Clark Boylan | 500992b | 2017-04-03 14:28:24 -0700 | [diff] [blame] | 691 | are expected to be present (in order) in the git repository of |
| 692 | the active project. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 693 | |
| 694 | :returns: Whether the build has the indicated changes. |
| 695 | :rtype: bool |
| 696 | |
| 697 | """ |
Clint Byrum | 3343e3e | 2016-11-15 16:05:03 -0800 | [diff] [blame] | 698 | for change in changes: |
Monty Taylor | d642d85 | 2017-02-23 14:05:42 -0500 | [diff] [blame] | 699 | path = os.path.join(self.jobdir.src_root, change.project) |
Clint Byrum | 3343e3e | 2016-11-15 16:05:03 -0800 | [diff] [blame] | 700 | try: |
| 701 | repo = git.Repo(path) |
| 702 | except NoSuchPathError as e: |
| 703 | self.log.debug('%s' % e) |
| 704 | return False |
| 705 | ref = self.parameters['ZUUL_REF'] |
| 706 | repo_messages = [c.message.strip() for c in repo.iter_commits(ref)] |
| 707 | commit_message = '%s-1' % change.subject |
| 708 | self.log.debug("Checking if build %s has changes; commit_message " |
| 709 | "%s; repo_messages %s" % (self, commit_message, |
| 710 | repo_messages)) |
| 711 | if commit_message not in repo_messages: |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 712 | self.log.debug(" messages do not match") |
| 713 | return False |
| 714 | self.log.debug(" OK") |
| 715 | return True |
| 716 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 717 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 718 | class RecordingExecutorServer(zuul.executor.server.ExecutorServer): |
| 719 | """An Ansible executor to be used in tests. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 720 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 721 | :ivar bool hold_jobs_in_build: If true, when jobs are executed |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 722 | they will report that they have started but then pause until |
| 723 | released before reporting completion. This attribute may be |
| 724 | changed at any time and will take effect for subsequently |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 725 | executed builds, but previously held builds will still need to |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 726 | be explicitly released. |
| 727 | |
| 728 | """ |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 729 | def __init__(self, *args, **kw): |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 730 | self._run_ansible = kw.pop('_run_ansible', False) |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 731 | self._test_root = kw.pop('_test_root', False) |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 732 | super(RecordingExecutorServer, self).__init__(*args, **kw) |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 733 | self.hold_jobs_in_build = False |
| 734 | self.lock = threading.Lock() |
| 735 | self.running_builds = [] |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 736 | self.build_history = [] |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 737 | self.fail_tests = {} |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 738 | self.job_builds = {} |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 739 | |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 740 | def failJob(self, name, change): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 741 | """Instruct the executor to report matching builds as failures. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 742 | |
| 743 | :arg str name: The name of the job to fail. |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 744 | :arg Change change: The :py:class:`~tests.base.FakeChange` |
| 745 | instance which should cause the job to fail. This job |
| 746 | will also fail for changes depending on this change. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 747 | |
| 748 | """ |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 749 | l = self.fail_tests.get(name, []) |
| 750 | l.append(change) |
| 751 | self.fail_tests[name] = l |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 752 | |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 753 | def release(self, regex=None): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 754 | """Release a held build. |
| 755 | |
| 756 | :arg str regex: A regular expression which, if supplied, will |
| 757 | cause only builds with matching names to be released. If |
| 758 | not supplied, all builds will be released. |
| 759 | |
| 760 | """ |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 761 | builds = self.running_builds[:] |
| 762 | self.log.debug("Releasing build %s (%s)" % (regex, |
| 763 | len(self.running_builds))) |
| 764 | for build in builds: |
| 765 | if not regex or re.match(regex, build.name): |
| 766 | self.log.debug("Releasing build %s" % |
| 767 | (build.parameters['ZUUL_UUID'])) |
| 768 | build.release() |
| 769 | else: |
| 770 | self.log.debug("Not releasing build %s" % |
| 771 | (build.parameters['ZUUL_UUID'])) |
| 772 | self.log.debug("Done releasing builds %s (%s)" % |
| 773 | (regex, len(self.running_builds))) |
| 774 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 775 | def executeJob(self, job): |
James E. Blair | 34776ee | 2016-08-25 13:53:54 -0700 | [diff] [blame] | 776 | build = FakeBuild(self, job) |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 777 | job.build = build |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 778 | self.running_builds.append(build) |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 779 | self.job_builds[job.unique] = build |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 780 | args = json.loads(job.arguments) |
James E. Blair | 490cf04 | 2017-02-24 23:07:21 -0500 | [diff] [blame] | 781 | args['vars']['zuul']['_test'] = dict(test_root=self._test_root) |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 782 | job.arguments = json.dumps(args) |
Joshua Hesketh | 50c2178 | 2016-10-13 21:34:14 +1100 | [diff] [blame] | 783 | self.job_workers[job.unique] = RecordingAnsibleJob(self, job) |
| 784 | self.job_workers[job.unique].run() |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 785 | |
| 786 | def stopJob(self, job): |
| 787 | self.log.debug("handle stop") |
| 788 | parameters = json.loads(job.arguments) |
| 789 | uuid = parameters['uuid'] |
| 790 | for build in self.running_builds: |
| 791 | if build.unique == uuid: |
| 792 | build.aborted = True |
| 793 | build.release() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 794 | super(RecordingExecutorServer, self).stopJob(job) |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 795 | |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 796 | def stop(self): |
| 797 | for build in self.running_builds: |
| 798 | build.release() |
| 799 | super(RecordingExecutorServer, self).stop() |
| 800 | |
Joshua Hesketh | 50c2178 | 2016-10-13 21:34:14 +1100 | [diff] [blame] | 801 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 802 | class RecordingAnsibleJob(zuul.executor.server.AnsibleJob): |
K Jonathan Harker | ae04e4c | 2017-03-15 19:07:11 -0700 | [diff] [blame] | 803 | def doMergeChanges(self, items): |
| 804 | # Get a merger in order to update the repos involved in this job. |
| 805 | commit = super(RecordingAnsibleJob, self).doMergeChanges(items) |
| 806 | if not commit: # merge conflict |
| 807 | self.recordResult('MERGER_FAILURE') |
| 808 | return commit |
| 809 | |
| 810 | def recordResult(self, result): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 811 | build = self.executor_server.job_builds[self.job.unique] |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 812 | self.executor_server.lock.acquire() |
| 813 | self.executor_server.build_history.append( |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 814 | BuildHistory(name=build.name, result=result, changes=build.changes, |
| 815 | node=build.node, uuid=build.unique, |
K Jonathan Harker | 2c1a623 | 2017-02-21 14:34:08 -0800 | [diff] [blame] | 816 | parameters=build.parameters, jobdir=build.jobdir, |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 817 | pipeline=build.parameters['ZUUL_PIPELINE']) |
| 818 | ) |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 819 | self.executor_server.running_builds.remove(build) |
| 820 | del self.executor_server.job_builds[self.job.unique] |
| 821 | self.executor_server.lock.release() |
K Jonathan Harker | ae04e4c | 2017-03-15 19:07:11 -0700 | [diff] [blame] | 822 | |
| 823 | def runPlaybooks(self, args): |
| 824 | build = self.executor_server.job_builds[self.job.unique] |
| 825 | build.jobdir = self.jobdir |
| 826 | |
| 827 | result = super(RecordingAnsibleJob, self).runPlaybooks(args) |
| 828 | self.recordResult(result) |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 829 | return result |
| 830 | |
Monty Taylor | e6562aa | 2017-02-20 07:37:39 -0500 | [diff] [blame] | 831 | def runAnsible(self, cmd, timeout, trusted=False): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 832 | build = self.executor_server.job_builds[self.job.unique] |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 833 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 834 | if self.executor_server._run_ansible: |
Monty Taylor | c231d93 | 2017-02-03 09:57:15 -0600 | [diff] [blame] | 835 | result = super(RecordingAnsibleJob, self).runAnsible( |
Monty Taylor | e6562aa | 2017-02-20 07:37:39 -0500 | [diff] [blame] | 836 | cmd, timeout, trusted=trusted) |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 837 | else: |
| 838 | result = build.run() |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 839 | return result |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 840 | |
James E. Blair | ad8dca0 | 2017-02-21 11:48:32 -0500 | [diff] [blame] | 841 | def getHostList(self, args): |
| 842 | self.log.debug("hostlist") |
| 843 | hosts = super(RecordingAnsibleJob, self).getHostList(args) |
Paul Belanger | c5bf375 | 2017-03-16 19:38:43 -0400 | [diff] [blame] | 844 | for host in hosts: |
| 845 | host['host_vars']['ansible_connection'] = 'local' |
| 846 | |
| 847 | hosts.append(dict( |
| 848 | name='localhost', |
| 849 | host_vars=dict(ansible_connection='local'), |
| 850 | host_keys=[])) |
James E. Blair | ad8dca0 | 2017-02-21 11:48:32 -0500 | [diff] [blame] | 851 | return hosts |
| 852 | |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 853 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 854 | class FakeGearmanServer(gear.Server): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 855 | """A Gearman server for use in tests. |
| 856 | |
| 857 | :ivar bool hold_jobs_in_queue: If true, submitted jobs will be |
| 858 | added to the queue but will not be distributed to workers |
| 859 | until released. This attribute may be changed at any time and |
| 860 | will take effect for subsequently enqueued jobs, but |
| 861 | previously held jobs will still need to be explicitly |
| 862 | released. |
| 863 | |
| 864 | """ |
| 865 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 866 | def __init__(self): |
| 867 | self.hold_jobs_in_queue = False |
| 868 | super(FakeGearmanServer, self).__init__(0) |
| 869 | |
| 870 | def getJobForConnection(self, connection, peek=False): |
| 871 | for queue in [self.high_queue, self.normal_queue, self.low_queue]: |
| 872 | for job in queue: |
| 873 | if not hasattr(job, 'waiting'): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 874 | if job.name.startswith('executor:execute'): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 875 | job.waiting = self.hold_jobs_in_queue |
| 876 | else: |
| 877 | job.waiting = False |
| 878 | if job.waiting: |
| 879 | continue |
| 880 | if job.name in connection.functions: |
| 881 | if not peek: |
| 882 | queue.remove(job) |
| 883 | connection.related_jobs[job.handle] = job |
| 884 | job.worker_connection = connection |
| 885 | job.running = True |
| 886 | return job |
| 887 | return None |
| 888 | |
| 889 | def release(self, regex=None): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 890 | """Release a held job. |
| 891 | |
| 892 | :arg str regex: A regular expression which, if supplied, will |
| 893 | cause only jobs with matching names to be released. If |
| 894 | not supplied, all jobs will be released. |
| 895 | """ |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 896 | released = False |
| 897 | qlen = (len(self.high_queue) + len(self.normal_queue) + |
| 898 | len(self.low_queue)) |
| 899 | self.log.debug("releasing queued job %s (%s)" % (regex, qlen)) |
| 900 | for job in self.getQueue(): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 901 | if job.name != 'executor:execute': |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 902 | continue |
Paul Belanger | 6ab6af7 | 2016-11-06 11:32:59 -0500 | [diff] [blame] | 903 | parameters = json.loads(job.arguments) |
| 904 | if not regex or re.match(regex, parameters.get('job')): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 905 | self.log.debug("releasing queued job %s" % |
| 906 | job.unique) |
| 907 | job.waiting = False |
| 908 | released = True |
| 909 | else: |
| 910 | self.log.debug("not releasing queued job %s" % |
| 911 | job.unique) |
| 912 | if released: |
| 913 | self.wakeConnections() |
| 914 | qlen = (len(self.high_queue) + len(self.normal_queue) + |
| 915 | len(self.low_queue)) |
| 916 | self.log.debug("done releasing queued jobs %s (%s)" % (regex, qlen)) |
| 917 | |
| 918 | |
| 919 | class FakeSMTP(object): |
| 920 | log = logging.getLogger('zuul.FakeSMTP') |
| 921 | |
| 922 | def __init__(self, messages, server, port): |
| 923 | self.server = server |
| 924 | self.port = port |
| 925 | self.messages = messages |
| 926 | |
| 927 | def sendmail(self, from_email, to_email, msg): |
| 928 | self.log.info("Sending email from %s, to %s, with msg %s" % ( |
| 929 | from_email, to_email, msg)) |
| 930 | |
| 931 | headers = msg.split('\n\n', 1)[0] |
| 932 | body = msg.split('\n\n', 1)[1] |
| 933 | |
| 934 | self.messages.append(dict( |
| 935 | from_email=from_email, |
| 936 | to_email=to_email, |
| 937 | msg=msg, |
| 938 | headers=headers, |
| 939 | body=body, |
| 940 | )) |
| 941 | |
| 942 | return True |
| 943 | |
| 944 | def quit(self): |
| 945 | return True |
| 946 | |
| 947 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 948 | class FakeNodepool(object): |
| 949 | REQUEST_ROOT = '/nodepool/requests' |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 950 | NODE_ROOT = '/nodepool/nodes' |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 951 | |
| 952 | log = logging.getLogger("zuul.test.FakeNodepool") |
| 953 | |
| 954 | def __init__(self, host, port, chroot): |
| 955 | self.client = kazoo.client.KazooClient( |
| 956 | hosts='%s:%s%s' % (host, port, chroot)) |
| 957 | self.client.start() |
| 958 | self._running = True |
James E. Blair | 15be0e1 | 2017-01-03 13:45:20 -0800 | [diff] [blame] | 959 | self.paused = False |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 960 | self.thread = threading.Thread(target=self.run) |
| 961 | self.thread.daemon = True |
| 962 | self.thread.start() |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 963 | self.fail_requests = set() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 964 | |
| 965 | def stop(self): |
| 966 | self._running = False |
| 967 | self.thread.join() |
| 968 | self.client.stop() |
| 969 | self.client.close() |
| 970 | |
| 971 | def run(self): |
| 972 | while self._running: |
| 973 | self._run() |
| 974 | time.sleep(0.1) |
| 975 | |
| 976 | def _run(self): |
James E. Blair | 15be0e1 | 2017-01-03 13:45:20 -0800 | [diff] [blame] | 977 | if self.paused: |
| 978 | return |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 979 | for req in self.getNodeRequests(): |
| 980 | self.fulfillRequest(req) |
| 981 | |
| 982 | def getNodeRequests(self): |
| 983 | try: |
| 984 | reqids = self.client.get_children(self.REQUEST_ROOT) |
| 985 | except kazoo.exceptions.NoNodeError: |
| 986 | return [] |
| 987 | reqs = [] |
| 988 | for oid in sorted(reqids): |
| 989 | path = self.REQUEST_ROOT + '/' + oid |
James E. Blair | 0ef64f8 | 2017-02-02 11:25:16 -0800 | [diff] [blame] | 990 | try: |
| 991 | data, stat = self.client.get(path) |
| 992 | data = json.loads(data) |
| 993 | data['_oid'] = oid |
| 994 | reqs.append(data) |
| 995 | except kazoo.exceptions.NoNodeError: |
| 996 | pass |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 997 | return reqs |
| 998 | |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 999 | def getNodes(self): |
| 1000 | try: |
| 1001 | nodeids = self.client.get_children(self.NODE_ROOT) |
| 1002 | except kazoo.exceptions.NoNodeError: |
| 1003 | return [] |
| 1004 | nodes = [] |
| 1005 | for oid in sorted(nodeids): |
| 1006 | path = self.NODE_ROOT + '/' + oid |
| 1007 | data, stat = self.client.get(path) |
| 1008 | data = json.loads(data) |
| 1009 | data['_oid'] = oid |
| 1010 | try: |
| 1011 | lockfiles = self.client.get_children(path + '/lock') |
| 1012 | except kazoo.exceptions.NoNodeError: |
| 1013 | lockfiles = [] |
| 1014 | if lockfiles: |
| 1015 | data['_lock'] = True |
| 1016 | else: |
| 1017 | data['_lock'] = False |
| 1018 | nodes.append(data) |
| 1019 | return nodes |
| 1020 | |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1021 | def makeNode(self, request_id, node_type): |
| 1022 | now = time.time() |
| 1023 | path = '/nodepool/nodes/' |
| 1024 | data = dict(type=node_type, |
| 1025 | provider='test-provider', |
| 1026 | region='test-region', |
Paul Belanger | 30ba93a | 2017-03-16 16:28:10 -0400 | [diff] [blame] | 1027 | az='test-az', |
Monty Taylor | 56f6133 | 2017-04-11 05:38:12 -0500 | [diff] [blame] | 1028 | interface_ip='127.0.0.1', |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1029 | public_ipv4='127.0.0.1', |
| 1030 | private_ipv4=None, |
| 1031 | public_ipv6=None, |
| 1032 | allocated_to=request_id, |
| 1033 | state='ready', |
| 1034 | state_time=now, |
| 1035 | created_time=now, |
| 1036 | updated_time=now, |
| 1037 | image_id=None, |
Paul Belanger | c5bf375 | 2017-03-16 19:38:43 -0400 | [diff] [blame] | 1038 | host_keys=["fake-key1", "fake-key2"], |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1039 | executor='fake-nodepool') |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1040 | data = json.dumps(data) |
| 1041 | path = self.client.create(path, data, |
| 1042 | makepath=True, |
| 1043 | sequence=True) |
| 1044 | nodeid = path.split("/")[-1] |
| 1045 | return nodeid |
| 1046 | |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 1047 | def addFailRequest(self, request): |
| 1048 | self.fail_requests.add(request['_oid']) |
| 1049 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1050 | def fulfillRequest(self, request): |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 1051 | if request['state'] != 'requested': |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1052 | return |
| 1053 | request = request.copy() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1054 | oid = request['_oid'] |
| 1055 | del request['_oid'] |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1056 | |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 1057 | if oid in self.fail_requests: |
| 1058 | request['state'] = 'failed' |
| 1059 | else: |
| 1060 | request['state'] = 'fulfilled' |
| 1061 | nodes = [] |
| 1062 | for node in request['node_types']: |
| 1063 | nodeid = self.makeNode(oid, node) |
| 1064 | nodes.append(nodeid) |
| 1065 | request['nodes'] = nodes |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1066 | |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1067 | request['state_time'] = time.time() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1068 | path = self.REQUEST_ROOT + '/' + oid |
| 1069 | data = json.dumps(request) |
| 1070 | self.log.debug("Fulfilling node request: %s %s" % (oid, data)) |
| 1071 | self.client.set(path, data) |
| 1072 | |
| 1073 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1074 | class ChrootedKazooFixture(fixtures.Fixture): |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 1075 | def __init__(self, test_id): |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1076 | super(ChrootedKazooFixture, self).__init__() |
| 1077 | |
| 1078 | zk_host = os.environ.get('NODEPOOL_ZK_HOST', 'localhost') |
| 1079 | if ':' in zk_host: |
| 1080 | host, port = zk_host.split(':') |
| 1081 | else: |
| 1082 | host = zk_host |
| 1083 | port = None |
| 1084 | |
| 1085 | self.zookeeper_host = host |
| 1086 | |
| 1087 | if not port: |
| 1088 | self.zookeeper_port = 2181 |
| 1089 | else: |
| 1090 | self.zookeeper_port = int(port) |
| 1091 | |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 1092 | self.test_id = test_id |
| 1093 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1094 | def _setUp(self): |
| 1095 | # Make sure the test chroot paths do not conflict |
| 1096 | random_bits = ''.join(random.choice(string.ascii_lowercase + |
| 1097 | string.ascii_uppercase) |
| 1098 | for x in range(8)) |
| 1099 | |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 1100 | rand_test_path = '%s_%s_%s' % (random_bits, os.getpid(), self.test_id) |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1101 | self.zookeeper_chroot = "/nodepool_test/%s" % rand_test_path |
| 1102 | |
Clark Boylan | 7f5f1ec | 2017-04-07 17:39:56 -0700 | [diff] [blame] | 1103 | self.addCleanup(self._cleanup) |
| 1104 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1105 | # Ensure the chroot path exists and clean up any pre-existing znodes. |
| 1106 | _tmp_client = kazoo.client.KazooClient( |
| 1107 | hosts='%s:%s' % (self.zookeeper_host, self.zookeeper_port)) |
| 1108 | _tmp_client.start() |
| 1109 | |
| 1110 | if _tmp_client.exists(self.zookeeper_chroot): |
| 1111 | _tmp_client.delete(self.zookeeper_chroot, recursive=True) |
| 1112 | |
| 1113 | _tmp_client.ensure_path(self.zookeeper_chroot) |
| 1114 | _tmp_client.stop() |
| 1115 | _tmp_client.close() |
| 1116 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1117 | def _cleanup(self): |
| 1118 | '''Remove the chroot path.''' |
| 1119 | # Need a non-chroot'ed client to remove the chroot path |
| 1120 | _tmp_client = kazoo.client.KazooClient( |
| 1121 | hosts='%s:%s' % (self.zookeeper_host, self.zookeeper_port)) |
| 1122 | _tmp_client.start() |
| 1123 | _tmp_client.delete(self.zookeeper_chroot, recursive=True) |
| 1124 | _tmp_client.stop() |
Clark Boylan | 7f5f1ec | 2017-04-07 17:39:56 -0700 | [diff] [blame] | 1125 | _tmp_client.close() |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1126 | |
| 1127 | |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 1128 | class MySQLSchemaFixture(fixtures.Fixture): |
| 1129 | def setUp(self): |
| 1130 | super(MySQLSchemaFixture, self).setUp() |
| 1131 | |
| 1132 | random_bits = ''.join(random.choice(string.ascii_lowercase + |
| 1133 | string.ascii_uppercase) |
| 1134 | for x in range(8)) |
| 1135 | self.name = '%s_%s' % (random_bits, os.getpid()) |
| 1136 | self.passwd = uuid.uuid4().hex |
| 1137 | db = pymysql.connect(host="localhost", |
| 1138 | user="openstack_citest", |
| 1139 | passwd="openstack_citest", |
| 1140 | db="openstack_citest") |
| 1141 | cur = db.cursor() |
| 1142 | cur.execute("create database %s" % self.name) |
| 1143 | cur.execute( |
| 1144 | "grant all on %s.* to '%s'@'localhost' identified by '%s'" % |
| 1145 | (self.name, self.name, self.passwd)) |
| 1146 | cur.execute("flush privileges") |
| 1147 | |
| 1148 | self.dburi = 'mysql+pymysql://%s:%s@localhost/%s' % (self.name, |
| 1149 | self.passwd, |
| 1150 | self.name) |
| 1151 | self.addDetail('dburi', testtools.content.text_content(self.dburi)) |
| 1152 | self.addCleanup(self.cleanup) |
| 1153 | |
| 1154 | def cleanup(self): |
| 1155 | db = pymysql.connect(host="localhost", |
| 1156 | user="openstack_citest", |
| 1157 | passwd="openstack_citest", |
| 1158 | db="openstack_citest") |
| 1159 | cur = db.cursor() |
| 1160 | cur.execute("drop database %s" % self.name) |
| 1161 | cur.execute("drop user '%s'@'localhost'" % self.name) |
| 1162 | cur.execute("flush privileges") |
| 1163 | |
| 1164 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1165 | class BaseTestCase(testtools.TestCase): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1166 | log = logging.getLogger("zuul.test") |
James E. Blair | 267e516 | 2017-04-07 10:08:20 -0700 | [diff] [blame] | 1167 | wait_timeout = 30 |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1168 | |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1169 | def attachLogs(self, *args): |
| 1170 | def reader(): |
| 1171 | self._log_stream.seek(0) |
| 1172 | while True: |
| 1173 | x = self._log_stream.read(4096) |
| 1174 | if not x: |
| 1175 | break |
| 1176 | yield x.encode('utf8') |
| 1177 | content = testtools.content.content_from_reader( |
| 1178 | reader, |
| 1179 | testtools.content_type.UTF8_TEXT, |
| 1180 | False) |
| 1181 | self.addDetail('logging', content) |
| 1182 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1183 | def setUp(self): |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1184 | super(BaseTestCase, self).setUp() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1185 | test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) |
| 1186 | try: |
| 1187 | test_timeout = int(test_timeout) |
| 1188 | except ValueError: |
| 1189 | # If timeout value is invalid do not set a timeout. |
| 1190 | test_timeout = 0 |
| 1191 | if test_timeout > 0: |
| 1192 | self.useFixture(fixtures.Timeout(test_timeout, gentle=False)) |
| 1193 | |
| 1194 | if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or |
| 1195 | os.environ.get('OS_STDOUT_CAPTURE') == '1'): |
| 1196 | stdout = self.useFixture(fixtures.StringStream('stdout')).stream |
| 1197 | self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) |
| 1198 | if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or |
| 1199 | os.environ.get('OS_STDERR_CAPTURE') == '1'): |
| 1200 | stderr = self.useFixture(fixtures.StringStream('stderr')).stream |
| 1201 | self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) |
| 1202 | if (os.environ.get('OS_LOG_CAPTURE') == 'True' or |
| 1203 | os.environ.get('OS_LOG_CAPTURE') == '1'): |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1204 | self._log_stream = StringIO() |
| 1205 | self.addOnException(self.attachLogs) |
| 1206 | else: |
| 1207 | self._log_stream = sys.stdout |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1208 | |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1209 | handler = logging.StreamHandler(self._log_stream) |
| 1210 | formatter = logging.Formatter('%(asctime)s %(name)-32s ' |
| 1211 | '%(levelname)-8s %(message)s') |
| 1212 | handler.setFormatter(formatter) |
| 1213 | |
| 1214 | logger = logging.getLogger() |
| 1215 | logger.setLevel(logging.DEBUG) |
| 1216 | logger.addHandler(handler) |
| 1217 | |
| 1218 | # NOTE(notmorgan): Extract logging overrides for specific |
| 1219 | # libraries from the OS_LOG_DEFAULTS env and create loggers |
| 1220 | # for each. This is used to limit the output during test runs |
| 1221 | # from libraries that zuul depends on such as gear. |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1222 | log_defaults_from_env = os.environ.get( |
| 1223 | 'OS_LOG_DEFAULTS', |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1224 | 'git.cmd=INFO,kazoo.client=WARNING,gear=INFO') |
Morgan Fainberg | d34e0b4 | 2016-06-09 19:10:38 -0700 | [diff] [blame] | 1225 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1226 | if log_defaults_from_env: |
| 1227 | for default in log_defaults_from_env.split(','): |
| 1228 | try: |
| 1229 | name, level_str = default.split('=', 1) |
| 1230 | level = getattr(logging, level_str, logging.DEBUG) |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1231 | logger = logging.getLogger(name) |
| 1232 | logger.setLevel(level) |
| 1233 | logger.addHandler(handler) |
| 1234 | logger.propagate = False |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1235 | except ValueError: |
| 1236 | # NOTE(notmorgan): Invalid format of the log default, |
| 1237 | # skip and don't try and apply a logger for the |
| 1238 | # specified module |
| 1239 | pass |
Morgan Fainberg | d34e0b4 | 2016-06-09 19:10:38 -0700 | [diff] [blame] | 1240 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1241 | |
| 1242 | class ZuulTestCase(BaseTestCase): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1243 | """A test case with a functioning Zuul. |
| 1244 | |
| 1245 | The following class variables are used during test setup and can |
| 1246 | be overidden by subclasses but are effectively read-only once a |
| 1247 | test method starts running: |
| 1248 | |
| 1249 | :cvar str config_file: This points to the main zuul config file |
| 1250 | within the fixtures directory. Subclasses may override this |
| 1251 | to obtain a different behavior. |
| 1252 | |
| 1253 | :cvar str tenant_config_file: This is the tenant config file |
| 1254 | (which specifies from what git repos the configuration should |
| 1255 | be loaded). It defaults to the value specified in |
| 1256 | `config_file` but can be overidden by subclasses to obtain a |
| 1257 | different tenant/project layout while using the standard main |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1258 | configuration. See also the :py:func:`simple_layout` |
| 1259 | decorator. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1260 | |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1261 | :cvar bool create_project_keys: Indicates whether Zuul should |
| 1262 | auto-generate keys for each project, or whether the test |
| 1263 | infrastructure should insert dummy keys to save time during |
| 1264 | startup. Defaults to False. |
| 1265 | |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1266 | The following are instance variables that are useful within test |
| 1267 | methods: |
| 1268 | |
| 1269 | :ivar FakeGerritConnection fake_<connection>: |
| 1270 | A :py:class:`~tests.base.FakeGerritConnection` will be |
| 1271 | instantiated for each connection present in the config file |
| 1272 | and stored here. For instance, `fake_gerrit` will hold the |
| 1273 | FakeGerritConnection object for a connection named `gerrit`. |
| 1274 | |
| 1275 | :ivar FakeGearmanServer gearman_server: An instance of |
| 1276 | :py:class:`~tests.base.FakeGearmanServer` which is the Gearman |
| 1277 | server that all of the Zuul components in this test use to |
| 1278 | communicate with each other. |
| 1279 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1280 | :ivar RecordingExecutorServer executor_server: An instance of |
| 1281 | :py:class:`~tests.base.RecordingExecutorServer` which is the |
| 1282 | Ansible execute server used to run jobs for this test. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1283 | |
| 1284 | :ivar list builds: A list of :py:class:`~tests.base.FakeBuild` objects |
| 1285 | representing currently running builds. They are appended to |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1286 | the list in the order they are executed, and removed from this |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1287 | list upon completion. |
| 1288 | |
| 1289 | :ivar list history: A list of :py:class:`~tests.base.BuildHistory` |
| 1290 | objects representing completed builds. They are appended to |
| 1291 | the list in the order they complete. |
| 1292 | |
| 1293 | """ |
| 1294 | |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1295 | config_file = 'zuul.conf' |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1296 | run_ansible = False |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1297 | create_project_keys = False |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1298 | |
| 1299 | def _startMerger(self): |
| 1300 | self.merge_server = zuul.merger.server.MergeServer(self.config, |
| 1301 | self.connections) |
| 1302 | self.merge_server.start() |
| 1303 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1304 | def setUp(self): |
| 1305 | super(ZuulTestCase, self).setUp() |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1306 | |
| 1307 | self.setupZK() |
| 1308 | |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 1309 | if not KEEP_TEMPDIRS: |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1310 | tmp_root = self.useFixture(fixtures.TempDir( |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 1311 | rootdir=os.environ.get("ZUUL_TEST_ROOT")) |
| 1312 | ).path |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1313 | else: |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 1314 | tmp_root = tempfile.mkdtemp( |
| 1315 | dir=os.environ.get("ZUUL_TEST_ROOT", None)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1316 | self.test_root = os.path.join(tmp_root, "zuul-test") |
| 1317 | self.upstream_root = os.path.join(self.test_root, "upstream") |
Monty Taylor | d642d85 | 2017-02-23 14:05:42 -0500 | [diff] [blame] | 1318 | self.merger_src_root = os.path.join(self.test_root, "merger-git") |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1319 | self.executor_src_root = os.path.join(self.test_root, "executor-git") |
James E. Blair | ce8a213 | 2016-05-19 15:21:52 -0700 | [diff] [blame] | 1320 | self.state_root = os.path.join(self.test_root, "lib") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1321 | |
| 1322 | if os.path.exists(self.test_root): |
| 1323 | shutil.rmtree(self.test_root) |
| 1324 | os.makedirs(self.test_root) |
| 1325 | os.makedirs(self.upstream_root) |
James E. Blair | ce8a213 | 2016-05-19 15:21:52 -0700 | [diff] [blame] | 1326 | os.makedirs(self.state_root) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1327 | |
| 1328 | # Make per test copy of Configuration. |
| 1329 | self.setup_config() |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1330 | self.config.set('zuul', 'tenant_config', |
Joshua Hesketh | acccffc | 2015-03-31 23:38:17 +1100 | [diff] [blame] | 1331 | os.path.join(FIXTURE_DIR, |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1332 | self.config.get('zuul', 'tenant_config'))) |
Monty Taylor | d642d85 | 2017-02-23 14:05:42 -0500 | [diff] [blame] | 1333 | self.config.set('merger', 'git_dir', self.merger_src_root) |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1334 | self.config.set('executor', 'git_dir', self.executor_src_root) |
James E. Blair | ce8a213 | 2016-05-19 15:21:52 -0700 | [diff] [blame] | 1335 | self.config.set('zuul', 'state_dir', self.state_root) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1336 | |
| 1337 | # For each project in config: |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 1338 | # TODOv3(jeblair): remove these and replace with new git |
| 1339 | # filesystem fixtures |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1340 | self.init_repo("org/project3") |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1341 | self.init_repo("org/project4") |
James E. Blair | bce35e1 | 2014-08-21 14:31:17 -0700 | [diff] [blame] | 1342 | self.init_repo("org/project5") |
| 1343 | self.init_repo("org/project6") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1344 | self.init_repo("org/one-job-project") |
| 1345 | self.init_repo("org/nonvoting-project") |
| 1346 | self.init_repo("org/templated-project") |
| 1347 | self.init_repo("org/layered-project") |
| 1348 | self.init_repo("org/node-project") |
| 1349 | self.init_repo("org/conflict-project") |
| 1350 | self.init_repo("org/noop-project") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1351 | |
| 1352 | self.statsd = FakeStatsd() |
Ian Wienand | ff977bf | 2015-09-30 15:38:47 +1000 | [diff] [blame] | 1353 | # note, use 127.0.0.1 rather than localhost to avoid getting ipv6 |
| 1354 | # see: https://github.com/jsocol/pystatsd/issues/61 |
| 1355 | os.environ['STATSD_HOST'] = '127.0.0.1' |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1356 | os.environ['STATSD_PORT'] = str(self.statsd.port) |
| 1357 | self.statsd.start() |
| 1358 | # the statsd client object is configured in the statsd module import |
Monty Taylor | 74fa386 | 2016-06-02 07:39:49 +0300 | [diff] [blame] | 1359 | reload_module(statsd) |
| 1360 | reload_module(zuul.scheduler) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1361 | |
| 1362 | self.gearman_server = FakeGearmanServer() |
| 1363 | |
| 1364 | self.config.set('gearman', 'port', str(self.gearman_server.port)) |
James E. Blair | e47eb77 | 2017-02-02 17:19:40 -0800 | [diff] [blame] | 1365 | self.log.info("Gearman server on port %s" % |
| 1366 | (self.gearman_server.port,)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1367 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 1368 | gerritsource.GerritSource.replication_timeout = 1.5 |
| 1369 | gerritsource.GerritSource.replication_retry_interval = 0.5 |
| 1370 | gerritconnection.GerritEventConnector.delay = 0.0 |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1371 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1372 | self.sched = zuul.scheduler.Scheduler(self.config) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1373 | |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1374 | self.event_queues = [ |
| 1375 | self.sched.result_event_queue, |
James E. Blair | 646322f | 2017-01-27 15:50:34 -0800 | [diff] [blame] | 1376 | self.sched.trigger_event_queue, |
| 1377 | self.sched.management_event_queue |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1378 | ] |
| 1379 | |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 1380 | self.configure_connections() |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1381 | self.sched.registerConnections(self.connections) |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1382 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1383 | def URLOpenerFactory(*args, **kw): |
Morgan Fainberg | 293f7f8 | 2016-05-30 14:01:22 -0700 | [diff] [blame] | 1384 | if isinstance(args[0], urllib.request.Request): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1385 | return old_urlopen(*args, **kw) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1386 | return FakeURLOpener(self.upstream_root, *args, **kw) |
| 1387 | |
Morgan Fainberg | 293f7f8 | 2016-05-30 14:01:22 -0700 | [diff] [blame] | 1388 | old_urlopen = urllib.request.urlopen |
| 1389 | urllib.request.urlopen = URLOpenerFactory |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1390 | |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1391 | self._startMerger() |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1392 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1393 | self.executor_server = RecordingExecutorServer( |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 1394 | self.config, self.connections, |
James E. Blair | 854f889 | 2017-02-02 11:25:39 -0800 | [diff] [blame] | 1395 | jobdir_root=self.test_root, |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 1396 | _run_ansible=self.run_ansible, |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 1397 | _test_root=self.test_root, |
| 1398 | keep_jobdir=KEEP_TEMPDIRS) |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1399 | self.executor_server.start() |
| 1400 | self.history = self.executor_server.build_history |
| 1401 | self.builds = self.executor_server.running_builds |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1402 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1403 | self.executor_client = zuul.executor.client.ExecutorClient( |
James E. Blair | 92e953a | 2017-03-07 13:08:47 -0800 | [diff] [blame] | 1404 | self.config, self.sched) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1405 | self.merge_client = zuul.merger.client.MergeClient( |
| 1406 | self.config, self.sched) |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 1407 | self.nodepool = zuul.nodepool.Nodepool(self.sched) |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1408 | self.zk = zuul.zk.ZooKeeper() |
James E. Blair | 0d5a36e | 2017-02-21 10:53:44 -0500 | [diff] [blame] | 1409 | self.zk.connect(self.zk_config) |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1410 | |
James E. Blair | 0d5a36e | 2017-02-21 10:53:44 -0500 | [diff] [blame] | 1411 | self.fake_nodepool = FakeNodepool( |
| 1412 | self.zk_chroot_fixture.zookeeper_host, |
| 1413 | self.zk_chroot_fixture.zookeeper_port, |
| 1414 | self.zk_chroot_fixture.zookeeper_chroot) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1415 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1416 | self.sched.setExecutor(self.executor_client) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1417 | self.sched.setMerger(self.merge_client) |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 1418 | self.sched.setNodepool(self.nodepool) |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1419 | self.sched.setZooKeeper(self.zk) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1420 | |
Paul Belanger | 88ef0ea | 2015-12-23 11:57:02 -0500 | [diff] [blame] | 1421 | self.webapp = zuul.webapp.WebApp( |
| 1422 | self.sched, port=0, listen_address='127.0.0.1') |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1423 | self.rpc = zuul.rpclistener.RPCListener(self.config, self.sched) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1424 | |
| 1425 | self.sched.start() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1426 | self.webapp.start() |
| 1427 | self.rpc.start() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1428 | self.executor_client.gearman.waitForServer() |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1429 | # Cleanups are run in reverse order |
| 1430 | self.addCleanup(self.assertCleanShutdown) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1431 | self.addCleanup(self.shutdown) |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1432 | self.addCleanup(self.assertFinalState) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1433 | |
James E. Blair | b9c0d77 | 2017-03-03 14:34:49 -0800 | [diff] [blame] | 1434 | self.sched.reconfigure(self.config) |
| 1435 | self.sched.resume() |
| 1436 | |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 1437 | def configure_connections(self): |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 1438 | # Set up gerrit related fakes |
| 1439 | # Set a changes database so multiple FakeGerrit's can report back to |
| 1440 | # a virtual canonical database given by the configured hostname |
| 1441 | self.gerrit_changes_dbs = {} |
| 1442 | |
| 1443 | def getGerritConnection(driver, name, config): |
| 1444 | db = self.gerrit_changes_dbs.setdefault(config['server'], {}) |
| 1445 | con = FakeGerritConnection(driver, name, config, |
| 1446 | changes_db=db, |
| 1447 | upstream_root=self.upstream_root) |
| 1448 | self.event_queues.append(con.event_queue) |
| 1449 | setattr(self, 'fake_' + name, con) |
| 1450 | return con |
| 1451 | |
| 1452 | self.useFixture(fixtures.MonkeyPatch( |
| 1453 | 'zuul.driver.gerrit.GerritDriver.getConnection', |
| 1454 | getGerritConnection)) |
| 1455 | |
| 1456 | # Set up smtp related fakes |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 1457 | # TODO(jhesketh): This should come from lib.connections for better |
| 1458 | # coverage |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1459 | # Register connections from the config |
| 1460 | self.smtp_messages = [] |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1461 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1462 | def FakeSMTPFactory(*args, **kw): |
| 1463 | args = [self.smtp_messages] + list(args) |
| 1464 | return FakeSMTP(*args, **kw) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1465 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 1466 | self.useFixture(fixtures.MonkeyPatch('smtplib.SMTP', FakeSMTPFactory)) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1467 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 1468 | # Register connections from the config using fakes |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 1469 | self.connections = zuul.lib.connections.ConnectionRegistry() |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 1470 | self.connections.configure(self.config) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 1471 | |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1472 | def setup_config(self): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1473 | # This creates the per-test configuration object. It can be |
| 1474 | # overriden by subclasses, but should not need to be since it |
| 1475 | # obeys the config_file and tenant_config_file attributes. |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1476 | self.config = ConfigParser.ConfigParser() |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1477 | self.config.read(os.path.join(FIXTURE_DIR, self.config_file)) |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1478 | |
| 1479 | if not self.setupSimpleLayout(): |
| 1480 | if hasattr(self, 'tenant_config_file'): |
| 1481 | self.config.set('zuul', 'tenant_config', |
| 1482 | self.tenant_config_file) |
| 1483 | git_path = os.path.join( |
| 1484 | os.path.dirname( |
| 1485 | os.path.join(FIXTURE_DIR, self.tenant_config_file)), |
| 1486 | 'git') |
| 1487 | if os.path.exists(git_path): |
| 1488 | for reponame in os.listdir(git_path): |
| 1489 | project = reponame.replace('_', '/') |
| 1490 | self.copyDirToRepo(project, |
| 1491 | os.path.join(git_path, reponame)) |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1492 | self.setupAllProjectKeys() |
| 1493 | |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1494 | def setupSimpleLayout(self): |
| 1495 | # If the test method has been decorated with a simple_layout, |
| 1496 | # use that instead of the class tenant_config_file. Set up a |
| 1497 | # single config-project with the specified layout, and |
| 1498 | # initialize repos for all of the 'project' entries which |
| 1499 | # appear in the layout. |
| 1500 | test_name = self.id().split('.')[-1] |
| 1501 | test = getattr(self, test_name) |
| 1502 | if hasattr(test, '__simple_layout__'): |
| 1503 | path = getattr(test, '__simple_layout__') |
| 1504 | else: |
| 1505 | return False |
| 1506 | |
James E. Blair | b70e55a | 2017-04-19 12:57:02 -0700 | [diff] [blame^] | 1507 | files = {} |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1508 | path = os.path.join(FIXTURE_DIR, path) |
| 1509 | with open(path) as f: |
James E. Blair | b70e55a | 2017-04-19 12:57:02 -0700 | [diff] [blame^] | 1510 | data = f.read() |
| 1511 | layout = yaml.safe_load(data) |
| 1512 | files['zuul.yaml'] = data |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1513 | untrusted_projects = [] |
| 1514 | for item in layout: |
| 1515 | if 'project' in item: |
| 1516 | name = item['project']['name'] |
| 1517 | untrusted_projects.append(name) |
| 1518 | self.init_repo(name) |
| 1519 | self.addCommitToRepo(name, 'initial commit', |
| 1520 | files={'README': ''}, |
| 1521 | branch='master', tag='init') |
James E. Blair | b70e55a | 2017-04-19 12:57:02 -0700 | [diff] [blame^] | 1522 | if 'job' in item: |
| 1523 | jobname = item['job']['name'] |
| 1524 | files['playbooks/%s.yaml' % jobname] = '' |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1525 | |
| 1526 | root = os.path.join(self.test_root, "config") |
| 1527 | if not os.path.exists(root): |
| 1528 | os.makedirs(root) |
| 1529 | f = tempfile.NamedTemporaryFile(dir=root, delete=False) |
| 1530 | config = [{'tenant': |
| 1531 | {'name': 'tenant-one', |
| 1532 | 'source': {'gerrit': |
| 1533 | {'config-projects': ['common-config'], |
| 1534 | 'untrusted-projects': untrusted_projects}}}}] |
| 1535 | f.write(yaml.dump(config)) |
| 1536 | f.close() |
| 1537 | self.config.set('zuul', 'tenant_config', |
| 1538 | os.path.join(FIXTURE_DIR, f.name)) |
| 1539 | |
| 1540 | self.init_repo('common-config') |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1541 | self.addCommitToRepo('common-config', 'add content from fixture', |
| 1542 | files, branch='master', tag='init') |
| 1543 | |
| 1544 | return True |
| 1545 | |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1546 | def setupAllProjectKeys(self): |
| 1547 | if self.create_project_keys: |
| 1548 | return |
| 1549 | |
| 1550 | path = self.config.get('zuul', 'tenant_config') |
| 1551 | with open(os.path.join(FIXTURE_DIR, path)) as f: |
| 1552 | tenant_config = yaml.safe_load(f.read()) |
| 1553 | for tenant in tenant_config: |
| 1554 | sources = tenant['tenant']['source'] |
| 1555 | for source, conf in sources.items(): |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 1556 | for project in conf.get('config-projects', []): |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1557 | self.setupProjectKeys(source, project) |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 1558 | for project in conf.get('untrusted-projects', []): |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1559 | self.setupProjectKeys(source, project) |
| 1560 | |
| 1561 | def setupProjectKeys(self, source, project): |
| 1562 | # Make sure we set up an RSA key for the project so that we |
| 1563 | # don't spend time generating one: |
| 1564 | |
| 1565 | key_root = os.path.join(self.state_root, 'keys') |
| 1566 | if not os.path.isdir(key_root): |
| 1567 | os.mkdir(key_root, 0o700) |
| 1568 | private_key_file = os.path.join(key_root, source, project + '.pem') |
| 1569 | private_key_dir = os.path.dirname(private_key_file) |
| 1570 | self.log.debug("Installing test keys for project %s at %s" % ( |
| 1571 | project, private_key_file)) |
| 1572 | if not os.path.isdir(private_key_dir): |
| 1573 | os.makedirs(private_key_dir) |
| 1574 | with open(os.path.join(FIXTURE_DIR, 'private.pem')) as i: |
| 1575 | with open(private_key_file, 'w') as o: |
| 1576 | o.write(i.read()) |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1577 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1578 | def setupZK(self): |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 1579 | self.zk_chroot_fixture = self.useFixture( |
| 1580 | ChrootedKazooFixture(self.id())) |
James E. Blair | 0d5a36e | 2017-02-21 10:53:44 -0500 | [diff] [blame] | 1581 | self.zk_config = '%s:%s%s' % ( |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1582 | self.zk_chroot_fixture.zookeeper_host, |
| 1583 | self.zk_chroot_fixture.zookeeper_port, |
| 1584 | self.zk_chroot_fixture.zookeeper_chroot) |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1585 | |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1586 | def copyDirToRepo(self, project, source_path): |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 1587 | self.init_repo(project) |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1588 | |
| 1589 | files = {} |
| 1590 | for (dirpath, dirnames, filenames) in os.walk(source_path): |
| 1591 | for filename in filenames: |
| 1592 | test_tree_filepath = os.path.join(dirpath, filename) |
| 1593 | common_path = os.path.commonprefix([test_tree_filepath, |
| 1594 | source_path]) |
| 1595 | relative_filepath = test_tree_filepath[len(common_path) + 1:] |
| 1596 | with open(test_tree_filepath, 'r') as f: |
| 1597 | content = f.read() |
| 1598 | files[relative_filepath] = content |
| 1599 | self.addCommitToRepo(project, 'add content from fixture', |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 1600 | files, branch='master', tag='init') |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1601 | |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 1602 | def assertNodepoolState(self): |
| 1603 | # Make sure that there are no pending requests |
| 1604 | |
| 1605 | requests = self.fake_nodepool.getNodeRequests() |
| 1606 | self.assertEqual(len(requests), 0) |
| 1607 | |
| 1608 | nodes = self.fake_nodepool.getNodes() |
| 1609 | for node in nodes: |
| 1610 | self.assertFalse(node['_lock'], "Node %s is locked" % |
| 1611 | (node['_oid'],)) |
| 1612 | |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1613 | def assertNoGeneratedKeys(self): |
| 1614 | # Make sure that Zuul did not generate any project keys |
| 1615 | # (unless it was supposed to). |
| 1616 | |
| 1617 | if self.create_project_keys: |
| 1618 | return |
| 1619 | |
| 1620 | with open(os.path.join(FIXTURE_DIR, 'private.pem')) as i: |
| 1621 | test_key = i.read() |
| 1622 | |
| 1623 | key_root = os.path.join(self.state_root, 'keys') |
| 1624 | for root, dirname, files in os.walk(key_root): |
| 1625 | for fn in files: |
| 1626 | with open(os.path.join(root, fn)) as f: |
| 1627 | self.assertEqual(test_key, f.read()) |
| 1628 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1629 | def assertFinalState(self): |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1630 | self.log.debug("Assert final state") |
| 1631 | # Make sure no jobs are running |
| 1632 | self.assertEqual({}, self.executor_server.job_workers) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1633 | # Make sure that git.Repo objects have been garbage collected. |
| 1634 | repos = [] |
| 1635 | gc.collect() |
| 1636 | for obj in gc.get_objects(): |
| 1637 | if isinstance(obj, git.Repo): |
James E. Blair | c43525f | 2017-03-03 11:10:26 -0800 | [diff] [blame] | 1638 | self.log.debug("Leaked git repo object: %s" % repr(obj)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1639 | repos.append(obj) |
| 1640 | self.assertEqual(len(repos), 0) |
| 1641 | self.assertEmptyQueues() |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 1642 | self.assertNodepoolState() |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1643 | self.assertNoGeneratedKeys() |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1644 | ipm = zuul.manager.independent.IndependentPipelineManager |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1645 | for tenant in self.sched.abide.tenants.values(): |
| 1646 | for pipeline in tenant.layout.pipelines.values(): |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 1647 | if isinstance(pipeline.manager, ipm): |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1648 | self.assertEqual(len(pipeline.queues), 0) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1649 | |
| 1650 | def shutdown(self): |
| 1651 | self.log.debug("Shutting down after tests") |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1652 | self.executor_client.stop() |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1653 | self.merge_server.stop() |
| 1654 | self.merge_server.join() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1655 | self.merge_client.stop() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1656 | self.executor_server.stop() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1657 | self.sched.stop() |
| 1658 | self.sched.join() |
| 1659 | self.statsd.stop() |
| 1660 | self.statsd.join() |
| 1661 | self.webapp.stop() |
| 1662 | self.webapp.join() |
| 1663 | self.rpc.stop() |
| 1664 | self.rpc.join() |
| 1665 | self.gearman_server.shutdown() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1666 | self.fake_nodepool.stop() |
| 1667 | self.zk.disconnect() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1668 | threads = threading.enumerate() |
| 1669 | if len(threads) > 1: |
| 1670 | self.log.error("More than one thread is running: %s" % threads) |
James E. Blair | 6ac368c | 2016-12-22 18:07:20 -0800 | [diff] [blame] | 1671 | self.printHistory() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1672 | |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1673 | def assertCleanShutdown(self): |
| 1674 | pass |
| 1675 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1676 | def init_repo(self, project): |
| 1677 | parts = project.split('/') |
| 1678 | path = os.path.join(self.upstream_root, *parts[:-1]) |
| 1679 | if not os.path.exists(path): |
| 1680 | os.makedirs(path) |
| 1681 | path = os.path.join(self.upstream_root, project) |
| 1682 | repo = git.Repo.init(path) |
| 1683 | |
Morgan Fainberg | 78c301a | 2016-07-14 13:47:01 -0700 | [diff] [blame] | 1684 | with repo.config_writer() as config_writer: |
| 1685 | config_writer.set_value('user', 'email', 'user@example.com') |
| 1686 | config_writer.set_value('user', 'name', 'User Name') |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1687 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1688 | repo.index.commit('initial commit') |
| 1689 | master = repo.create_head('master') |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1690 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1691 | repo.head.reference = master |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 1692 | zuul.merger.merger.reset_repo_to_head(repo) |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1693 | repo.git.clean('-x', '-f', '-d') |
| 1694 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1695 | def create_branch(self, project, branch): |
| 1696 | path = os.path.join(self.upstream_root, project) |
| 1697 | repo = git.Repo.init(path) |
| 1698 | fn = os.path.join(path, 'README') |
| 1699 | |
| 1700 | branch_head = repo.create_head(branch) |
| 1701 | repo.head.reference = branch_head |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1702 | f = open(fn, 'a') |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1703 | f.write("test %s\n" % branch) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1704 | f.close() |
| 1705 | repo.index.add([fn]) |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1706 | repo.index.commit('%s commit' % branch) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1707 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 1708 | repo.head.reference = repo.heads['master'] |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 1709 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1710 | repo.git.clean('-x', '-f', '-d') |
| 1711 | |
Sachi King | 9f16d52 | 2016-03-16 12:20:45 +1100 | [diff] [blame] | 1712 | def create_commit(self, project): |
| 1713 | path = os.path.join(self.upstream_root, project) |
| 1714 | repo = git.Repo(path) |
| 1715 | repo.head.reference = repo.heads['master'] |
| 1716 | file_name = os.path.join(path, 'README') |
| 1717 | with open(file_name, 'a') as f: |
| 1718 | f.write('creating fake commit\n') |
| 1719 | repo.index.add([file_name]) |
| 1720 | commit = repo.index.commit('Creating a fake commit') |
| 1721 | return commit.hexsha |
| 1722 | |
James E. Blair | f4a5f02 | 2017-04-18 14:01:10 -0700 | [diff] [blame] | 1723 | def orderedRelease(self, count=None): |
James E. Blair | b8c1647 | 2015-05-05 14:55:26 -0700 | [diff] [blame] | 1724 | # Run one build at a time to ensure non-race order: |
James E. Blair | f4a5f02 | 2017-04-18 14:01:10 -0700 | [diff] [blame] | 1725 | i = 0 |
James E. Blair | b8c1647 | 2015-05-05 14:55:26 -0700 | [diff] [blame] | 1726 | while len(self.builds): |
| 1727 | self.release(self.builds[0]) |
| 1728 | self.waitUntilSettled() |
James E. Blair | f4a5f02 | 2017-04-18 14:01:10 -0700 | [diff] [blame] | 1729 | i += 1 |
| 1730 | if count is not None and i >= count: |
| 1731 | break |
James E. Blair | b8c1647 | 2015-05-05 14:55:26 -0700 | [diff] [blame] | 1732 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1733 | def release(self, job): |
| 1734 | if isinstance(job, FakeBuild): |
| 1735 | job.release() |
| 1736 | else: |
| 1737 | job.waiting = False |
| 1738 | self.log.debug("Queued job %s released" % job.unique) |
| 1739 | self.gearman_server.wakeConnections() |
| 1740 | |
| 1741 | def getParameter(self, job, name): |
| 1742 | if isinstance(job, FakeBuild): |
| 1743 | return job.parameters[name] |
| 1744 | else: |
| 1745 | parameters = json.loads(job.arguments) |
| 1746 | return parameters[name] |
| 1747 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1748 | def haveAllBuildsReported(self): |
| 1749 | # See if Zuul is waiting on a meta job to complete |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1750 | if self.executor_client.meta_jobs: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1751 | return False |
| 1752 | # Find out if every build that the worker has completed has been |
| 1753 | # reported back to Zuul. If it hasn't then that means a Gearman |
| 1754 | # event is still in transit and the system is not stable. |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1755 | for build in self.history: |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1756 | zbuild = self.executor_client.builds.get(build.uuid) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1757 | if not zbuild: |
| 1758 | # It has already been reported |
| 1759 | continue |
| 1760 | # It hasn't been reported yet. |
| 1761 | return False |
| 1762 | # Make sure that none of the worker connections are in GRAB_WAIT |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1763 | for connection in self.executor_server.worker.active_connections: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1764 | if connection.state == 'GRAB_WAIT': |
| 1765 | return False |
| 1766 | return True |
| 1767 | |
| 1768 | def areAllBuildsWaiting(self): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1769 | builds = self.executor_client.builds.values() |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1770 | seen_builds = set() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1771 | for build in builds: |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1772 | seen_builds.add(build.uuid) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1773 | client_job = None |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1774 | for conn in self.executor_client.gearman.active_connections: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1775 | for j in conn.related_jobs.values(): |
| 1776 | if j.unique == build.uuid: |
| 1777 | client_job = j |
| 1778 | break |
| 1779 | if not client_job: |
| 1780 | self.log.debug("%s is not known to the gearman client" % |
| 1781 | build) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1782 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1783 | if not client_job.handle: |
| 1784 | self.log.debug("%s has no handle" % client_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1785 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1786 | server_job = self.gearman_server.jobs.get(client_job.handle) |
| 1787 | if not server_job: |
| 1788 | self.log.debug("%s is not known to the gearman server" % |
| 1789 | client_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1790 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1791 | if not hasattr(server_job, 'waiting'): |
| 1792 | self.log.debug("%s is being enqueued" % server_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1793 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1794 | if server_job.waiting: |
| 1795 | continue |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 1796 | if build.url is None: |
James E. Blair | bbda470 | 2016-03-09 15:19:56 -0800 | [diff] [blame] | 1797 | self.log.debug("%s has not reported start" % build) |
| 1798 | return False |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1799 | worker_build = self.executor_server.job_builds.get( |
| 1800 | server_job.unique) |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 1801 | if worker_build: |
| 1802 | if worker_build.isWaiting(): |
| 1803 | continue |
| 1804 | else: |
| 1805 | self.log.debug("%s is running" % worker_build) |
| 1806 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1807 | else: |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 1808 | self.log.debug("%s is unassigned" % server_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1809 | return False |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1810 | for (build_uuid, job_worker) in \ |
| 1811 | self.executor_server.job_workers.items(): |
| 1812 | if build_uuid not in seen_builds: |
| 1813 | self.log.debug("%s is not finalized" % build_uuid) |
| 1814 | return False |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 1815 | return True |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1816 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1817 | def areAllNodeRequestsComplete(self): |
James E. Blair | 15be0e1 | 2017-01-03 13:45:20 -0800 | [diff] [blame] | 1818 | if self.fake_nodepool.paused: |
| 1819 | return True |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1820 | if self.sched.nodepool.requests: |
| 1821 | return False |
| 1822 | return True |
| 1823 | |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1824 | def eventQueuesEmpty(self): |
| 1825 | for queue in self.event_queues: |
| 1826 | yield queue.empty() |
| 1827 | |
| 1828 | def eventQueuesJoin(self): |
| 1829 | for queue in self.event_queues: |
| 1830 | queue.join() |
| 1831 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1832 | def waitUntilSettled(self): |
| 1833 | self.log.debug("Waiting until settled...") |
| 1834 | start = time.time() |
| 1835 | while True: |
Clint Byrum | a962657 | 2017-02-22 14:04:00 -0500 | [diff] [blame] | 1836 | if time.time() - start > self.wait_timeout: |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 1837 | self.log.error("Timeout waiting for Zuul to settle") |
| 1838 | self.log.error("Queue status:") |
James E. Blair | 622c968 | 2016-06-09 08:14:53 -0700 | [diff] [blame] | 1839 | for queue in self.event_queues: |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 1840 | self.log.error(" %s: %s" % (queue, queue.empty())) |
| 1841 | self.log.error("All builds waiting: %s" % |
James E. Blair | 622c968 | 2016-06-09 08:14:53 -0700 | [diff] [blame] | 1842 | (self.areAllBuildsWaiting(),)) |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 1843 | self.log.error("All builds reported: %s" % |
James E. Blair | f3156c9 | 2016-08-10 15:32:19 -0700 | [diff] [blame] | 1844 | (self.haveAllBuildsReported(),)) |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 1845 | self.log.error("All requests completed: %s" % |
| 1846 | (self.areAllNodeRequestsComplete(),)) |
| 1847 | self.log.error("Merge client jobs: %s" % |
| 1848 | (self.merge_client.jobs,)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1849 | raise Exception("Timeout waiting for Zuul to settle") |
| 1850 | # Make sure no new events show up while we're checking |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1851 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1852 | self.executor_server.lock.acquire() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1853 | # have all build states propogated to zuul? |
| 1854 | if self.haveAllBuildsReported(): |
| 1855 | # Join ensures that the queue is empty _and_ events have been |
| 1856 | # processed |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 1857 | self.eventQueuesJoin() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1858 | self.sched.run_handler_lock.acquire() |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 1859 | if (not self.merge_client.jobs and |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1860 | self.haveAllBuildsReported() and |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1861 | self.areAllBuildsWaiting() and |
James E. Blair | 36c611a | 2017-02-06 15:59:43 -0800 | [diff] [blame] | 1862 | self.areAllNodeRequestsComplete() and |
| 1863 | all(self.eventQueuesEmpty())): |
| 1864 | # The queue empty check is placed at the end to |
| 1865 | # ensure that if a component adds an event between |
| 1866 | # when locked the run handler and checked that the |
| 1867 | # components were stable, we don't erroneously |
| 1868 | # report that we are settled. |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1869 | self.sched.run_handler_lock.release() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1870 | self.executor_server.lock.release() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1871 | self.log.debug("...settled.") |
| 1872 | return |
| 1873 | self.sched.run_handler_lock.release() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1874 | self.executor_server.lock.release() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1875 | self.sched.wake_event.wait(0.1) |
| 1876 | |
| 1877 | def countJobResults(self, jobs, result): |
| 1878 | jobs = filter(lambda x: x.result == result, jobs) |
| 1879 | return len(jobs) |
| 1880 | |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 1881 | def getJobFromHistory(self, name, project=None): |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1882 | for job in self.history: |
| 1883 | if (job.name == name and |
| 1884 | (project is None or |
| 1885 | job.parameters['ZUUL_PROJECT'] == project)): |
| 1886 | return job |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1887 | raise Exception("Unable to find job %s in history" % name) |
| 1888 | |
| 1889 | def assertEmptyQueues(self): |
| 1890 | # Make sure there are no orphaned jobs |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1891 | for tenant in self.sched.abide.tenants.values(): |
| 1892 | for pipeline in tenant.layout.pipelines.values(): |
| 1893 | for queue in pipeline.queues: |
| 1894 | if len(queue.queue) != 0: |
Joshua Hesketh | 0aa7e8b | 2016-07-14 00:12:25 +1000 | [diff] [blame] | 1895 | print('pipeline %s queue %s contents %s' % ( |
| 1896 | pipeline.name, queue.name, queue.queue)) |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1897 | self.assertEqual(len(queue.queue), 0, |
| 1898 | "Pipelines queues should be empty") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1899 | |
| 1900 | def assertReportedStat(self, key, value=None, kind=None): |
| 1901 | start = time.time() |
| 1902 | while time.time() < (start + 5): |
| 1903 | for stat in self.statsd.stats: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1904 | k, v = stat.split(':') |
| 1905 | if key == k: |
| 1906 | if value is None and kind is None: |
| 1907 | return |
| 1908 | elif value: |
| 1909 | if value == v: |
| 1910 | return |
| 1911 | elif kind: |
| 1912 | if v.endswith('|' + kind): |
| 1913 | return |
| 1914 | time.sleep(0.1) |
| 1915 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1916 | raise Exception("Key %s not found in reported stats" % key) |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 1917 | |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 1918 | def assertBuilds(self, builds): |
| 1919 | """Assert that the running builds are as described. |
| 1920 | |
| 1921 | The list of running builds is examined and must match exactly |
| 1922 | the list of builds described by the input. |
| 1923 | |
| 1924 | :arg list builds: A list of dictionaries. Each item in the |
| 1925 | list must match the corresponding build in the build |
| 1926 | history, and each element of the dictionary must match the |
| 1927 | corresponding attribute of the build. |
| 1928 | |
| 1929 | """ |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 1930 | try: |
| 1931 | self.assertEqual(len(self.builds), len(builds)) |
| 1932 | for i, d in enumerate(builds): |
| 1933 | for k, v in d.items(): |
| 1934 | self.assertEqual( |
| 1935 | getattr(self.builds[i], k), v, |
| 1936 | "Element %i in builds does not match" % (i,)) |
| 1937 | except Exception: |
| 1938 | for build in self.builds: |
| 1939 | self.log.error("Running build: %s" % build) |
| 1940 | else: |
| 1941 | self.log.error("No running builds") |
| 1942 | raise |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 1943 | |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 1944 | def assertHistory(self, history, ordered=True): |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 1945 | """Assert that the completed builds are as described. |
| 1946 | |
| 1947 | The list of completed builds is examined and must match |
| 1948 | exactly the list of builds described by the input. |
| 1949 | |
| 1950 | :arg list history: A list of dictionaries. Each item in the |
| 1951 | list must match the corresponding build in the build |
| 1952 | history, and each element of the dictionary must match the |
| 1953 | corresponding attribute of the build. |
| 1954 | |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 1955 | :arg bool ordered: If true, the history must match the order |
| 1956 | supplied, if false, the builds are permitted to have |
| 1957 | arrived in any order. |
| 1958 | |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 1959 | """ |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 1960 | def matches(history_item, item): |
| 1961 | for k, v in item.items(): |
| 1962 | if getattr(history_item, k) != v: |
| 1963 | return False |
| 1964 | return True |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 1965 | try: |
| 1966 | self.assertEqual(len(self.history), len(history)) |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 1967 | if ordered: |
| 1968 | for i, d in enumerate(history): |
| 1969 | if not matches(self.history[i], d): |
| 1970 | raise Exception( |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 1971 | "Element %i in history does not match %s" % |
| 1972 | (i, self.history[i])) |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 1973 | else: |
| 1974 | unseen = self.history[:] |
| 1975 | for i, d in enumerate(history): |
| 1976 | found = False |
| 1977 | for unseen_item in unseen: |
| 1978 | if matches(unseen_item, d): |
| 1979 | found = True |
| 1980 | unseen.remove(unseen_item) |
| 1981 | break |
| 1982 | if not found: |
| 1983 | raise Exception("No match found for element %i " |
| 1984 | "in history" % (i,)) |
| 1985 | if unseen: |
| 1986 | raise Exception("Unexpected items in history") |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 1987 | except Exception: |
| 1988 | for build in self.history: |
| 1989 | self.log.error("Completed build: %s" % build) |
| 1990 | else: |
| 1991 | self.log.error("No completed builds") |
| 1992 | raise |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 1993 | |
James E. Blair | 6ac368c | 2016-12-22 18:07:20 -0800 | [diff] [blame] | 1994 | def printHistory(self): |
| 1995 | """Log the build history. |
| 1996 | |
| 1997 | This can be useful during tests to summarize what jobs have |
| 1998 | completed. |
| 1999 | |
| 2000 | """ |
| 2001 | self.log.debug("Build history:") |
| 2002 | for build in self.history: |
| 2003 | self.log.debug(build) |
| 2004 | |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 2005 | def getPipeline(self, name): |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2006 | return self.sched.abide.tenants.values()[0].layout.pipelines.get(name) |
| 2007 | |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2008 | def updateConfigLayout(self, path, untrusted_projects=None): |
| 2009 | if untrusted_projects is None: |
| 2010 | untrusted_projects = [] |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2011 | root = os.path.join(self.test_root, "config") |
Clint Byrum | ead6c56 | 2017-02-01 16:34:04 -0800 | [diff] [blame] | 2012 | if not os.path.exists(root): |
| 2013 | os.makedirs(root) |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2014 | f = tempfile.NamedTemporaryFile(dir=root, delete=False) |
| 2015 | f.write(""" |
Paul Belanger | 66e9596 | 2016-11-11 12:11:06 -0500 | [diff] [blame] | 2016 | - tenant: |
| 2017 | name: openstack |
| 2018 | source: |
| 2019 | gerrit: |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2020 | config-projects: |
Paul Belanger | 66e9596 | 2016-11-11 12:11:06 -0500 | [diff] [blame] | 2021 | - %s |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2022 | untrusted-projects: |
James E. Blair | 0ffa010 | 2017-03-30 13:11:33 -0700 | [diff] [blame] | 2023 | - org/project |
| 2024 | - org/project1 |
| 2025 | - org/project2 |
| 2026 | - org/project3 |
| 2027 | - org/project4 |
| 2028 | - org/project5 |
| 2029 | - org/project6 |
| 2030 | - org/one-job-project |
| 2031 | - org/nonvoting-project |
| 2032 | - org/templated-project |
| 2033 | - org/layered-project |
| 2034 | - org/node-project |
| 2035 | - org/conflict-project |
James E. Blair | b70e55a | 2017-04-19 12:57:02 -0700 | [diff] [blame^] | 2036 | - org/noop-project\n""" % path) |
James E. Blair | 0ffa010 | 2017-03-30 13:11:33 -0700 | [diff] [blame] | 2037 | |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2038 | for repo in untrusted_projects: |
James E. Blair | 0ffa010 | 2017-03-30 13:11:33 -0700 | [diff] [blame] | 2039 | f.write(" - %s\n" % repo) |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2040 | f.close() |
Paul Belanger | 66e9596 | 2016-11-11 12:11:06 -0500 | [diff] [blame] | 2041 | self.config.set('zuul', 'tenant_config', |
| 2042 | os.path.join(FIXTURE_DIR, f.name)) |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2043 | self.setupAllProjectKeys() |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2044 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 2045 | def addCommitToRepo(self, project, message, files, |
| 2046 | branch='master', tag=None): |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2047 | path = os.path.join(self.upstream_root, project) |
| 2048 | repo = git.Repo(path) |
| 2049 | repo.head.reference = branch |
| 2050 | zuul.merger.merger.reset_repo_to_head(repo) |
| 2051 | for fn, content in files.items(): |
| 2052 | fn = os.path.join(path, fn) |
James E. Blair | c73c73a | 2017-01-20 15:15:15 -0800 | [diff] [blame] | 2053 | try: |
| 2054 | os.makedirs(os.path.dirname(fn)) |
| 2055 | except OSError: |
| 2056 | pass |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2057 | with open(fn, 'w') as f: |
| 2058 | f.write(content) |
| 2059 | repo.index.add([fn]) |
| 2060 | commit = repo.index.commit(message) |
Clint Byrum | 58264dc | 2017-02-07 21:21:22 -0800 | [diff] [blame] | 2061 | before = repo.heads[branch].commit |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2062 | repo.heads[branch].commit = commit |
| 2063 | repo.head.reference = branch |
| 2064 | repo.git.clean('-x', '-f', '-d') |
| 2065 | repo.heads[branch].checkout() |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 2066 | if tag: |
| 2067 | repo.create_tag(tag) |
Clint Byrum | 58264dc | 2017-02-07 21:21:22 -0800 | [diff] [blame] | 2068 | return before |
| 2069 | |
| 2070 | def commitLayoutUpdate(self, orig_name, source_name): |
| 2071 | source_path = os.path.join(self.test_root, 'upstream', |
Clint Byrum | 678e2c3 | 2017-03-16 16:27:21 -0700 | [diff] [blame] | 2072 | source_name) |
| 2073 | to_copy = ['zuul.yaml'] |
| 2074 | for playbook in os.listdir(os.path.join(source_path, 'playbooks')): |
| 2075 | to_copy.append('playbooks/{}'.format(playbook)) |
| 2076 | commit_data = {} |
| 2077 | for source_file in to_copy: |
| 2078 | source_file_path = os.path.join(source_path, source_file) |
| 2079 | with open(source_file_path, 'r') as nt: |
| 2080 | commit_data[source_file] = nt.read() |
| 2081 | before = self.addCommitToRepo( |
| 2082 | orig_name, 'Pulling content from %s' % source_name, |
| 2083 | commit_data) |
Clint Byrum | 58264dc | 2017-02-07 21:21:22 -0800 | [diff] [blame] | 2084 | return before |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2085 | |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 2086 | def addEvent(self, connection, event): |
| 2087 | """Inject a Fake (Gerrit) event. |
| 2088 | |
| 2089 | This method accepts a JSON-encoded event and simulates Zuul |
| 2090 | having received it from Gerrit. It could (and should) |
| 2091 | eventually apply to any connection type, but is currently only |
| 2092 | used with Gerrit connections. The name of the connection is |
| 2093 | used to look up the corresponding server, and the event is |
| 2094 | simulated as having been received by all Zuul connections |
| 2095 | attached to that server. So if two Gerrit connections in Zuul |
| 2096 | are connected to the same Gerrit server, and you invoke this |
| 2097 | method specifying the name of one of them, the event will be |
| 2098 | received by both. |
| 2099 | |
| 2100 | .. note:: |
| 2101 | |
| 2102 | "self.fake_gerrit.addEvent" calls should be migrated to |
| 2103 | this method. |
| 2104 | |
| 2105 | :arg str connection: The name of the connection corresponding |
Clark Boylan | 500992b | 2017-04-03 14:28:24 -0700 | [diff] [blame] | 2106 | to the gerrit server. |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 2107 | :arg str event: The JSON-encoded event. |
| 2108 | |
| 2109 | """ |
| 2110 | specified_conn = self.connections.connections[connection] |
| 2111 | for conn in self.connections.connections.values(): |
| 2112 | if (isinstance(conn, specified_conn.__class__) and |
| 2113 | specified_conn.server == conn.server): |
| 2114 | conn.addEvent(event) |
| 2115 | |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2116 | |
| 2117 | class AnsibleZuulTestCase(ZuulTestCase): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2118 | """ZuulTestCase but with an actual ansible executor running""" |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 2119 | run_ansible = True |
Joshua Hesketh | 25695cb | 2017-03-06 12:50:04 +1100 | [diff] [blame] | 2120 | |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 2121 | |
| 2122 | class ZuulDBTestCase(ZuulTestCase): |
James E. Blair | 8284489 | 2017-03-06 10:55:26 -0800 | [diff] [blame] | 2123 | def setup_config(self): |
| 2124 | super(ZuulDBTestCase, self).setup_config() |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 2125 | for section_name in self.config.sections(): |
| 2126 | con_match = re.match(r'^connection ([\'\"]?)(.*)(\1)$', |
| 2127 | section_name, re.I) |
| 2128 | if not con_match: |
| 2129 | continue |
| 2130 | |
| 2131 | if self.config.get(section_name, 'driver') == 'sql': |
| 2132 | f = MySQLSchemaFixture() |
| 2133 | self.useFixture(f) |
| 2134 | if (self.config.get(section_name, 'dburi') == |
| 2135 | '$MYSQL_FIXTURE_DBURI$'): |
| 2136 | self.config.set(section_name, 'dburi', f.dburi) |