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 | |
Monty Taylor | 4a781a7 | 2017-07-25 07:28:04 -0400 | [diff] [blame] | 18 | import asyncio |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 19 | import configparser |
Jamie Lennox | 7655b55 | 2017-03-17 12:33:38 +1100 | [diff] [blame] | 20 | from contextlib import contextmanager |
Adam Gandelman | d81dd76 | 2017-02-09 15:15:49 -0800 | [diff] [blame] | 21 | import datetime |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 22 | import gc |
| 23 | import hashlib |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 24 | from io import StringIO |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 25 | import json |
| 26 | import logging |
| 27 | import os |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 28 | import queue |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 29 | import random |
| 30 | import re |
| 31 | import select |
| 32 | import shutil |
| 33 | import socket |
| 34 | import string |
| 35 | import subprocess |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 36 | import sys |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 37 | import tempfile |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 38 | import threading |
Clark Boylan | 8208c19 | 2017-04-24 18:08:08 -0700 | [diff] [blame] | 39 | import traceback |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 40 | import time |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 41 | import uuid |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 42 | import urllib |
Monty Taylor | 4a781a7 | 2017-07-25 07:28:04 -0400 | [diff] [blame] | 43 | import socketserver |
| 44 | import http.server |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 45 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 46 | import git |
| 47 | import gear |
| 48 | import fixtures |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 49 | import kazoo.client |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 50 | import kazoo.exceptions |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 51 | import pymysql |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 52 | import testtools |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 53 | import testtools.content |
| 54 | import testtools.content_type |
Clint Byrum | 3343e3e | 2016-11-15 16:05:03 -0800 | [diff] [blame] | 55 | from git.exc import NoSuchPathError |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 56 | import yaml |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 57 | |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 58 | import tests.fakegithub |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 59 | import zuul.driver.gerrit.gerritsource as gerritsource |
| 60 | import zuul.driver.gerrit.gerritconnection as gerritconnection |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 61 | import zuul.driver.github.githubconnection as githubconnection |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 62 | import zuul.scheduler |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 63 | import zuul.executor.server |
| 64 | import zuul.executor.client |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 65 | import zuul.lib.connections |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 66 | import zuul.merger.client |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 67 | import zuul.merger.merger |
| 68 | import zuul.merger.server |
Tobias Henkel | d91b4d7 | 2017-05-23 15:43:40 +0200 | [diff] [blame] | 69 | import zuul.model |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 70 | import zuul.nodepool |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 71 | import zuul.rpcclient |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 72 | import zuul.zk |
James E. Blair | b09a0c5 | 2017-10-04 07:35:14 -0700 | [diff] [blame] | 73 | import zuul.configloader |
Jan Hruban | 49bff07 | 2015-11-03 11:45:46 +0100 | [diff] [blame] | 74 | from zuul.exceptions import MergeFailure |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 75 | from zuul.lib.config import get_default |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 76 | |
| 77 | FIXTURE_DIR = os.path.join(os.path.dirname(__file__), |
| 78 | 'fixtures') |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 79 | |
| 80 | KEEP_TEMPDIRS = bool(os.environ.get('KEEP_TEMPDIRS', False)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 81 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 82 | |
| 83 | def repack_repo(path): |
| 84 | cmd = ['git', '--git-dir=%s/.git' % path, 'repack', '-afd'] |
| 85 | output = subprocess.Popen(cmd, close_fds=True, |
| 86 | stdout=subprocess.PIPE, |
| 87 | stderr=subprocess.PIPE) |
| 88 | out = output.communicate() |
| 89 | if output.returncode: |
| 90 | raise Exception("git repack returned %d" % output.returncode) |
| 91 | return out |
| 92 | |
| 93 | |
| 94 | def random_sha1(): |
Clint Byrum | c0923d5 | 2017-05-10 15:47:41 -0400 | [diff] [blame] | 95 | return hashlib.sha1(str(random.random()).encode('ascii')).hexdigest() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 96 | |
| 97 | |
James E. Blair | a190f3b | 2015-01-05 14:56:54 -0800 | [diff] [blame] | 98 | def iterate_timeout(max_seconds, purpose): |
| 99 | start = time.time() |
| 100 | count = 0 |
| 101 | while (time.time() < start + max_seconds): |
| 102 | count += 1 |
| 103 | yield count |
| 104 | time.sleep(0) |
| 105 | raise Exception("Timeout waiting for %s" % purpose) |
| 106 | |
| 107 | |
Jesse Keating | 436a545 | 2017-04-20 11:48:41 -0700 | [diff] [blame] | 108 | def simple_layout(path, driver='gerrit'): |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 109 | """Specify a layout file for use by a test method. |
| 110 | |
| 111 | :arg str path: The path to the layout file. |
Jesse Keating | 436a545 | 2017-04-20 11:48:41 -0700 | [diff] [blame] | 112 | :arg str driver: The source driver to use, defaults to gerrit. |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 113 | |
| 114 | Some tests require only a very simple configuration. For those, |
| 115 | establishing a complete config directory hierachy is too much |
| 116 | work. In those cases, you can add a simple zuul.yaml file to the |
| 117 | test fixtures directory (in fixtures/layouts/foo.yaml) and use |
| 118 | this decorator to indicate the test method should use that rather |
| 119 | than the tenant config file specified by the test class. |
| 120 | |
| 121 | The decorator will cause that layout file to be added to a |
| 122 | config-project called "common-config" and each "project" instance |
| 123 | referenced in the layout file will have a git repo automatically |
| 124 | initialized. |
| 125 | """ |
| 126 | |
| 127 | def decorator(test): |
Jesse Keating | 436a545 | 2017-04-20 11:48:41 -0700 | [diff] [blame] | 128 | test.__simple_layout__ = (path, driver) |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 129 | return test |
| 130 | return decorator |
| 131 | |
| 132 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 133 | class GerritChangeReference(git.Reference): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 134 | _common_path_default = "refs/changes" |
| 135 | _points_to_commits_only = True |
| 136 | |
| 137 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 138 | class FakeGerritChange(object): |
Tobias Henkel | ea98a19 | 2017-05-29 21:15:17 +0200 | [diff] [blame] | 139 | categories = {'Approved': ('Approved', -1, 1), |
| 140 | 'Code-Review': ('Code-Review', -2, 2), |
| 141 | 'Verified': ('Verified', -2, 2)} |
| 142 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 143 | def __init__(self, gerrit, number, project, branch, subject, |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 144 | status='NEW', upstream_root=None, files={}, |
| 145 | parent=None): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 146 | self.gerrit = gerrit |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 147 | self.source = gerrit |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 148 | self.reported = 0 |
| 149 | self.queried = 0 |
| 150 | self.patchsets = [] |
| 151 | self.number = number |
| 152 | self.project = project |
| 153 | self.branch = branch |
| 154 | self.subject = subject |
| 155 | self.latest_patchset = 0 |
| 156 | self.depends_on_change = None |
| 157 | self.needed_by_changes = [] |
| 158 | self.fail_merge = False |
| 159 | self.messages = [] |
| 160 | self.data = { |
| 161 | 'branch': branch, |
| 162 | 'comments': [], |
| 163 | 'commitMessage': subject, |
| 164 | 'createdOn': time.time(), |
| 165 | 'id': 'I' + random_sha1(), |
| 166 | 'lastUpdated': time.time(), |
| 167 | 'number': str(number), |
| 168 | 'open': status == 'NEW', |
| 169 | 'owner': {'email': 'user@example.com', |
| 170 | 'name': 'User Name', |
| 171 | 'username': 'username'}, |
| 172 | 'patchSets': self.patchsets, |
| 173 | 'project': project, |
| 174 | 'status': status, |
| 175 | 'subject': subject, |
| 176 | 'submitRecords': [], |
James E. Blair | 0e4c791 | 2018-01-02 14:20:17 -0800 | [diff] [blame] | 177 | 'url': 'https://%s/%s' % (self.gerrit.server, number)} |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 178 | |
| 179 | self.upstream_root = upstream_root |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 180 | self.addPatchset(files=files, parent=parent) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 181 | self.data['submitRecords'] = self.getSubmitRecords() |
| 182 | self.open = status == 'NEW' |
| 183 | |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 184 | def addFakeChangeToRepo(self, msg, files, large, parent): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 185 | path = os.path.join(self.upstream_root, self.project) |
| 186 | repo = git.Repo(path) |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 187 | if parent is None: |
| 188 | parent = 'refs/tags/init' |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 189 | ref = GerritChangeReference.create( |
| 190 | repo, '1/%s/%s' % (self.number, self.latest_patchset), |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 191 | parent) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 192 | repo.head.reference = ref |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 193 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 194 | repo.git.clean('-x', '-f', '-d') |
| 195 | |
| 196 | path = os.path.join(self.upstream_root, self.project) |
| 197 | if not large: |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 198 | for fn, content in files.items(): |
| 199 | fn = os.path.join(path, fn) |
James E. Blair | 332636e | 2017-09-05 10:14:35 -0700 | [diff] [blame] | 200 | if content is None: |
| 201 | os.unlink(fn) |
| 202 | repo.index.remove([fn]) |
| 203 | else: |
| 204 | d = os.path.dirname(fn) |
| 205 | if not os.path.exists(d): |
| 206 | os.makedirs(d) |
| 207 | with open(fn, 'w') as f: |
| 208 | f.write(content) |
| 209 | repo.index.add([fn]) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 210 | else: |
| 211 | for fni in range(100): |
| 212 | fn = os.path.join(path, str(fni)) |
| 213 | f = open(fn, 'w') |
| 214 | for ci in range(4096): |
| 215 | f.write(random.choice(string.printable)) |
| 216 | f.close() |
| 217 | repo.index.add([fn]) |
| 218 | |
| 219 | r = repo.index.commit(msg) |
| 220 | repo.head.reference = 'master' |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 221 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 222 | repo.git.clean('-x', '-f', '-d') |
| 223 | repo.heads['master'].checkout() |
| 224 | return r |
| 225 | |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 226 | def addPatchset(self, files=None, large=False, parent=None): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 227 | self.latest_patchset += 1 |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 228 | if not files: |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 229 | fn = '%s-%s' % (self.branch.replace('/', '_'), self.number) |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 230 | data = ("test %s %s %s\n" % |
| 231 | (self.branch, self.number, self.latest_patchset)) |
| 232 | files = {fn: data} |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 233 | msg = self.subject + '-' + str(self.latest_patchset) |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 234 | c = self.addFakeChangeToRepo(msg, files, large, parent) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 235 | ps_files = [{'file': '/COMMIT_MSG', |
| 236 | 'type': 'ADDED'}, |
| 237 | {'file': 'README', |
| 238 | 'type': 'MODIFIED'}] |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 239 | for f in files.keys(): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 240 | ps_files.append({'file': f, 'type': 'ADDED'}) |
| 241 | d = {'approvals': [], |
| 242 | 'createdOn': time.time(), |
| 243 | 'files': ps_files, |
| 244 | 'number': str(self.latest_patchset), |
| 245 | 'ref': 'refs/changes/1/%s/%s' % (self.number, |
| 246 | self.latest_patchset), |
| 247 | 'revision': c.hexsha, |
| 248 | 'uploader': {'email': 'user@example.com', |
| 249 | 'name': 'User name', |
| 250 | 'username': 'user'}} |
| 251 | self.data['currentPatchSet'] = d |
| 252 | self.patchsets.append(d) |
| 253 | self.data['submitRecords'] = self.getSubmitRecords() |
| 254 | |
| 255 | def getPatchsetCreatedEvent(self, patchset): |
| 256 | event = {"type": "patchset-created", |
| 257 | "change": {"project": self.project, |
| 258 | "branch": self.branch, |
| 259 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 260 | "number": str(self.number), |
| 261 | "subject": self.subject, |
| 262 | "owner": {"name": "User Name"}, |
| 263 | "url": "https://hostname/3"}, |
| 264 | "patchSet": self.patchsets[patchset - 1], |
| 265 | "uploader": {"name": "User Name"}} |
| 266 | return event |
| 267 | |
| 268 | def getChangeRestoredEvent(self): |
| 269 | event = {"type": "change-restored", |
| 270 | "change": {"project": self.project, |
| 271 | "branch": self.branch, |
| 272 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 273 | "number": str(self.number), |
| 274 | "subject": self.subject, |
| 275 | "owner": {"name": "User Name"}, |
| 276 | "url": "https://hostname/3"}, |
| 277 | "restorer": {"name": "User Name"}, |
Antoine Musso | bd86a31 | 2014-01-08 14:51:33 +0100 | [diff] [blame] | 278 | "patchSet": self.patchsets[-1], |
| 279 | "reason": ""} |
| 280 | return event |
| 281 | |
| 282 | def getChangeAbandonedEvent(self): |
| 283 | event = {"type": "change-abandoned", |
| 284 | "change": {"project": self.project, |
| 285 | "branch": self.branch, |
| 286 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 287 | "number": str(self.number), |
| 288 | "subject": self.subject, |
| 289 | "owner": {"name": "User Name"}, |
| 290 | "url": "https://hostname/3"}, |
| 291 | "abandoner": {"name": "User Name"}, |
| 292 | "patchSet": self.patchsets[-1], |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 293 | "reason": ""} |
| 294 | return event |
| 295 | |
| 296 | def getChangeCommentEvent(self, patchset): |
| 297 | event = {"type": "comment-added", |
| 298 | "change": {"project": self.project, |
| 299 | "branch": self.branch, |
| 300 | "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af", |
| 301 | "number": str(self.number), |
| 302 | "subject": self.subject, |
| 303 | "owner": {"name": "User Name"}, |
| 304 | "url": "https://hostname/3"}, |
| 305 | "patchSet": self.patchsets[patchset - 1], |
| 306 | "author": {"name": "User Name"}, |
Tobias Henkel | bf24fd1 | 2017-07-27 06:13:07 +0200 | [diff] [blame] | 307 | "approvals": [{"type": "Code-Review", |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 308 | "description": "Code-Review", |
| 309 | "value": "0"}], |
| 310 | "comment": "This is a comment"} |
| 311 | return event |
| 312 | |
James E. Blair | c2a5ed7 | 2017-02-20 14:12:01 -0500 | [diff] [blame] | 313 | def getChangeMergedEvent(self): |
| 314 | event = {"submitter": {"name": "Jenkins", |
| 315 | "username": "jenkins"}, |
| 316 | "newRev": "29ed3b5f8f750a225c5be70235230e3a6ccb04d9", |
| 317 | "patchSet": self.patchsets[-1], |
| 318 | "change": self.data, |
| 319 | "type": "change-merged", |
| 320 | "eventCreatedOn": 1487613810} |
| 321 | return event |
| 322 | |
James E. Blair | 8cce42e | 2016-10-18 08:18:36 -0700 | [diff] [blame] | 323 | def getRefUpdatedEvent(self): |
| 324 | path = os.path.join(self.upstream_root, self.project) |
| 325 | repo = git.Repo(path) |
| 326 | oldrev = repo.heads[self.branch].commit.hexsha |
| 327 | |
| 328 | event = { |
| 329 | "type": "ref-updated", |
| 330 | "submitter": { |
| 331 | "name": "User Name", |
| 332 | }, |
| 333 | "refUpdate": { |
| 334 | "oldRev": oldrev, |
| 335 | "newRev": self.patchsets[-1]['revision'], |
| 336 | "refName": self.branch, |
| 337 | "project": self.project, |
| 338 | } |
| 339 | } |
| 340 | return event |
| 341 | |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 342 | def addApproval(self, category, value, username='reviewer_john', |
| 343 | granted_on=None, message=''): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 344 | if not granted_on: |
| 345 | granted_on = time.time() |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 346 | approval = { |
Tobias Henkel | bf24fd1 | 2017-07-27 06:13:07 +0200 | [diff] [blame] | 347 | 'description': self.categories[category][0], |
| 348 | 'type': category, |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 349 | 'value': str(value), |
| 350 | 'by': { |
| 351 | 'username': username, |
| 352 | 'email': username + '@example.com', |
| 353 | }, |
| 354 | 'grantedOn': int(granted_on) |
| 355 | } |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 356 | for i, x in enumerate(self.patchsets[-1]['approvals'][:]): |
Tobias Henkel | bf24fd1 | 2017-07-27 06:13:07 +0200 | [diff] [blame] | 357 | if x['by']['username'] == username and x['type'] == category: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 358 | del self.patchsets[-1]['approvals'][i] |
| 359 | self.patchsets[-1]['approvals'].append(approval) |
| 360 | event = {'approvals': [approval], |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 361 | 'author': {'email': 'author@example.com', |
| 362 | 'name': 'Patchset Author', |
| 363 | 'username': 'author_phil'}, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 364 | 'change': {'branch': self.branch, |
| 365 | 'id': 'Iaa69c46accf97d0598111724a38250ae76a22c87', |
| 366 | 'number': str(self.number), |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 367 | 'owner': {'email': 'owner@example.com', |
| 368 | 'name': 'Change Owner', |
| 369 | 'username': 'owner_jane'}, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 370 | 'project': self.project, |
| 371 | 'subject': self.subject, |
| 372 | 'topic': 'master', |
| 373 | 'url': 'https://hostname/459'}, |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 374 | 'comment': message, |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 375 | 'patchSet': self.patchsets[-1], |
| 376 | 'type': 'comment-added'} |
| 377 | self.data['submitRecords'] = self.getSubmitRecords() |
| 378 | return json.loads(json.dumps(event)) |
| 379 | |
| 380 | def getSubmitRecords(self): |
| 381 | status = {} |
| 382 | for cat in self.categories.keys(): |
| 383 | status[cat] = 0 |
| 384 | |
| 385 | for a in self.patchsets[-1]['approvals']: |
| 386 | cur = status[a['type']] |
| 387 | cat_min, cat_max = self.categories[a['type']][1:] |
| 388 | new = int(a['value']) |
| 389 | if new == cat_min: |
| 390 | cur = new |
| 391 | elif abs(new) > abs(cur): |
| 392 | cur = new |
| 393 | status[a['type']] = cur |
| 394 | |
| 395 | labels = [] |
| 396 | ok = True |
| 397 | for typ, cat in self.categories.items(): |
| 398 | cur = status[typ] |
| 399 | cat_min, cat_max = cat[1:] |
| 400 | if cur == cat_min: |
| 401 | value = 'REJECT' |
| 402 | ok = False |
| 403 | elif cur == cat_max: |
| 404 | value = 'OK' |
| 405 | else: |
| 406 | value = 'NEED' |
| 407 | ok = False |
| 408 | labels.append({'label': cat[0], 'status': value}) |
| 409 | if ok: |
| 410 | return [{'status': 'OK'}] |
| 411 | return [{'status': 'NOT_READY', |
| 412 | 'labels': labels}] |
| 413 | |
| 414 | def setDependsOn(self, other, patchset): |
| 415 | self.depends_on_change = other |
| 416 | d = {'id': other.data['id'], |
| 417 | 'number': other.data['number'], |
| 418 | 'ref': other.patchsets[patchset - 1]['ref'] |
| 419 | } |
| 420 | self.data['dependsOn'] = [d] |
| 421 | |
| 422 | other.needed_by_changes.append(self) |
| 423 | needed = other.data.get('neededBy', []) |
| 424 | d = {'id': self.data['id'], |
| 425 | 'number': self.data['number'], |
James E. Blair | db93b30 | 2017-07-19 15:33:11 -0700 | [diff] [blame] | 426 | 'ref': self.patchsets[-1]['ref'], |
| 427 | 'revision': self.patchsets[-1]['revision'] |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 428 | } |
| 429 | needed.append(d) |
| 430 | other.data['neededBy'] = needed |
| 431 | |
| 432 | def query(self): |
| 433 | self.queried += 1 |
| 434 | d = self.data.get('dependsOn') |
| 435 | if d: |
| 436 | d = d[0] |
| 437 | if (self.depends_on_change.patchsets[-1]['ref'] == d['ref']): |
| 438 | d['isCurrentPatchSet'] = True |
| 439 | else: |
| 440 | d['isCurrentPatchSet'] = False |
| 441 | return json.loads(json.dumps(self.data)) |
| 442 | |
| 443 | def setMerged(self): |
| 444 | if (self.depends_on_change and |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 445 | self.depends_on_change.data['status'] != 'MERGED'): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 446 | return |
| 447 | if self.fail_merge: |
| 448 | return |
| 449 | self.data['status'] = 'MERGED' |
| 450 | self.open = False |
| 451 | |
| 452 | path = os.path.join(self.upstream_root, self.project) |
| 453 | repo = git.Repo(path) |
| 454 | repo.heads[self.branch].commit = \ |
| 455 | repo.commit(self.patchsets[-1]['revision']) |
| 456 | |
| 457 | def setReported(self): |
| 458 | self.reported += 1 |
| 459 | |
| 460 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 461 | class FakeGerritConnection(gerritconnection.GerritConnection): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 462 | """A Fake Gerrit connection for use in tests. |
| 463 | |
| 464 | This subclasses |
| 465 | :py:class:`~zuul.connection.gerrit.GerritConnection` to add the |
| 466 | ability for tests to add changes to the fake Gerrit it represents. |
| 467 | """ |
| 468 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 469 | log = logging.getLogger("zuul.test.FakeGerritConnection") |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 470 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 471 | def __init__(self, driver, connection_name, connection_config, |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 472 | changes_db=None, upstream_root=None): |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 473 | super(FakeGerritConnection, self).__init__(driver, connection_name, |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 474 | connection_config) |
| 475 | |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 476 | self.event_queue = queue.Queue() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 477 | self.fixture_dir = os.path.join(FIXTURE_DIR, 'gerrit') |
| 478 | self.change_number = 0 |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 479 | self.changes = changes_db |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 480 | self.queries = [] |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 481 | self.upstream_root = upstream_root |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 482 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 483 | def addFakeChange(self, project, branch, subject, status='NEW', |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 484 | files=None, parent=None): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 485 | """Add a change to the fake Gerrit.""" |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 486 | self.change_number += 1 |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 487 | c = FakeGerritChange(self, self.change_number, project, branch, |
| 488 | subject, upstream_root=self.upstream_root, |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 489 | status=status, files=files, parent=parent) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 490 | self.changes[self.change_number] = c |
| 491 | return c |
| 492 | |
James E. Blair | 1edfd97 | 2017-12-01 15:54:24 -0800 | [diff] [blame] | 493 | def addFakeTag(self, project, branch, tag): |
| 494 | path = os.path.join(self.upstream_root, project) |
| 495 | repo = git.Repo(path) |
| 496 | commit = repo.heads[branch].commit |
| 497 | newrev = commit.hexsha |
| 498 | ref = 'refs/tags/' + tag |
| 499 | |
| 500 | git.Tag.create(repo, tag, commit) |
| 501 | |
| 502 | event = { |
| 503 | "type": "ref-updated", |
| 504 | "submitter": { |
| 505 | "name": "User Name", |
| 506 | }, |
| 507 | "refUpdate": { |
| 508 | "oldRev": 40 * '0', |
| 509 | "newRev": newrev, |
| 510 | "refName": ref, |
| 511 | "project": project, |
| 512 | } |
| 513 | } |
| 514 | return event |
| 515 | |
James E. Blair | 72facdc | 2017-08-17 10:29:12 -0700 | [diff] [blame] | 516 | def getFakeBranchCreatedEvent(self, project, branch): |
| 517 | path = os.path.join(self.upstream_root, project) |
| 518 | repo = git.Repo(path) |
| 519 | oldrev = 40 * '0' |
| 520 | |
| 521 | event = { |
| 522 | "type": "ref-updated", |
| 523 | "submitter": { |
| 524 | "name": "User Name", |
| 525 | }, |
| 526 | "refUpdate": { |
| 527 | "oldRev": oldrev, |
| 528 | "newRev": repo.heads[branch].commit.hexsha, |
James E. Blair | 24690ec | 2017-11-02 09:05:01 -0700 | [diff] [blame] | 529 | "refName": 'refs/heads/' + branch, |
James E. Blair | 72facdc | 2017-08-17 10:29:12 -0700 | [diff] [blame] | 530 | "project": project, |
| 531 | } |
| 532 | } |
| 533 | return event |
| 534 | |
James E. Blair | c6d4865 | 2018-02-14 14:20:13 -0800 | [diff] [blame] | 535 | def getFakeBranchDeletedEvent(self, project, branch): |
| 536 | oldrev = '4abd38457c2da2a72d4d030219ab180ecdb04bf0' |
| 537 | newrev = 40 * '0' |
| 538 | |
| 539 | event = { |
| 540 | "type": "ref-updated", |
| 541 | "submitter": { |
| 542 | "name": "User Name", |
| 543 | }, |
| 544 | "refUpdate": { |
| 545 | "oldRev": oldrev, |
| 546 | "newRev": newrev, |
| 547 | "refName": 'refs/heads/' + branch, |
| 548 | "project": project, |
| 549 | } |
| 550 | } |
| 551 | return event |
| 552 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 553 | def review(self, project, changeid, message, action): |
| 554 | number, ps = changeid.split(',') |
| 555 | change = self.changes[int(number)] |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 556 | |
| 557 | # Add the approval back onto the change (ie simulate what gerrit would |
| 558 | # do). |
| 559 | # Usually when zuul leaves a review it'll create a feedback loop where |
| 560 | # zuul's review enters another gerrit event (which is then picked up by |
| 561 | # zuul). However, we can't mimic this behaviour (by adding this |
| 562 | # approval event into the queue) as it stops jobs from checking what |
| 563 | # happens before this event is triggered. If a job needs to see what |
| 564 | # happens they can add their own verified event into the queue. |
| 565 | # Nevertheless, we can update change with the new review in gerrit. |
| 566 | |
James E. Blair | 8b5408c | 2016-08-08 15:37:46 -0700 | [diff] [blame] | 567 | for cat in action.keys(): |
| 568 | if cat != 'submit': |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 569 | change.addApproval(cat, action[cat], username=self.user) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 570 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 571 | change.messages.append(message) |
Joshua Hesketh | 642824b | 2014-07-01 17:54:59 +1000 | [diff] [blame] | 572 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 573 | if 'submit' in action: |
| 574 | change.setMerged() |
| 575 | if message: |
| 576 | change.setReported() |
| 577 | |
| 578 | def query(self, number): |
| 579 | change = self.changes.get(int(number)) |
| 580 | if change: |
| 581 | return change.query() |
| 582 | return {} |
| 583 | |
James E. Blair | 0e4c791 | 2018-01-02 14:20:17 -0800 | [diff] [blame] | 584 | def _simpleQuery(self, query): |
James E. Blair | 5ee2425 | 2014-12-30 10:12:29 -0800 | [diff] [blame] | 585 | if query.startswith('change:'): |
| 586 | # Query a specific changeid |
| 587 | changeid = query[len('change:'):] |
| 588 | l = [change.query() for change in self.changes.values() |
James E. Blair | 0e4c791 | 2018-01-02 14:20:17 -0800 | [diff] [blame] | 589 | if (change.data['id'] == changeid or |
| 590 | change.data['number'] == changeid)] |
James E. Blair | 96698e2 | 2015-04-02 07:48:21 -0700 | [diff] [blame] | 591 | elif query.startswith('message:'): |
| 592 | # Query the content of a commit message |
| 593 | msg = query[len('message:'):].strip() |
| 594 | l = [change.query() for change in self.changes.values() |
| 595 | if msg in change.data['commitMessage']] |
James E. Blair | 5ee2425 | 2014-12-30 10:12:29 -0800 | [diff] [blame] | 596 | else: |
| 597 | # Query all open changes |
| 598 | l = [change.query() for change in self.changes.values()] |
James E. Blair | f8ff993 | 2014-08-15 15:24:24 -0700 | [diff] [blame] | 599 | return l |
James E. Blair | c494d54 | 2014-08-06 09:23:52 -0700 | [diff] [blame] | 600 | |
James E. Blair | 0e4c791 | 2018-01-02 14:20:17 -0800 | [diff] [blame] | 601 | def simpleQuery(self, query): |
| 602 | self.log.debug("simpleQuery: %s" % query) |
| 603 | self.queries.append(query) |
| 604 | results = [] |
| 605 | if query.startswith('(') and 'OR' in query: |
| 606 | query = query[1:-2] |
| 607 | for q in query.split(' OR '): |
| 608 | for r in self._simpleQuery(q): |
| 609 | if r not in results: |
| 610 | results.append(r) |
| 611 | else: |
| 612 | results = self._simpleQuery(query) |
| 613 | return results |
| 614 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 615 | def _start_watcher_thread(self, *args, **kw): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 616 | pass |
| 617 | |
Tobias Henkel | d91b4d7 | 2017-05-23 15:43:40 +0200 | [diff] [blame] | 618 | def _uploadPack(self, project): |
| 619 | ret = ('00a31270149696713ba7e06f1beb760f20d359c4abed HEAD\x00' |
| 620 | 'multi_ack thin-pack side-band side-band-64k ofs-delta ' |
| 621 | 'shallow no-progress include-tag multi_ack_detailed no-done\n') |
| 622 | path = os.path.join(self.upstream_root, project.name) |
| 623 | repo = git.Repo(path) |
| 624 | for ref in repo.refs: |
| 625 | r = ref.object.hexsha + ' ' + ref.path + '\n' |
| 626 | ret += '%04x%s' % (len(r) + 4, r) |
| 627 | ret += '0000' |
| 628 | return ret |
| 629 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 630 | def getGitUrl(self, project): |
James E. Blair | da5bb7e | 2018-01-22 16:12:17 -0800 | [diff] [blame] | 631 | return 'file://' + os.path.join(self.upstream_root, project.name) |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 632 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 633 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 634 | class GithubChangeReference(git.Reference): |
| 635 | _common_path_default = "refs/pull" |
| 636 | _points_to_commits_only = True |
| 637 | |
| 638 | |
| 639 | class FakeGithubPullRequest(object): |
| 640 | |
| 641 | def __init__(self, github, number, project, branch, |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 642 | subject, upstream_root, files=[], number_of_commits=1, |
Jesse Keating | 152a402 | 2017-07-07 08:39:52 -0700 | [diff] [blame] | 643 | writers=[], body=None): |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 644 | """Creates a new PR with several commits. |
| 645 | Sends an event about opened PR.""" |
| 646 | self.github = github |
| 647 | self.source = github |
| 648 | self.number = number |
| 649 | self.project = project |
| 650 | self.branch = branch |
Jan Hruban | 37615e5 | 2015-11-19 14:30:49 +0100 | [diff] [blame] | 651 | self.subject = subject |
Jesse Keating | a41566f | 2017-06-14 18:17:51 -0700 | [diff] [blame] | 652 | self.body = body |
Jan Hruban | 37615e5 | 2015-11-19 14:30:49 +0100 | [diff] [blame] | 653 | self.number_of_commits = 0 |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 654 | self.upstream_root = upstream_root |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 655 | self.files = [] |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 656 | self.comments = [] |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 657 | self.labels = [] |
Jan Hruban | e252a73 | 2017-01-03 15:03:09 +0100 | [diff] [blame] | 658 | self.statuses = {} |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 659 | self.reviews = [] |
| 660 | self.writers = [] |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 661 | self.updated_at = None |
| 662 | self.head_sha = None |
Jan Hruban | 49bff07 | 2015-11-03 11:45:46 +0100 | [diff] [blame] | 663 | self.is_merged = False |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 664 | self.merge_message = None |
Jesse Keating | 4a27f13 | 2017-05-25 16:44:01 -0700 | [diff] [blame] | 665 | self.state = 'open' |
James E. Blair | 54145e0 | 2018-01-10 16:07:41 -0800 | [diff] [blame] | 666 | self.url = 'https://%s/%s/pull/%s' % (github.server, project, number) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 667 | self._createPRRef() |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 668 | self._addCommitToRepo(files=files) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 669 | self._updateTimeStamp() |
| 670 | |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 671 | def addCommit(self, files=[]): |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 672 | """Adds a commit on top of the actual PR head.""" |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 673 | self._addCommitToRepo(files=files) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 674 | self._updateTimeStamp() |
| 675 | |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 676 | def forcePush(self, files=[]): |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 677 | """Clears actual commits and add a commit on top of the base.""" |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 678 | self._addCommitToRepo(files=files, reset=True) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 679 | self._updateTimeStamp() |
| 680 | |
| 681 | def getPullRequestOpenedEvent(self): |
| 682 | return self._getPullRequestEvent('opened') |
| 683 | |
| 684 | def getPullRequestSynchronizeEvent(self): |
| 685 | return self._getPullRequestEvent('synchronize') |
| 686 | |
| 687 | def getPullRequestReopenedEvent(self): |
| 688 | return self._getPullRequestEvent('reopened') |
| 689 | |
| 690 | def getPullRequestClosedEvent(self): |
| 691 | return self._getPullRequestEvent('closed') |
| 692 | |
Jesse Keating | a41566f | 2017-06-14 18:17:51 -0700 | [diff] [blame] | 693 | def getPullRequestEditedEvent(self): |
| 694 | return self._getPullRequestEvent('edited') |
| 695 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 696 | def addComment(self, message): |
| 697 | self.comments.append(message) |
| 698 | self._updateTimeStamp() |
| 699 | |
Jan Hruban | c7ab160 | 2015-10-14 15:29:33 +0200 | [diff] [blame] | 700 | def getCommentAddedEvent(self, text): |
| 701 | name = 'issue_comment' |
| 702 | data = { |
| 703 | 'action': 'created', |
| 704 | 'issue': { |
| 705 | 'number': self.number |
| 706 | }, |
| 707 | 'comment': { |
| 708 | 'body': text |
| 709 | }, |
| 710 | 'repository': { |
| 711 | 'full_name': self.project |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 712 | }, |
| 713 | 'sender': { |
| 714 | 'login': 'ghuser' |
Jan Hruban | c7ab160 | 2015-10-14 15:29:33 +0200 | [diff] [blame] | 715 | } |
| 716 | } |
| 717 | return (name, data) |
| 718 | |
Jesse Keating | 5c05a9f | 2017-01-12 14:44:58 -0800 | [diff] [blame] | 719 | def getReviewAddedEvent(self, review): |
| 720 | name = 'pull_request_review' |
| 721 | data = { |
| 722 | 'action': 'submitted', |
| 723 | 'pull_request': { |
| 724 | 'number': self.number, |
| 725 | 'title': self.subject, |
| 726 | 'updated_at': self.updated_at, |
| 727 | 'base': { |
| 728 | 'ref': self.branch, |
| 729 | 'repo': { |
| 730 | 'full_name': self.project |
| 731 | } |
| 732 | }, |
| 733 | 'head': { |
| 734 | 'sha': self.head_sha |
| 735 | } |
| 736 | }, |
| 737 | 'review': { |
| 738 | 'state': review |
| 739 | }, |
| 740 | 'repository': { |
| 741 | 'full_name': self.project |
| 742 | }, |
| 743 | 'sender': { |
| 744 | 'login': 'ghuser' |
| 745 | } |
| 746 | } |
| 747 | return (name, data) |
| 748 | |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 749 | def addLabel(self, name): |
| 750 | if name not in self.labels: |
| 751 | self.labels.append(name) |
| 752 | self._updateTimeStamp() |
| 753 | return self._getLabelEvent(name) |
| 754 | |
| 755 | def removeLabel(self, name): |
| 756 | if name in self.labels: |
| 757 | self.labels.remove(name) |
| 758 | self._updateTimeStamp() |
| 759 | return self._getUnlabelEvent(name) |
| 760 | |
| 761 | def _getLabelEvent(self, label): |
| 762 | name = 'pull_request' |
| 763 | data = { |
| 764 | 'action': 'labeled', |
| 765 | 'pull_request': { |
| 766 | 'number': self.number, |
| 767 | 'updated_at': self.updated_at, |
| 768 | 'base': { |
| 769 | 'ref': self.branch, |
| 770 | 'repo': { |
| 771 | 'full_name': self.project |
| 772 | } |
| 773 | }, |
| 774 | 'head': { |
| 775 | 'sha': self.head_sha |
| 776 | } |
| 777 | }, |
| 778 | 'label': { |
| 779 | 'name': label |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 780 | }, |
| 781 | 'sender': { |
| 782 | 'login': 'ghuser' |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 783 | } |
| 784 | } |
| 785 | return (name, data) |
| 786 | |
| 787 | def _getUnlabelEvent(self, label): |
| 788 | name = 'pull_request' |
| 789 | data = { |
| 790 | 'action': 'unlabeled', |
| 791 | 'pull_request': { |
| 792 | 'number': self.number, |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 793 | 'title': self.subject, |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 794 | 'updated_at': self.updated_at, |
| 795 | 'base': { |
| 796 | 'ref': self.branch, |
| 797 | 'repo': { |
| 798 | 'full_name': self.project |
| 799 | } |
| 800 | }, |
| 801 | 'head': { |
Jesse Keating | d96e588 | 2017-01-19 13:55:50 -0800 | [diff] [blame] | 802 | 'sha': self.head_sha, |
| 803 | 'repo': { |
| 804 | 'full_name': self.project |
| 805 | } |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 806 | } |
| 807 | }, |
| 808 | 'label': { |
| 809 | 'name': label |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 810 | }, |
| 811 | 'sender': { |
| 812 | 'login': 'ghuser' |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 813 | } |
| 814 | } |
| 815 | return (name, data) |
| 816 | |
Jesse Keating | a41566f | 2017-06-14 18:17:51 -0700 | [diff] [blame] | 817 | def editBody(self, body): |
| 818 | self.body = body |
| 819 | self._updateTimeStamp() |
| 820 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 821 | def _getRepo(self): |
| 822 | repo_path = os.path.join(self.upstream_root, self.project) |
| 823 | return git.Repo(repo_path) |
| 824 | |
| 825 | def _createPRRef(self): |
| 826 | repo = self._getRepo() |
| 827 | GithubChangeReference.create( |
| 828 | repo, self._getPRReference(), 'refs/tags/init') |
| 829 | |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 830 | def _addCommitToRepo(self, files=[], reset=False): |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 831 | repo = self._getRepo() |
| 832 | ref = repo.references[self._getPRReference()] |
| 833 | if reset: |
Jan Hruban | 37615e5 | 2015-11-19 14:30:49 +0100 | [diff] [blame] | 834 | self.number_of_commits = 0 |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 835 | ref.set_object('refs/tags/init') |
Jan Hruban | 37615e5 | 2015-11-19 14:30:49 +0100 | [diff] [blame] | 836 | self.number_of_commits += 1 |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 837 | repo.head.reference = ref |
| 838 | zuul.merger.merger.reset_repo_to_head(repo) |
| 839 | repo.git.clean('-x', '-f', '-d') |
| 840 | |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 841 | if files: |
| 842 | fn = files[0] |
| 843 | self.files = files |
| 844 | else: |
| 845 | fn = '%s-%s' % (self.branch.replace('/', '_'), self.number) |
| 846 | self.files = [fn] |
Jan Hruban | 37615e5 | 2015-11-19 14:30:49 +0100 | [diff] [blame] | 847 | msg = self.subject + '-' + str(self.number_of_commits) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 848 | fn = os.path.join(repo.working_dir, fn) |
| 849 | f = open(fn, 'w') |
| 850 | with open(fn, 'w') as f: |
| 851 | f.write("test %s %s\n" % |
| 852 | (self.branch, self.number)) |
| 853 | repo.index.add([fn]) |
| 854 | |
| 855 | self.head_sha = repo.index.commit(msg).hexsha |
Jesse Keating | d96e588 | 2017-01-19 13:55:50 -0800 | [diff] [blame] | 856 | # Create an empty set of statuses for the given sha, |
| 857 | # each sha on a PR may have a status set on it |
| 858 | self.statuses[self.head_sha] = [] |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 859 | repo.head.reference = 'master' |
| 860 | zuul.merger.merger.reset_repo_to_head(repo) |
| 861 | repo.git.clean('-x', '-f', '-d') |
| 862 | repo.heads['master'].checkout() |
| 863 | |
| 864 | def _updateTimeStamp(self): |
| 865 | self.updated_at = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.localtime()) |
| 866 | |
| 867 | def getPRHeadSha(self): |
| 868 | repo = self._getRepo() |
| 869 | return repo.references[self._getPRReference()].commit.hexsha |
| 870 | |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 871 | def addReview(self, user, state, granted_on=None): |
Adam Gandelman | d81dd76 | 2017-02-09 15:15:49 -0800 | [diff] [blame] | 872 | gh_time_format = '%Y-%m-%dT%H:%M:%SZ' |
| 873 | # convert the timestamp to a str format that would be returned |
| 874 | # from github as 'submitted_at' in the API response |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 875 | |
Adam Gandelman | d81dd76 | 2017-02-09 15:15:49 -0800 | [diff] [blame] | 876 | if granted_on: |
| 877 | granted_on = datetime.datetime.utcfromtimestamp(granted_on) |
| 878 | submitted_at = time.strftime( |
| 879 | gh_time_format, granted_on.timetuple()) |
| 880 | else: |
| 881 | # github timestamps only down to the second, so we need to make |
| 882 | # sure reviews that tests add appear to be added over a period of |
| 883 | # time in the past and not all at once. |
| 884 | if not self.reviews: |
| 885 | # the first review happens 10 mins ago |
| 886 | offset = 600 |
| 887 | else: |
| 888 | # subsequent reviews happen 1 minute closer to now |
| 889 | offset = 600 - (len(self.reviews) * 60) |
| 890 | |
| 891 | granted_on = datetime.datetime.utcfromtimestamp( |
| 892 | time.time() - offset) |
| 893 | submitted_at = time.strftime( |
| 894 | gh_time_format, granted_on.timetuple()) |
| 895 | |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 896 | self.reviews.append({ |
| 897 | 'state': state, |
| 898 | 'user': { |
| 899 | 'login': user, |
| 900 | 'email': user + "@derp.com", |
| 901 | }, |
Adam Gandelman | d81dd76 | 2017-02-09 15:15:49 -0800 | [diff] [blame] | 902 | 'submitted_at': submitted_at, |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 903 | }) |
| 904 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 905 | def _getPRReference(self): |
| 906 | return '%s/head' % self.number |
| 907 | |
| 908 | def _getPullRequestEvent(self, action): |
| 909 | name = 'pull_request' |
| 910 | data = { |
| 911 | 'action': action, |
| 912 | 'number': self.number, |
| 913 | 'pull_request': { |
| 914 | 'number': self.number, |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 915 | 'title': self.subject, |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 916 | 'updated_at': self.updated_at, |
| 917 | 'base': { |
| 918 | 'ref': self.branch, |
| 919 | 'repo': { |
| 920 | 'full_name': self.project |
| 921 | } |
| 922 | }, |
| 923 | 'head': { |
Jesse Keating | d96e588 | 2017-01-19 13:55:50 -0800 | [diff] [blame] | 924 | 'sha': self.head_sha, |
| 925 | 'repo': { |
| 926 | 'full_name': self.project |
| 927 | } |
Jesse Keating | a41566f | 2017-06-14 18:17:51 -0700 | [diff] [blame] | 928 | }, |
| 929 | 'body': self.body |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 930 | }, |
| 931 | 'sender': { |
| 932 | 'login': 'ghuser' |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 933 | } |
| 934 | } |
| 935 | return (name, data) |
| 936 | |
Adam Gandelman | 8c6eeb5 | 2017-01-23 16:31:06 -0800 | [diff] [blame] | 937 | def getCommitStatusEvent(self, context, state='success', user='zuul'): |
| 938 | name = 'status' |
| 939 | data = { |
| 940 | 'state': state, |
| 941 | 'sha': self.head_sha, |
Jesse Keating | 9021a01 | 2017-08-29 14:45:27 -0700 | [diff] [blame] | 942 | 'name': self.project, |
Adam Gandelman | 8c6eeb5 | 2017-01-23 16:31:06 -0800 | [diff] [blame] | 943 | 'description': 'Test results for %s: %s' % (self.head_sha, state), |
| 944 | 'target_url': 'http://zuul/%s' % self.head_sha, |
| 945 | 'branches': [], |
| 946 | 'context': context, |
| 947 | 'sender': { |
| 948 | 'login': user |
| 949 | } |
| 950 | } |
| 951 | return (name, data) |
| 952 | |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 953 | def setMerged(self, commit_message): |
| 954 | self.is_merged = True |
| 955 | self.merge_message = commit_message |
| 956 | |
| 957 | repo = self._getRepo() |
| 958 | repo.heads[self.branch].commit = repo.commit(self.head_sha) |
| 959 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 960 | |
| 961 | class FakeGithubConnection(githubconnection.GithubConnection): |
| 962 | log = logging.getLogger("zuul.test.FakeGithubConnection") |
| 963 | |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 964 | def __init__(self, driver, connection_name, connection_config, rpcclient, |
Tobias Henkel | 054eccc | 2017-12-20 11:36:19 +0100 | [diff] [blame] | 965 | changes_db=None, upstream_root=None, git_url_with_auth=False): |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 966 | super(FakeGithubConnection, self).__init__(driver, connection_name, |
| 967 | connection_config) |
| 968 | self.connection_name = connection_name |
| 969 | self.pr_number = 0 |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 970 | self.pull_requests = changes_db |
Jesse Keating | 1f7ebe9 | 2017-06-12 17:21:00 -0700 | [diff] [blame] | 971 | self.statuses = {} |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 972 | self.upstream_root = upstream_root |
Jan Hruban | 49bff07 | 2015-11-03 11:45:46 +0100 | [diff] [blame] | 973 | self.merge_failure = False |
| 974 | self.merge_not_allowed_count = 0 |
Jesse Keating | 08dab8f | 2017-06-21 12:59:23 +0100 | [diff] [blame] | 975 | self.reports = [] |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 976 | self.github_client = tests.fakegithub.FakeGithub(changes_db) |
Tobias Henkel | 054eccc | 2017-12-20 11:36:19 +0100 | [diff] [blame] | 977 | self.git_url_with_auth = git_url_with_auth |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 978 | self.rpcclient = rpcclient |
Tobias Henkel | 64e37a0 | 2017-08-02 10:13:30 +0200 | [diff] [blame] | 979 | |
| 980 | def getGithubClient(self, |
| 981 | project=None, |
Jesse Keating | 97b4248 | 2017-09-12 16:13:13 -0600 | [diff] [blame] | 982 | user_id=None): |
Tobias Henkel | 64e37a0 | 2017-08-02 10:13:30 +0200 | [diff] [blame] | 983 | return self.github_client |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 984 | |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 985 | def setZuulWebPort(self, port): |
| 986 | self.zuul_web_port = port |
| 987 | |
Jesse Keating | a41566f | 2017-06-14 18:17:51 -0700 | [diff] [blame] | 988 | def openFakePullRequest(self, project, branch, subject, files=[], |
Jesse Keating | 152a402 | 2017-07-07 08:39:52 -0700 | [diff] [blame] | 989 | body=None): |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 990 | self.pr_number += 1 |
| 991 | pull_request = FakeGithubPullRequest( |
Jan Hruban | 570d01c | 2016-03-10 21:51:32 +0100 | [diff] [blame] | 992 | self, self.pr_number, project, branch, subject, self.upstream_root, |
Jesse Keating | a41566f | 2017-06-14 18:17:51 -0700 | [diff] [blame] | 993 | files=files, body=body) |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 994 | self.pull_requests[self.pr_number] = pull_request |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 995 | return pull_request |
| 996 | |
Jesse Keating | 71a47ff | 2017-06-06 11:36:43 -0700 | [diff] [blame] | 997 | def getPushEvent(self, project, ref, old_rev=None, new_rev=None, |
| 998 | added_files=[], removed_files=[], modified_files=[]): |
Wayne | 1a78c61 | 2015-06-11 17:14:13 -0700 | [diff] [blame] | 999 | if not old_rev: |
James E. Blair | b8203e4 | 2017-08-02 17:00:14 -0700 | [diff] [blame] | 1000 | old_rev = '0' * 40 |
Wayne | 1a78c61 | 2015-06-11 17:14:13 -0700 | [diff] [blame] | 1001 | if not new_rev: |
| 1002 | new_rev = random_sha1() |
| 1003 | name = 'push' |
| 1004 | data = { |
| 1005 | 'ref': ref, |
| 1006 | 'before': old_rev, |
| 1007 | 'after': new_rev, |
| 1008 | 'repository': { |
| 1009 | 'full_name': project |
Jesse Keating | 71a47ff | 2017-06-06 11:36:43 -0700 | [diff] [blame] | 1010 | }, |
| 1011 | 'commits': [ |
| 1012 | { |
| 1013 | 'added': added_files, |
| 1014 | 'removed': removed_files, |
| 1015 | 'modified': modified_files |
| 1016 | } |
| 1017 | ] |
Wayne | 1a78c61 | 2015-06-11 17:14:13 -0700 | [diff] [blame] | 1018 | } |
| 1019 | return (name, data) |
| 1020 | |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 1021 | def emitEvent(self, event, use_zuulweb=False): |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 1022 | """Emulates sending the GitHub webhook event to the connection.""" |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 1023 | name, data = event |
Clint Byrum | 607d10e | 2017-05-18 12:05:13 -0700 | [diff] [blame] | 1024 | payload = json.dumps(data).encode('utf8') |
Clint Byrum | cf1b742 | 2017-07-27 17:12:00 -0700 | [diff] [blame] | 1025 | secret = self.connection_config['webhook_token'] |
| 1026 | signature = githubconnection._sign_request(payload, secret) |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 1027 | headers = {'x-github-event': name, 'x-hub-signature': signature} |
| 1028 | |
| 1029 | if use_zuulweb: |
| 1030 | req = urllib.request.Request( |
Monty Taylor | 64bf8e0 | 2018-01-23 16:39:30 -0600 | [diff] [blame] | 1031 | 'http://127.0.0.1:%s/connection/%s/payload' |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 1032 | % (self.zuul_web_port, self.connection_name), |
| 1033 | data=payload, headers=headers) |
| 1034 | return urllib.request.urlopen(req) |
| 1035 | else: |
| 1036 | job = self.rpcclient.submitJob( |
| 1037 | 'github:%s:payload' % self.connection_name, |
| 1038 | {'headers': headers, 'body': data}) |
| 1039 | return json.loads(job.data[0]) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 1040 | |
Tobias Henkel | 3c17d5f | 2017-08-03 11:46:54 +0200 | [diff] [blame] | 1041 | def addProject(self, project): |
| 1042 | # use the original method here and additionally register it in the |
| 1043 | # fake github |
| 1044 | super(FakeGithubConnection, self).addProject(project) |
| 1045 | self.getGithubClient(project).addProject(project) |
| 1046 | |
Jesse Keating | 9021a01 | 2017-08-29 14:45:27 -0700 | [diff] [blame] | 1047 | def getPullBySha(self, sha, project): |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 1048 | prs = list(set([p for p in self.pull_requests.values() if |
Jesse Keating | 9021a01 | 2017-08-29 14:45:27 -0700 | [diff] [blame] | 1049 | sha == p.head_sha and project == p.project])) |
Adam Gandelman | 8c6eeb5 | 2017-01-23 16:31:06 -0800 | [diff] [blame] | 1050 | if len(prs) > 1: |
| 1051 | raise Exception('Multiple pulls found with head sha: %s' % sha) |
| 1052 | pr = prs[0] |
| 1053 | return self.getPull(pr.project, pr.number) |
| 1054 | |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 1055 | def _getPullReviews(self, owner, project, number): |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 1056 | pr = self.pull_requests[number] |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 1057 | return pr.reviews |
| 1058 | |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 1059 | def getRepoPermission(self, project, login): |
| 1060 | owner, proj = project.split('/') |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 1061 | for pr in self.pull_requests.values(): |
Jesse Keating | ae4cd27 | 2017-01-30 17:10:44 -0800 | [diff] [blame] | 1062 | pr_owner, pr_project = pr.project.split('/') |
| 1063 | if (pr_owner == owner and proj == pr_project): |
| 1064 | if login in pr.writers: |
| 1065 | return 'write' |
| 1066 | else: |
| 1067 | return 'read' |
| 1068 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 1069 | def getGitUrl(self, project): |
Tobias Henkel | 054eccc | 2017-12-20 11:36:19 +0100 | [diff] [blame] | 1070 | if self.git_url_with_auth: |
| 1071 | auth_token = ''.join( |
| 1072 | random.choice(string.ascii_lowercase) for x in range(8)) |
| 1073 | prefix = 'file://x-access-token:%s@' % auth_token |
| 1074 | else: |
| 1075 | prefix = '' |
| 1076 | return prefix + os.path.join(self.upstream_root, str(project)) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 1077 | |
Jan Hruban | 6d53c5e | 2015-10-24 03:03:34 +0200 | [diff] [blame] | 1078 | def real_getGitUrl(self, project): |
| 1079 | return super(FakeGithubConnection, self).getGitUrl(project) |
| 1080 | |
Jan Hruban | e252a73 | 2017-01-03 15:03:09 +0100 | [diff] [blame] | 1081 | def commentPull(self, project, pr_number, message): |
Jesse Keating | 08dab8f | 2017-06-21 12:59:23 +0100 | [diff] [blame] | 1082 | # record that this got reported |
| 1083 | self.reports.append((project, pr_number, 'comment')) |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 1084 | pull_request = self.pull_requests[pr_number] |
Wayne | 40f4004 | 2015-06-12 16:56:30 -0700 | [diff] [blame] | 1085 | pull_request.addComment(message) |
| 1086 | |
Jan Hruban | 3b41592 | 2016-02-03 13:10:22 +0100 | [diff] [blame] | 1087 | def mergePull(self, project, pr_number, commit_message='', sha=None): |
Jesse Keating | 08dab8f | 2017-06-21 12:59:23 +0100 | [diff] [blame] | 1088 | # record that this got reported |
| 1089 | self.reports.append((project, pr_number, 'merge')) |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 1090 | pull_request = self.pull_requests[pr_number] |
Jan Hruban | 49bff07 | 2015-11-03 11:45:46 +0100 | [diff] [blame] | 1091 | if self.merge_failure: |
| 1092 | raise Exception('Pull request was not merged') |
| 1093 | if self.merge_not_allowed_count > 0: |
| 1094 | self.merge_not_allowed_count -= 1 |
| 1095 | raise MergeFailure('Merge was not successful due to mergeability' |
| 1096 | ' conflict') |
James E. Blair | 289f593 | 2017-07-27 15:02:29 -0700 | [diff] [blame] | 1097 | pull_request.setMerged(commit_message) |
Jan Hruban | 49bff07 | 2015-11-03 11:45:46 +0100 | [diff] [blame] | 1098 | |
Jesse Keating | 1f7ebe9 | 2017-06-12 17:21:00 -0700 | [diff] [blame] | 1099 | def setCommitStatus(self, project, sha, state, url='', description='', |
| 1100 | context='default', user='zuul'): |
Tobias Henkel | 3c17d5f | 2017-08-03 11:46:54 +0200 | [diff] [blame] | 1101 | # record that this got reported and call original method |
Jesse Keating | 08dab8f | 2017-06-21 12:59:23 +0100 | [diff] [blame] | 1102 | self.reports.append((project, sha, 'status', (user, context, state))) |
Tobias Henkel | 3c17d5f | 2017-08-03 11:46:54 +0200 | [diff] [blame] | 1103 | super(FakeGithubConnection, self).setCommitStatus( |
| 1104 | project, sha, state, |
| 1105 | url=url, description=description, context=context) |
Jan Hruban | e252a73 | 2017-01-03 15:03:09 +0100 | [diff] [blame] | 1106 | |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 1107 | def labelPull(self, project, pr_number, label): |
Jesse Keating | 08dab8f | 2017-06-21 12:59:23 +0100 | [diff] [blame] | 1108 | # record that this got reported |
| 1109 | self.reports.append((project, pr_number, 'label', label)) |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 1110 | pull_request = self.pull_requests[pr_number] |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 1111 | pull_request.addLabel(label) |
| 1112 | |
| 1113 | def unlabelPull(self, project, pr_number, label): |
Jesse Keating | 08dab8f | 2017-06-21 12:59:23 +0100 | [diff] [blame] | 1114 | # record that this got reported |
| 1115 | self.reports.append((project, pr_number, 'unlabel', label)) |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 1116 | pull_request = self.pull_requests[pr_number] |
Jan Hruban | 16ad31f | 2015-11-07 14:39:07 +0100 | [diff] [blame] | 1117 | pull_request.removeLabel(label) |
| 1118 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 1119 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1120 | class BuildHistory(object): |
| 1121 | def __init__(self, **kw): |
| 1122 | self.__dict__.update(kw) |
| 1123 | |
| 1124 | def __repr__(self): |
James E. Blair | 2103778 | 2017-07-19 11:56:55 -0700 | [diff] [blame] | 1125 | return ("<Completed build, result: %s name: %s uuid: %s " |
| 1126 | "changes: %s ref: %s>" % |
| 1127 | (self.result, self.name, self.uuid, |
| 1128 | self.changes, self.ref)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1129 | |
| 1130 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1131 | class FakeStatsd(threading.Thread): |
| 1132 | def __init__(self): |
| 1133 | threading.Thread.__init__(self) |
| 1134 | self.daemon = True |
Monty Taylor | 211883d | 2017-09-06 08:40:47 -0500 | [diff] [blame] | 1135 | self.sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1136 | self.sock.bind(('', 0)) |
| 1137 | self.port = self.sock.getsockname()[1] |
| 1138 | self.wake_read, self.wake_write = os.pipe() |
| 1139 | self.stats = [] |
| 1140 | |
| 1141 | def run(self): |
| 1142 | while True: |
| 1143 | poll = select.poll() |
| 1144 | poll.register(self.sock, select.POLLIN) |
| 1145 | poll.register(self.wake_read, select.POLLIN) |
| 1146 | ret = poll.poll() |
| 1147 | for (fd, event) in ret: |
| 1148 | if fd == self.sock.fileno(): |
| 1149 | data = self.sock.recvfrom(1024) |
| 1150 | if not data: |
| 1151 | return |
| 1152 | self.stats.append(data[0]) |
| 1153 | if fd == self.wake_read: |
| 1154 | return |
| 1155 | |
| 1156 | def stop(self): |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 1157 | os.write(self.wake_write, b'1\n') |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1158 | |
| 1159 | |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1160 | class FakeBuild(object): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1161 | log = logging.getLogger("zuul.test") |
| 1162 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1163 | def __init__(self, executor_server, job): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1164 | self.daemon = True |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1165 | self.executor_server = executor_server |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1166 | self.job = job |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 1167 | self.jobdir = None |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 1168 | self.uuid = job.unique |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1169 | self.parameters = json.loads(job.arguments) |
James E. Blair | 16d96a0 | 2017-06-08 11:32:56 -0700 | [diff] [blame] | 1170 | # TODOv3(jeblair): self.node is really "the label of the node |
| 1171 | # assigned". We should rename it (self.node_label?) if we |
James E. Blair | 34776ee | 2016-08-25 13:53:54 -0700 | [diff] [blame] | 1172 | # keep using it like this, or we may end up exposing more of |
| 1173 | # the complexity around multi-node jobs here |
James E. Blair | 16d96a0 | 2017-06-08 11:32:56 -0700 | [diff] [blame] | 1174 | # (self.nodes[0].label?) |
James E. Blair | 34776ee | 2016-08-25 13:53:54 -0700 | [diff] [blame] | 1175 | self.node = None |
| 1176 | if len(self.parameters.get('nodes')) == 1: |
James E. Blair | 16d96a0 | 2017-06-08 11:32:56 -0700 | [diff] [blame] | 1177 | self.node = self.parameters['nodes'][0]['label'] |
James E. Blair | 74f101b | 2017-07-21 15:32:01 -0700 | [diff] [blame] | 1178 | self.unique = self.parameters['zuul']['build'] |
James E. Blair | e675d68 | 2017-07-21 15:29:35 -0700 | [diff] [blame] | 1179 | self.pipeline = self.parameters['zuul']['pipeline'] |
James E. Blair | e536609 | 2017-07-21 15:30:39 -0700 | [diff] [blame] | 1180 | self.project = self.parameters['zuul']['project']['name'] |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1181 | self.name = self.parameters['job'] |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1182 | self.wait_condition = threading.Condition() |
| 1183 | self.waiting = False |
| 1184 | self.aborted = False |
Paul Belanger | 71d9817 | 2016-11-08 10:56:31 -0500 | [diff] [blame] | 1185 | self.requeue = False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1186 | self.created = time.time() |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1187 | self.changes = None |
James E. Blair | 6193a1f | 2017-07-21 15:13:15 -0700 | [diff] [blame] | 1188 | items = self.parameters['zuul']['items'] |
| 1189 | self.changes = ' '.join(['%s,%s' % (x['change'], x['patchset']) |
| 1190 | for x in items if 'change' in x]) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1191 | |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 1192 | def __repr__(self): |
| 1193 | waiting = '' |
| 1194 | if self.waiting: |
| 1195 | waiting = ' [waiting]' |
Jamie Lennox | d2e3733 | 2016-12-05 15:26:19 +1100 | [diff] [blame] | 1196 | return '<FakeBuild %s:%s %s%s>' % (self.pipeline, self.name, |
| 1197 | self.changes, waiting) |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 1198 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1199 | def release(self): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1200 | """Release this build.""" |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1201 | self.wait_condition.acquire() |
| 1202 | self.wait_condition.notify() |
| 1203 | self.waiting = False |
| 1204 | self.log.debug("Build %s released" % self.unique) |
| 1205 | self.wait_condition.release() |
| 1206 | |
| 1207 | def isWaiting(self): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1208 | """Return whether this build is being held. |
| 1209 | |
| 1210 | :returns: Whether the build is being held. |
| 1211 | :rtype: bool |
| 1212 | """ |
| 1213 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1214 | self.wait_condition.acquire() |
| 1215 | if self.waiting: |
| 1216 | ret = True |
| 1217 | else: |
| 1218 | ret = False |
| 1219 | self.wait_condition.release() |
| 1220 | return ret |
| 1221 | |
| 1222 | def _wait(self): |
| 1223 | self.wait_condition.acquire() |
| 1224 | self.waiting = True |
| 1225 | self.log.debug("Build %s waiting" % self.unique) |
| 1226 | self.wait_condition.wait() |
| 1227 | self.wait_condition.release() |
| 1228 | |
| 1229 | def run(self): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1230 | self.log.debug('Running build %s' % self.unique) |
| 1231 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1232 | if self.executor_server.hold_jobs_in_build: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1233 | self.log.debug('Holding build %s' % self.unique) |
| 1234 | self._wait() |
| 1235 | self.log.debug("Build %s continuing" % self.unique) |
| 1236 | |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 1237 | result = (RecordingAnsibleJob.RESULT_NORMAL, 0) # Success |
James E. Blair | 247cab7 | 2017-07-20 16:52:36 -0700 | [diff] [blame] | 1238 | if self.shouldFail(): |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 1239 | result = (RecordingAnsibleJob.RESULT_NORMAL, 1) # Failure |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1240 | if self.aborted: |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 1241 | result = (RecordingAnsibleJob.RESULT_ABORTED, None) |
Paul Belanger | 71d9817 | 2016-11-08 10:56:31 -0500 | [diff] [blame] | 1242 | if self.requeue: |
James E. Blair | 412fba8 | 2017-01-26 15:00:50 -0800 | [diff] [blame] | 1243 | result = (RecordingAnsibleJob.RESULT_UNREACHABLE, None) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1244 | |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1245 | return result |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1246 | |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 1247 | def shouldFail(self): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1248 | changes = self.executor_server.fail_tests.get(self.name, []) |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 1249 | for change in changes: |
| 1250 | if self.hasChanges(change): |
| 1251 | return True |
| 1252 | return False |
| 1253 | |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1254 | def hasChanges(self, *changes): |
| 1255 | """Return whether this build has certain changes in its git repos. |
| 1256 | |
| 1257 | :arg FakeChange changes: One or more changes (varargs) that |
Clark Boylan | 500992b | 2017-04-03 14:28:24 -0700 | [diff] [blame] | 1258 | are expected to be present (in order) in the git repository of |
| 1259 | the active project. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1260 | |
| 1261 | :returns: Whether the build has the indicated changes. |
| 1262 | :rtype: bool |
| 1263 | |
| 1264 | """ |
Clint Byrum | 3343e3e | 2016-11-15 16:05:03 -0800 | [diff] [blame] | 1265 | for change in changes: |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 1266 | hostname = change.source.canonical_hostname |
James E. Blair | 2a53567 | 2017-04-27 12:03:15 -0700 | [diff] [blame] | 1267 | path = os.path.join(self.jobdir.src_root, hostname, change.project) |
Clint Byrum | 3343e3e | 2016-11-15 16:05:03 -0800 | [diff] [blame] | 1268 | try: |
| 1269 | repo = git.Repo(path) |
| 1270 | except NoSuchPathError as e: |
| 1271 | self.log.debug('%s' % e) |
| 1272 | return False |
James E. Blair | 247cab7 | 2017-07-20 16:52:36 -0700 | [diff] [blame] | 1273 | repo_messages = [c.message.strip() for c in repo.iter_commits()] |
Clint Byrum | 3343e3e | 2016-11-15 16:05:03 -0800 | [diff] [blame] | 1274 | commit_message = '%s-1' % change.subject |
| 1275 | self.log.debug("Checking if build %s has changes; commit_message " |
| 1276 | "%s; repo_messages %s" % (self, commit_message, |
| 1277 | repo_messages)) |
| 1278 | if commit_message not in repo_messages: |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 1279 | self.log.debug(" messages do not match") |
| 1280 | return False |
| 1281 | self.log.debug(" OK") |
| 1282 | return True |
| 1283 | |
James E. Blair | d8af542 | 2017-05-24 13:59:40 -0700 | [diff] [blame] | 1284 | def getWorkspaceRepos(self, projects): |
| 1285 | """Return workspace git repo objects for the listed projects |
| 1286 | |
| 1287 | :arg list projects: A list of strings, each the canonical name |
| 1288 | of a project. |
| 1289 | |
| 1290 | :returns: A dictionary of {name: repo} for every listed |
| 1291 | project. |
| 1292 | :rtype: dict |
| 1293 | |
| 1294 | """ |
| 1295 | |
| 1296 | repos = {} |
| 1297 | for project in projects: |
| 1298 | path = os.path.join(self.jobdir.src_root, project) |
| 1299 | repo = git.Repo(path) |
| 1300 | repos[project] = repo |
| 1301 | return repos |
| 1302 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1303 | |
James E. Blair | 107bb25 | 2017-10-13 15:53:16 -0700 | [diff] [blame] | 1304 | class RecordingAnsibleJob(zuul.executor.server.AnsibleJob): |
| 1305 | def doMergeChanges(self, merger, items, repo_state): |
| 1306 | # Get a merger in order to update the repos involved in this job. |
| 1307 | commit = super(RecordingAnsibleJob, self).doMergeChanges( |
| 1308 | merger, items, repo_state) |
| 1309 | if not commit: # merge conflict |
| 1310 | self.recordResult('MERGER_FAILURE') |
| 1311 | return commit |
| 1312 | |
| 1313 | def recordResult(self, result): |
| 1314 | build = self.executor_server.job_builds[self.job.unique] |
| 1315 | self.executor_server.lock.acquire() |
| 1316 | self.executor_server.build_history.append( |
| 1317 | BuildHistory(name=build.name, result=result, changes=build.changes, |
| 1318 | node=build.node, uuid=build.unique, |
| 1319 | ref=build.parameters['zuul']['ref'], |
| 1320 | parameters=build.parameters, jobdir=build.jobdir, |
| 1321 | pipeline=build.parameters['zuul']['pipeline']) |
| 1322 | ) |
| 1323 | self.executor_server.running_builds.remove(build) |
| 1324 | del self.executor_server.job_builds[self.job.unique] |
| 1325 | self.executor_server.lock.release() |
| 1326 | |
| 1327 | def runPlaybooks(self, args): |
| 1328 | build = self.executor_server.job_builds[self.job.unique] |
| 1329 | build.jobdir = self.jobdir |
| 1330 | |
| 1331 | result = super(RecordingAnsibleJob, self).runPlaybooks(args) |
| 1332 | self.recordResult(result) |
| 1333 | return result |
| 1334 | |
James E. Blair | a86aaf1 | 2017-10-15 20:59:50 -0700 | [diff] [blame] | 1335 | def runAnsible(self, cmd, timeout, playbook, wrapped=True): |
James E. Blair | 107bb25 | 2017-10-13 15:53:16 -0700 | [diff] [blame] | 1336 | build = self.executor_server.job_builds[self.job.unique] |
| 1337 | |
| 1338 | if self.executor_server._run_ansible: |
| 1339 | result = super(RecordingAnsibleJob, self).runAnsible( |
James E. Blair | a86aaf1 | 2017-10-15 20:59:50 -0700 | [diff] [blame] | 1340 | cmd, timeout, playbook, wrapped) |
James E. Blair | 107bb25 | 2017-10-13 15:53:16 -0700 | [diff] [blame] | 1341 | else: |
| 1342 | if playbook.path: |
| 1343 | result = build.run() |
| 1344 | else: |
| 1345 | result = (self.RESULT_NORMAL, 0) |
| 1346 | return result |
| 1347 | |
| 1348 | def getHostList(self, args): |
| 1349 | self.log.debug("hostlist") |
| 1350 | hosts = super(RecordingAnsibleJob, self).getHostList(args) |
| 1351 | for host in hosts: |
Tobias Henkel | c504321 | 2017-09-08 08:53:47 +0200 | [diff] [blame] | 1352 | if not host['host_vars'].get('ansible_connection'): |
| 1353 | host['host_vars']['ansible_connection'] = 'local' |
James E. Blair | 107bb25 | 2017-10-13 15:53:16 -0700 | [diff] [blame] | 1354 | |
| 1355 | hosts.append(dict( |
James E. Blair | 67cd859 | 2018-02-14 09:30:07 -0800 | [diff] [blame] | 1356 | name='localhost', |
James E. Blair | 107bb25 | 2017-10-13 15:53:16 -0700 | [diff] [blame] | 1357 | host_vars=dict(ansible_connection='local'), |
| 1358 | host_keys=[])) |
| 1359 | return hosts |
| 1360 | |
| 1361 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1362 | class RecordingExecutorServer(zuul.executor.server.ExecutorServer): |
| 1363 | """An Ansible executor to be used in tests. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1364 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1365 | :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] | 1366 | they will report that they have started but then pause until |
| 1367 | released before reporting completion. This attribute may be |
| 1368 | changed at any time and will take effect for subsequently |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1369 | executed builds, but previously held builds will still need to |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1370 | be explicitly released. |
| 1371 | |
| 1372 | """ |
James E. Blair | faf8198 | 2017-10-10 15:42:26 -0700 | [diff] [blame] | 1373 | |
| 1374 | _job_class = RecordingAnsibleJob |
| 1375 | |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1376 | def __init__(self, *args, **kw): |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1377 | self._run_ansible = kw.pop('_run_ansible', False) |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 1378 | self._test_root = kw.pop('_test_root', False) |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1379 | super(RecordingExecutorServer, self).__init__(*args, **kw) |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1380 | self.hold_jobs_in_build = False |
| 1381 | self.lock = threading.Lock() |
| 1382 | self.running_builds = [] |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 1383 | self.build_history = [] |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1384 | self.fail_tests = {} |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 1385 | self.job_builds = {} |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1386 | |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 1387 | def failJob(self, name, change): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1388 | """Instruct the executor to report matching builds as failures. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1389 | |
| 1390 | :arg str name: The name of the job to fail. |
James E. Blair | a5dba23 | 2016-08-08 15:53:24 -0700 | [diff] [blame] | 1391 | :arg Change change: The :py:class:`~tests.base.FakeChange` |
| 1392 | instance which should cause the job to fail. This job |
| 1393 | will also fail for changes depending on this change. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1394 | |
| 1395 | """ |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1396 | l = self.fail_tests.get(name, []) |
| 1397 | l.append(change) |
| 1398 | self.fail_tests[name] = l |
James E. Blair | f5dbd00 | 2015-12-23 15:26:17 -0800 | [diff] [blame] | 1399 | |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 1400 | def release(self, regex=None): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1401 | """Release a held build. |
| 1402 | |
| 1403 | :arg str regex: A regular expression which, if supplied, will |
| 1404 | cause only builds with matching names to be released. If |
| 1405 | not supplied, all builds will be released. |
| 1406 | |
| 1407 | """ |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 1408 | builds = self.running_builds[:] |
| 1409 | self.log.debug("Releasing build %s (%s)" % (regex, |
| 1410 | len(self.running_builds))) |
| 1411 | for build in builds: |
| 1412 | if not regex or re.match(regex, build.name): |
| 1413 | self.log.debug("Releasing build %s" % |
James E. Blair | 74f101b | 2017-07-21 15:32:01 -0700 | [diff] [blame] | 1414 | (build.parameters['zuul']['build'])) |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 1415 | build.release() |
| 1416 | else: |
| 1417 | self.log.debug("Not releasing build %s" % |
James E. Blair | 74f101b | 2017-07-21 15:32:01 -0700 | [diff] [blame] | 1418 | (build.parameters['zuul']['build'])) |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 1419 | self.log.debug("Done releasing builds %s (%s)" % |
| 1420 | (regex, len(self.running_builds))) |
| 1421 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1422 | def executeJob(self, job): |
James E. Blair | 34776ee | 2016-08-25 13:53:54 -0700 | [diff] [blame] | 1423 | build = FakeBuild(self, job) |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1424 | job.build = build |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 1425 | self.running_builds.append(build) |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 1426 | self.job_builds[job.unique] = build |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 1427 | args = json.loads(job.arguments) |
Monty Taylor | d13bc36 | 2017-06-30 13:11:37 -0500 | [diff] [blame] | 1428 | args['zuul']['_test'] = dict(test_root=self._test_root) |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 1429 | job.arguments = json.dumps(args) |
James E. Blair | faf8198 | 2017-10-10 15:42:26 -0700 | [diff] [blame] | 1430 | super(RecordingExecutorServer, self).executeJob(job) |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 1431 | |
| 1432 | def stopJob(self, job): |
| 1433 | self.log.debug("handle stop") |
| 1434 | parameters = json.loads(job.arguments) |
| 1435 | uuid = parameters['uuid'] |
| 1436 | for build in self.running_builds: |
| 1437 | if build.unique == uuid: |
| 1438 | build.aborted = True |
| 1439 | build.release() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1440 | super(RecordingExecutorServer, self).stopJob(job) |
James E. Blair | ab7132b | 2016-08-05 12:36:22 -0700 | [diff] [blame] | 1441 | |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 1442 | def stop(self): |
| 1443 | for build in self.running_builds: |
| 1444 | build.release() |
| 1445 | super(RecordingExecutorServer, self).stop() |
| 1446 | |
Joshua Hesketh | 50c2178 | 2016-10-13 21:34:14 +1100 | [diff] [blame] | 1447 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1448 | class FakeGearmanServer(gear.Server): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1449 | """A Gearman server for use in tests. |
| 1450 | |
| 1451 | :ivar bool hold_jobs_in_queue: If true, submitted jobs will be |
| 1452 | added to the queue but will not be distributed to workers |
| 1453 | until released. This attribute may be changed at any time and |
| 1454 | will take effect for subsequently enqueued jobs, but |
| 1455 | previously held jobs will still need to be explicitly |
| 1456 | released. |
| 1457 | |
| 1458 | """ |
| 1459 | |
Paul Belanger | 0a21f0a | 2017-06-13 13:14:42 -0400 | [diff] [blame] | 1460 | def __init__(self, use_ssl=False): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1461 | self.hold_jobs_in_queue = False |
James E. Blair | a615c36 | 2017-10-02 17:34:42 -0700 | [diff] [blame] | 1462 | self.hold_merge_jobs_in_queue = False |
Fabien Boucher | 5225231 | 2018-01-18 19:54:34 +0100 | [diff] [blame] | 1463 | self.jobs_history = [] |
Paul Belanger | 0a21f0a | 2017-06-13 13:14:42 -0400 | [diff] [blame] | 1464 | if use_ssl: |
| 1465 | ssl_ca = os.path.join(FIXTURE_DIR, 'gearman/root-ca.pem') |
| 1466 | ssl_cert = os.path.join(FIXTURE_DIR, 'gearman/server.pem') |
| 1467 | ssl_key = os.path.join(FIXTURE_DIR, 'gearman/server.key') |
| 1468 | else: |
| 1469 | ssl_ca = None |
| 1470 | ssl_cert = None |
| 1471 | ssl_key = None |
| 1472 | |
| 1473 | super(FakeGearmanServer, self).__init__(0, ssl_key=ssl_key, |
| 1474 | ssl_cert=ssl_cert, |
| 1475 | ssl_ca=ssl_ca) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1476 | |
| 1477 | def getJobForConnection(self, connection, peek=False): |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 1478 | for job_queue in [self.high_queue, self.normal_queue, self.low_queue]: |
| 1479 | for job in job_queue: |
Fabien Boucher | 5225231 | 2018-01-18 19:54:34 +0100 | [diff] [blame] | 1480 | self.jobs_history.append(job) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1481 | if not hasattr(job, 'waiting'): |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 1482 | if job.name.startswith(b'executor:execute'): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1483 | job.waiting = self.hold_jobs_in_queue |
James E. Blair | a615c36 | 2017-10-02 17:34:42 -0700 | [diff] [blame] | 1484 | elif job.name.startswith(b'merger:'): |
| 1485 | job.waiting = self.hold_merge_jobs_in_queue |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1486 | else: |
| 1487 | job.waiting = False |
| 1488 | if job.waiting: |
| 1489 | continue |
| 1490 | if job.name in connection.functions: |
| 1491 | if not peek: |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 1492 | job_queue.remove(job) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1493 | connection.related_jobs[job.handle] = job |
| 1494 | job.worker_connection = connection |
| 1495 | job.running = True |
| 1496 | return job |
| 1497 | return None |
| 1498 | |
| 1499 | def release(self, regex=None): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1500 | """Release a held job. |
| 1501 | |
| 1502 | :arg str regex: A regular expression which, if supplied, will |
| 1503 | cause only jobs with matching names to be released. If |
| 1504 | not supplied, all jobs will be released. |
| 1505 | """ |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1506 | released = False |
| 1507 | qlen = (len(self.high_queue) + len(self.normal_queue) + |
| 1508 | len(self.low_queue)) |
| 1509 | self.log.debug("releasing queued job %s (%s)" % (regex, qlen)) |
| 1510 | for job in self.getQueue(): |
James E. Blair | a615c36 | 2017-10-02 17:34:42 -0700 | [diff] [blame] | 1511 | match = False |
| 1512 | if job.name == b'executor:execute': |
| 1513 | parameters = json.loads(job.arguments.decode('utf8')) |
| 1514 | if not regex or re.match(regex, parameters.get('job')): |
| 1515 | match = True |
James E. Blair | 29c7700 | 2017-10-05 14:56:35 -0700 | [diff] [blame] | 1516 | if job.name.startswith(b'merger:'): |
James E. Blair | a615c36 | 2017-10-02 17:34:42 -0700 | [diff] [blame] | 1517 | if not regex: |
| 1518 | match = True |
| 1519 | if match: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1520 | self.log.debug("releasing queued job %s" % |
| 1521 | job.unique) |
| 1522 | job.waiting = False |
| 1523 | released = True |
| 1524 | else: |
| 1525 | self.log.debug("not releasing queued job %s" % |
| 1526 | job.unique) |
| 1527 | if released: |
| 1528 | self.wakeConnections() |
| 1529 | qlen = (len(self.high_queue) + len(self.normal_queue) + |
| 1530 | len(self.low_queue)) |
| 1531 | self.log.debug("done releasing queued jobs %s (%s)" % (regex, qlen)) |
| 1532 | |
| 1533 | |
| 1534 | class FakeSMTP(object): |
| 1535 | log = logging.getLogger('zuul.FakeSMTP') |
| 1536 | |
| 1537 | def __init__(self, messages, server, port): |
| 1538 | self.server = server |
| 1539 | self.port = port |
| 1540 | self.messages = messages |
| 1541 | |
| 1542 | def sendmail(self, from_email, to_email, msg): |
| 1543 | self.log.info("Sending email from %s, to %s, with msg %s" % ( |
| 1544 | from_email, to_email, msg)) |
| 1545 | |
| 1546 | headers = msg.split('\n\n', 1)[0] |
| 1547 | body = msg.split('\n\n', 1)[1] |
| 1548 | |
| 1549 | self.messages.append(dict( |
| 1550 | from_email=from_email, |
| 1551 | to_email=to_email, |
| 1552 | msg=msg, |
| 1553 | headers=headers, |
| 1554 | body=body, |
| 1555 | )) |
| 1556 | |
| 1557 | return True |
| 1558 | |
| 1559 | def quit(self): |
| 1560 | return True |
| 1561 | |
| 1562 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1563 | class FakeNodepool(object): |
| 1564 | REQUEST_ROOT = '/nodepool/requests' |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 1565 | NODE_ROOT = '/nodepool/nodes' |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1566 | |
| 1567 | log = logging.getLogger("zuul.test.FakeNodepool") |
| 1568 | |
| 1569 | def __init__(self, host, port, chroot): |
| 1570 | self.client = kazoo.client.KazooClient( |
| 1571 | hosts='%s:%s%s' % (host, port, chroot)) |
| 1572 | self.client.start() |
| 1573 | self._running = True |
James E. Blair | 15be0e1 | 2017-01-03 13:45:20 -0800 | [diff] [blame] | 1574 | self.paused = False |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1575 | self.thread = threading.Thread(target=self.run) |
| 1576 | self.thread.daemon = True |
| 1577 | self.thread.start() |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 1578 | self.fail_requests = set() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1579 | |
| 1580 | def stop(self): |
| 1581 | self._running = False |
| 1582 | self.thread.join() |
| 1583 | self.client.stop() |
| 1584 | self.client.close() |
| 1585 | |
| 1586 | def run(self): |
| 1587 | while self._running: |
James E. Blair | cbbce0d | 2017-05-19 07:28:29 -0700 | [diff] [blame] | 1588 | try: |
| 1589 | self._run() |
| 1590 | except Exception: |
| 1591 | self.log.exception("Error in fake nodepool:") |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1592 | time.sleep(0.1) |
| 1593 | |
| 1594 | def _run(self): |
James E. Blair | 15be0e1 | 2017-01-03 13:45:20 -0800 | [diff] [blame] | 1595 | if self.paused: |
| 1596 | return |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1597 | for req in self.getNodeRequests(): |
| 1598 | self.fulfillRequest(req) |
| 1599 | |
| 1600 | def getNodeRequests(self): |
| 1601 | try: |
| 1602 | reqids = self.client.get_children(self.REQUEST_ROOT) |
| 1603 | except kazoo.exceptions.NoNodeError: |
| 1604 | return [] |
| 1605 | reqs = [] |
| 1606 | for oid in sorted(reqids): |
| 1607 | path = self.REQUEST_ROOT + '/' + oid |
James E. Blair | 0ef64f8 | 2017-02-02 11:25:16 -0800 | [diff] [blame] | 1608 | try: |
| 1609 | data, stat = self.client.get(path) |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 1610 | data = json.loads(data.decode('utf8')) |
James E. Blair | 0ef64f8 | 2017-02-02 11:25:16 -0800 | [diff] [blame] | 1611 | data['_oid'] = oid |
| 1612 | reqs.append(data) |
| 1613 | except kazoo.exceptions.NoNodeError: |
| 1614 | pass |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1615 | return reqs |
| 1616 | |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 1617 | def getNodes(self): |
| 1618 | try: |
| 1619 | nodeids = self.client.get_children(self.NODE_ROOT) |
| 1620 | except kazoo.exceptions.NoNodeError: |
| 1621 | return [] |
| 1622 | nodes = [] |
| 1623 | for oid in sorted(nodeids): |
| 1624 | path = self.NODE_ROOT + '/' + oid |
| 1625 | data, stat = self.client.get(path) |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 1626 | data = json.loads(data.decode('utf8')) |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 1627 | data['_oid'] = oid |
| 1628 | try: |
| 1629 | lockfiles = self.client.get_children(path + '/lock') |
| 1630 | except kazoo.exceptions.NoNodeError: |
| 1631 | lockfiles = [] |
| 1632 | if lockfiles: |
| 1633 | data['_lock'] = True |
| 1634 | else: |
| 1635 | data['_lock'] = False |
| 1636 | nodes.append(data) |
| 1637 | return nodes |
| 1638 | |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1639 | def makeNode(self, request_id, node_type): |
| 1640 | now = time.time() |
| 1641 | path = '/nodepool/nodes/' |
| 1642 | data = dict(type=node_type, |
Paul Belanger | d28c755 | 2017-08-11 13:10:38 -0400 | [diff] [blame] | 1643 | cloud='test-cloud', |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1644 | provider='test-provider', |
| 1645 | region='test-region', |
Paul Belanger | 30ba93a | 2017-03-16 16:28:10 -0400 | [diff] [blame] | 1646 | az='test-az', |
Monty Taylor | 56f6133 | 2017-04-11 05:38:12 -0500 | [diff] [blame] | 1647 | interface_ip='127.0.0.1', |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1648 | public_ipv4='127.0.0.1', |
| 1649 | private_ipv4=None, |
| 1650 | public_ipv6=None, |
| 1651 | allocated_to=request_id, |
| 1652 | state='ready', |
| 1653 | state_time=now, |
| 1654 | created_time=now, |
| 1655 | updated_time=now, |
| 1656 | image_id=None, |
Paul Belanger | c5bf375 | 2017-03-16 19:38:43 -0400 | [diff] [blame] | 1657 | host_keys=["fake-key1", "fake-key2"], |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1658 | executor='fake-nodepool') |
Jamie Lennox | d4006d6 | 2017-04-06 10:34:04 +1000 | [diff] [blame] | 1659 | if 'fakeuser' in node_type: |
| 1660 | data['username'] = 'fakeuser' |
Tobias Henkel | c504321 | 2017-09-08 08:53:47 +0200 | [diff] [blame] | 1661 | if 'windows' in node_type: |
| 1662 | data['connection_type'] = 'winrm' |
Ricardo Carrillo Cruz | 6eda439 | 2017-12-27 19:34:47 +0100 | [diff] [blame] | 1663 | if 'network' in node_type: |
| 1664 | data['connection_type'] = 'network_cli' |
Tobias Henkel | c504321 | 2017-09-08 08:53:47 +0200 | [diff] [blame] | 1665 | |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 1666 | data = json.dumps(data).encode('utf8') |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1667 | path = self.client.create(path, data, |
| 1668 | makepath=True, |
| 1669 | sequence=True) |
| 1670 | nodeid = path.split("/")[-1] |
| 1671 | return nodeid |
| 1672 | |
Krzysztof Klimonda | 37d5403 | 2017-10-25 12:16:47 +0200 | [diff] [blame] | 1673 | def removeNode(self, node): |
| 1674 | path = self.NODE_ROOT + '/' + node["_oid"] |
| 1675 | self.client.delete(path, recursive=True) |
| 1676 | |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 1677 | def addFailRequest(self, request): |
| 1678 | self.fail_requests.add(request['_oid']) |
| 1679 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1680 | def fulfillRequest(self, request): |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 1681 | if request['state'] != 'requested': |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1682 | return |
| 1683 | request = request.copy() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1684 | oid = request['_oid'] |
| 1685 | del request['_oid'] |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1686 | |
James E. Blair | 6ab79e0 | 2017-01-06 10:10:17 -0800 | [diff] [blame] | 1687 | if oid in self.fail_requests: |
| 1688 | request['state'] = 'failed' |
| 1689 | else: |
| 1690 | request['state'] = 'fulfilled' |
| 1691 | nodes = [] |
| 1692 | for node in request['node_types']: |
| 1693 | nodeid = self.makeNode(oid, node) |
| 1694 | nodes.append(nodeid) |
| 1695 | request['nodes'] = nodes |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1696 | |
James E. Blair | a38c28e | 2017-01-04 10:33:20 -0800 | [diff] [blame] | 1697 | request['state_time'] = time.time() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1698 | path = self.REQUEST_ROOT + '/' + oid |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 1699 | data = json.dumps(request).encode('utf8') |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1700 | self.log.debug("Fulfilling node request: %s %s" % (oid, data)) |
James E. Blair | cbbce0d | 2017-05-19 07:28:29 -0700 | [diff] [blame] | 1701 | try: |
| 1702 | self.client.set(path, data) |
| 1703 | except kazoo.exceptions.NoNodeError: |
| 1704 | self.log.debug("Node request %s %s disappeared" % (oid, data)) |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1705 | |
| 1706 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1707 | class ChrootedKazooFixture(fixtures.Fixture): |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 1708 | def __init__(self, test_id): |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1709 | super(ChrootedKazooFixture, self).__init__() |
| 1710 | |
| 1711 | zk_host = os.environ.get('NODEPOOL_ZK_HOST', 'localhost') |
| 1712 | if ':' in zk_host: |
| 1713 | host, port = zk_host.split(':') |
| 1714 | else: |
| 1715 | host = zk_host |
| 1716 | port = None |
| 1717 | |
| 1718 | self.zookeeper_host = host |
| 1719 | |
| 1720 | if not port: |
| 1721 | self.zookeeper_port = 2181 |
| 1722 | else: |
| 1723 | self.zookeeper_port = int(port) |
| 1724 | |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 1725 | self.test_id = test_id |
| 1726 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1727 | def _setUp(self): |
| 1728 | # Make sure the test chroot paths do not conflict |
| 1729 | random_bits = ''.join(random.choice(string.ascii_lowercase + |
| 1730 | string.ascii_uppercase) |
| 1731 | for x in range(8)) |
| 1732 | |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 1733 | 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] | 1734 | self.zookeeper_chroot = "/nodepool_test/%s" % rand_test_path |
| 1735 | |
Clark Boylan | 7f5f1ec | 2017-04-07 17:39:56 -0700 | [diff] [blame] | 1736 | self.addCleanup(self._cleanup) |
| 1737 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1738 | # Ensure the chroot path exists and clean up any pre-existing znodes. |
| 1739 | _tmp_client = kazoo.client.KazooClient( |
| 1740 | hosts='%s:%s' % (self.zookeeper_host, self.zookeeper_port)) |
| 1741 | _tmp_client.start() |
| 1742 | |
| 1743 | if _tmp_client.exists(self.zookeeper_chroot): |
| 1744 | _tmp_client.delete(self.zookeeper_chroot, recursive=True) |
| 1745 | |
| 1746 | _tmp_client.ensure_path(self.zookeeper_chroot) |
| 1747 | _tmp_client.stop() |
| 1748 | _tmp_client.close() |
| 1749 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1750 | def _cleanup(self): |
| 1751 | '''Remove the chroot path.''' |
| 1752 | # Need a non-chroot'ed client to remove the chroot path |
| 1753 | _tmp_client = kazoo.client.KazooClient( |
| 1754 | hosts='%s:%s' % (self.zookeeper_host, self.zookeeper_port)) |
| 1755 | _tmp_client.start() |
| 1756 | _tmp_client.delete(self.zookeeper_chroot, recursive=True) |
| 1757 | _tmp_client.stop() |
Clark Boylan | 7f5f1ec | 2017-04-07 17:39:56 -0700 | [diff] [blame] | 1758 | _tmp_client.close() |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 1759 | |
| 1760 | |
Monty Taylor | 4a781a7 | 2017-07-25 07:28:04 -0400 | [diff] [blame] | 1761 | class WebProxyFixture(fixtures.Fixture): |
| 1762 | def __init__(self, rules): |
| 1763 | super(WebProxyFixture, self).__init__() |
| 1764 | self.rules = rules |
| 1765 | |
| 1766 | def _setUp(self): |
| 1767 | rules = self.rules |
| 1768 | |
| 1769 | class Proxy(http.server.SimpleHTTPRequestHandler): |
| 1770 | def do_GET(self): |
| 1771 | path = self.path |
| 1772 | for (pattern, replace) in rules: |
| 1773 | path = re.sub(pattern, replace, path) |
| 1774 | try: |
| 1775 | remote = urllib.request.urlopen(path) |
| 1776 | except urllib.error.HTTPError as e: |
| 1777 | self.send_response(e.code) |
| 1778 | self.end_headers() |
| 1779 | return |
| 1780 | self.send_response(int(remote.getcode())) |
| 1781 | for header in remote.info(): |
| 1782 | self.send_header(header, remote.info()[header]) |
| 1783 | self.end_headers() |
| 1784 | self.wfile.write(remote.read()) |
| 1785 | |
| 1786 | self.httpd = socketserver.ThreadingTCPServer(('', 0), Proxy) |
| 1787 | self.port = self.httpd.socket.getsockname()[1] |
| 1788 | self.thread = threading.Thread(target=self.httpd.serve_forever) |
| 1789 | self.thread.start() |
| 1790 | self.addCleanup(self._cleanup) |
| 1791 | |
| 1792 | def _cleanup(self): |
| 1793 | self.httpd.shutdown() |
| 1794 | self.thread.join() |
| 1795 | |
| 1796 | |
| 1797 | class ZuulWebFixture(fixtures.Fixture): |
| 1798 | def __init__(self, gearman_server_port): |
| 1799 | super(ZuulWebFixture, self).__init__() |
| 1800 | self.gearman_server_port = gearman_server_port |
| 1801 | |
| 1802 | def _setUp(self): |
| 1803 | # Start the web server |
| 1804 | self.web = zuul.web.ZuulWeb( |
| 1805 | listen_address='127.0.0.1', listen_port=0, |
| 1806 | gear_server='127.0.0.1', gear_port=self.gearman_server_port) |
| 1807 | loop = asyncio.new_event_loop() |
| 1808 | loop.set_debug(True) |
| 1809 | ws_thread = threading.Thread(target=self.web.run, args=(loop,)) |
| 1810 | ws_thread.start() |
| 1811 | self.addCleanup(loop.close) |
| 1812 | self.addCleanup(ws_thread.join) |
| 1813 | self.addCleanup(self.web.stop) |
| 1814 | |
| 1815 | self.host = 'localhost' |
| 1816 | # Wait until web server is started |
| 1817 | while True: |
| 1818 | time.sleep(0.1) |
| 1819 | if self.web.server is None: |
| 1820 | continue |
| 1821 | self.port = self.web.server.sockets[0].getsockname()[1] |
| 1822 | try: |
| 1823 | with socket.create_connection((self.host, self.port)): |
| 1824 | break |
| 1825 | except ConnectionRefusedError: |
| 1826 | pass |
| 1827 | |
| 1828 | |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 1829 | class MySQLSchemaFixture(fixtures.Fixture): |
| 1830 | def setUp(self): |
| 1831 | super(MySQLSchemaFixture, self).setUp() |
| 1832 | |
| 1833 | random_bits = ''.join(random.choice(string.ascii_lowercase + |
| 1834 | string.ascii_uppercase) |
| 1835 | for x in range(8)) |
| 1836 | self.name = '%s_%s' % (random_bits, os.getpid()) |
| 1837 | self.passwd = uuid.uuid4().hex |
| 1838 | db = pymysql.connect(host="localhost", |
| 1839 | user="openstack_citest", |
| 1840 | passwd="openstack_citest", |
| 1841 | db="openstack_citest") |
| 1842 | cur = db.cursor() |
| 1843 | cur.execute("create database %s" % self.name) |
| 1844 | cur.execute( |
| 1845 | "grant all on %s.* to '%s'@'localhost' identified by '%s'" % |
| 1846 | (self.name, self.name, self.passwd)) |
| 1847 | cur.execute("flush privileges") |
| 1848 | |
| 1849 | self.dburi = 'mysql+pymysql://%s:%s@localhost/%s' % (self.name, |
| 1850 | self.passwd, |
| 1851 | self.name) |
| 1852 | self.addDetail('dburi', testtools.content.text_content(self.dburi)) |
| 1853 | self.addCleanup(self.cleanup) |
| 1854 | |
| 1855 | def cleanup(self): |
| 1856 | db = pymysql.connect(host="localhost", |
| 1857 | user="openstack_citest", |
| 1858 | passwd="openstack_citest", |
| 1859 | db="openstack_citest") |
| 1860 | cur = db.cursor() |
| 1861 | cur.execute("drop database %s" % self.name) |
| 1862 | cur.execute("drop user '%s'@'localhost'" % self.name) |
| 1863 | cur.execute("flush privileges") |
| 1864 | |
| 1865 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1866 | class BaseTestCase(testtools.TestCase): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1867 | log = logging.getLogger("zuul.test") |
James E. Blair | 267e516 | 2017-04-07 10:08:20 -0700 | [diff] [blame] | 1868 | wait_timeout = 30 |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1869 | |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1870 | def attachLogs(self, *args): |
| 1871 | def reader(): |
| 1872 | self._log_stream.seek(0) |
| 1873 | while True: |
| 1874 | x = self._log_stream.read(4096) |
| 1875 | if not x: |
| 1876 | break |
| 1877 | yield x.encode('utf8') |
| 1878 | content = testtools.content.content_from_reader( |
| 1879 | reader, |
| 1880 | testtools.content_type.UTF8_TEXT, |
| 1881 | False) |
| 1882 | self.addDetail('logging', content) |
| 1883 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1884 | def setUp(self): |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1885 | super(BaseTestCase, self).setUp() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 1886 | test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) |
| 1887 | try: |
| 1888 | test_timeout = int(test_timeout) |
| 1889 | except ValueError: |
| 1890 | # If timeout value is invalid do not set a timeout. |
| 1891 | test_timeout = 0 |
| 1892 | if test_timeout > 0: |
| 1893 | self.useFixture(fixtures.Timeout(test_timeout, gentle=False)) |
| 1894 | |
| 1895 | if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or |
| 1896 | os.environ.get('OS_STDOUT_CAPTURE') == '1'): |
| 1897 | stdout = self.useFixture(fixtures.StringStream('stdout')).stream |
| 1898 | self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) |
| 1899 | if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or |
| 1900 | os.environ.get('OS_STDERR_CAPTURE') == '1'): |
| 1901 | stderr = self.useFixture(fixtures.StringStream('stderr')).stream |
| 1902 | self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) |
| 1903 | if (os.environ.get('OS_LOG_CAPTURE') == 'True' or |
| 1904 | os.environ.get('OS_LOG_CAPTURE') == '1'): |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1905 | self._log_stream = StringIO() |
| 1906 | self.addOnException(self.attachLogs) |
| 1907 | else: |
| 1908 | self._log_stream = sys.stdout |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1909 | |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1910 | handler = logging.StreamHandler(self._log_stream) |
| 1911 | formatter = logging.Formatter('%(asctime)s %(name)-32s ' |
| 1912 | '%(levelname)-8s %(message)s') |
| 1913 | handler.setFormatter(formatter) |
| 1914 | |
| 1915 | logger = logging.getLogger() |
| 1916 | logger.setLevel(logging.DEBUG) |
| 1917 | logger.addHandler(handler) |
| 1918 | |
Clark Boylan | 3410d53 | 2017-04-25 12:35:29 -0700 | [diff] [blame] | 1919 | # Make sure we don't carry old handlers around in process state |
| 1920 | # which slows down test runs |
| 1921 | self.addCleanup(logger.removeHandler, handler) |
| 1922 | self.addCleanup(handler.close) |
| 1923 | self.addCleanup(handler.flush) |
| 1924 | |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1925 | # NOTE(notmorgan): Extract logging overrides for specific |
| 1926 | # libraries from the OS_LOG_DEFAULTS env and create loggers |
| 1927 | # for each. This is used to limit the output during test runs |
| 1928 | # from libraries that zuul depends on such as gear. |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1929 | log_defaults_from_env = os.environ.get( |
| 1930 | 'OS_LOG_DEFAULTS', |
Monty Taylor | 9961c03 | 2018-02-19 16:37:51 -0600 | [diff] [blame] | 1931 | 'git.cmd=INFO,kazoo.client=WARNING,gear=INFO') |
Morgan Fainberg | d34e0b4 | 2016-06-09 19:10:38 -0700 | [diff] [blame] | 1932 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1933 | if log_defaults_from_env: |
| 1934 | for default in log_defaults_from_env.split(','): |
| 1935 | try: |
| 1936 | name, level_str = default.split('=', 1) |
| 1937 | level = getattr(logging, level_str, logging.DEBUG) |
James E. Blair | 1c236df | 2017-02-01 14:07:24 -0800 | [diff] [blame] | 1938 | logger = logging.getLogger(name) |
| 1939 | logger.setLevel(level) |
| 1940 | logger.addHandler(handler) |
| 1941 | logger.propagate = False |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 1942 | except ValueError: |
| 1943 | # NOTE(notmorgan): Invalid format of the log default, |
| 1944 | # skip and don't try and apply a logger for the |
| 1945 | # specified module |
| 1946 | pass |
Morgan Fainberg | d34e0b4 | 2016-06-09 19:10:38 -0700 | [diff] [blame] | 1947 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 1948 | |
| 1949 | class ZuulTestCase(BaseTestCase): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1950 | """A test case with a functioning Zuul. |
| 1951 | |
| 1952 | The following class variables are used during test setup and can |
| 1953 | be overidden by subclasses but are effectively read-only once a |
| 1954 | test method starts running: |
| 1955 | |
| 1956 | :cvar str config_file: This points to the main zuul config file |
| 1957 | within the fixtures directory. Subclasses may override this |
| 1958 | to obtain a different behavior. |
| 1959 | |
| 1960 | :cvar str tenant_config_file: This is the tenant config file |
| 1961 | (which specifies from what git repos the configuration should |
| 1962 | be loaded). It defaults to the value specified in |
| 1963 | `config_file` but can be overidden by subclasses to obtain a |
| 1964 | different tenant/project layout while using the standard main |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 1965 | configuration. See also the :py:func:`simple_layout` |
| 1966 | decorator. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1967 | |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 1968 | :cvar bool create_project_keys: Indicates whether Zuul should |
| 1969 | auto-generate keys for each project, or whether the test |
| 1970 | infrastructure should insert dummy keys to save time during |
| 1971 | startup. Defaults to False. |
| 1972 | |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1973 | The following are instance variables that are useful within test |
| 1974 | methods: |
| 1975 | |
| 1976 | :ivar FakeGerritConnection fake_<connection>: |
| 1977 | A :py:class:`~tests.base.FakeGerritConnection` will be |
| 1978 | instantiated for each connection present in the config file |
| 1979 | and stored here. For instance, `fake_gerrit` will hold the |
| 1980 | FakeGerritConnection object for a connection named `gerrit`. |
| 1981 | |
| 1982 | :ivar FakeGearmanServer gearman_server: An instance of |
| 1983 | :py:class:`~tests.base.FakeGearmanServer` which is the Gearman |
| 1984 | server that all of the Zuul components in this test use to |
| 1985 | communicate with each other. |
| 1986 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1987 | :ivar RecordingExecutorServer executor_server: An instance of |
| 1988 | :py:class:`~tests.base.RecordingExecutorServer` which is the |
| 1989 | Ansible execute server used to run jobs for this test. |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 1990 | |
| 1991 | :ivar list builds: A list of :py:class:`~tests.base.FakeBuild` objects |
| 1992 | representing currently running builds. They are appended to |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 1993 | 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] | 1994 | list upon completion. |
| 1995 | |
| 1996 | :ivar list history: A list of :py:class:`~tests.base.BuildHistory` |
| 1997 | objects representing completed builds. They are appended to |
| 1998 | the list in the order they complete. |
| 1999 | |
| 2000 | """ |
| 2001 | |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 2002 | config_file = 'zuul.conf' |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 2003 | run_ansible = False |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2004 | create_project_keys = False |
Paul Belanger | 0a21f0a | 2017-06-13 13:14:42 -0400 | [diff] [blame] | 2005 | use_ssl = False |
Tobias Henkel | 054eccc | 2017-12-20 11:36:19 +0100 | [diff] [blame] | 2006 | git_url_with_auth = False |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2007 | |
| 2008 | def _startMerger(self): |
| 2009 | self.merge_server = zuul.merger.server.MergeServer(self.config, |
| 2010 | self.connections) |
| 2011 | self.merge_server.start() |
| 2012 | |
Maru Newby | 3fe5f85 | 2015-01-13 04:22:14 +0000 | [diff] [blame] | 2013 | def setUp(self): |
| 2014 | super(ZuulTestCase, self).setUp() |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 2015 | |
| 2016 | self.setupZK() |
| 2017 | |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 2018 | if not KEEP_TEMPDIRS: |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2019 | tmp_root = self.useFixture(fixtures.TempDir( |
Joshua Hesketh | 29d99b7 | 2014-08-19 16:27:42 +1000 | [diff] [blame] | 2020 | rootdir=os.environ.get("ZUUL_TEST_ROOT")) |
| 2021 | ).path |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2022 | else: |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 2023 | tmp_root = tempfile.mkdtemp( |
| 2024 | dir=os.environ.get("ZUUL_TEST_ROOT", None)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2025 | self.test_root = os.path.join(tmp_root, "zuul-test") |
| 2026 | self.upstream_root = os.path.join(self.test_root, "upstream") |
Monty Taylor | d642d85 | 2017-02-23 14:05:42 -0500 | [diff] [blame] | 2027 | self.merger_src_root = os.path.join(self.test_root, "merger-git") |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2028 | 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] | 2029 | self.state_root = os.path.join(self.test_root, "lib") |
James E. Blair | 01d733e | 2017-06-23 20:47:51 +0100 | [diff] [blame] | 2030 | self.merger_state_root = os.path.join(self.test_root, "merger-lib") |
| 2031 | self.executor_state_root = os.path.join(self.test_root, "executor-lib") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2032 | |
| 2033 | if os.path.exists(self.test_root): |
| 2034 | shutil.rmtree(self.test_root) |
| 2035 | os.makedirs(self.test_root) |
| 2036 | os.makedirs(self.upstream_root) |
James E. Blair | ce8a213 | 2016-05-19 15:21:52 -0700 | [diff] [blame] | 2037 | os.makedirs(self.state_root) |
James E. Blair | 01d733e | 2017-06-23 20:47:51 +0100 | [diff] [blame] | 2038 | os.makedirs(self.merger_state_root) |
| 2039 | os.makedirs(self.executor_state_root) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2040 | |
| 2041 | # Make per test copy of Configuration. |
| 2042 | self.setup_config() |
Clint Byrum | 50c69d8 | 2017-05-04 11:55:20 -0700 | [diff] [blame] | 2043 | self.private_key_file = os.path.join(self.test_root, 'test_id_rsa') |
| 2044 | if not os.path.exists(self.private_key_file): |
| 2045 | src_private_key_file = os.path.join(FIXTURE_DIR, 'test_id_rsa') |
| 2046 | shutil.copy(src_private_key_file, self.private_key_file) |
| 2047 | shutil.copy('{}.pub'.format(src_private_key_file), |
| 2048 | '{}.pub'.format(self.private_key_file)) |
| 2049 | os.chmod(self.private_key_file, 0o0600) |
James E. Blair | 3984036 | 2017-06-23 20:34:02 +0100 | [diff] [blame] | 2050 | self.config.set('scheduler', 'tenant_config', |
| 2051 | os.path.join( |
| 2052 | FIXTURE_DIR, |
| 2053 | self.config.get('scheduler', 'tenant_config'))) |
James E. Blair | d1de946 | 2017-06-23 20:53:09 +0100 | [diff] [blame] | 2054 | self.config.set('scheduler', 'state_dir', self.state_root) |
Paul Belanger | 40d3ce6 | 2017-11-28 11:49:55 -0500 | [diff] [blame] | 2055 | self.config.set( |
| 2056 | 'scheduler', 'command_socket', |
| 2057 | os.path.join(self.test_root, 'scheduler.socket')) |
Monty Taylor | d642d85 | 2017-02-23 14:05:42 -0500 | [diff] [blame] | 2058 | self.config.set('merger', 'git_dir', self.merger_src_root) |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2059 | self.config.set('executor', 'git_dir', self.executor_src_root) |
Clint Byrum | 50c69d8 | 2017-05-04 11:55:20 -0700 | [diff] [blame] | 2060 | self.config.set('executor', 'private_key_file', self.private_key_file) |
James E. Blair | 01d733e | 2017-06-23 20:47:51 +0100 | [diff] [blame] | 2061 | self.config.set('executor', 'state_dir', self.executor_state_root) |
Paul Belanger | 2092091 | 2017-11-28 11:22:30 -0500 | [diff] [blame] | 2062 | self.config.set( |
| 2063 | 'executor', 'command_socket', |
| 2064 | os.path.join(self.test_root, 'executor.socket')) |
James E. Blair | da5bb7e | 2018-01-22 16:12:17 -0800 | [diff] [blame] | 2065 | self.config.set( |
| 2066 | 'merger', 'command_socket', |
| 2067 | os.path.join(self.test_root, 'merger.socket')) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2068 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2069 | self.statsd = FakeStatsd() |
James E. Blair | ded241e | 2017-10-10 13:22:40 -0700 | [diff] [blame] | 2070 | if self.config.has_section('statsd'): |
| 2071 | self.config.set('statsd', 'port', str(self.statsd.port)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2072 | self.statsd.start() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2073 | |
Paul Belanger | 0a21f0a | 2017-06-13 13:14:42 -0400 | [diff] [blame] | 2074 | self.gearman_server = FakeGearmanServer(self.use_ssl) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2075 | |
| 2076 | self.config.set('gearman', 'port', str(self.gearman_server.port)) |
James E. Blair | e47eb77 | 2017-02-02 17:19:40 -0800 | [diff] [blame] | 2077 | self.log.info("Gearman server on port %s" % |
| 2078 | (self.gearman_server.port,)) |
Paul Belanger | 0a21f0a | 2017-06-13 13:14:42 -0400 | [diff] [blame] | 2079 | if self.use_ssl: |
| 2080 | self.log.info('SSL enabled for gearman') |
| 2081 | self.config.set( |
| 2082 | 'gearman', 'ssl_ca', |
| 2083 | os.path.join(FIXTURE_DIR, 'gearman/root-ca.pem')) |
| 2084 | self.config.set( |
| 2085 | 'gearman', 'ssl_cert', |
| 2086 | os.path.join(FIXTURE_DIR, 'gearman/client.pem')) |
| 2087 | self.config.set( |
| 2088 | 'gearman', 'ssl_key', |
| 2089 | os.path.join(FIXTURE_DIR, 'gearman/client.key')) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2090 | |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 2091 | self.rpcclient = zuul.rpcclient.RPCClient( |
| 2092 | self.config.get('gearman', 'server'), |
| 2093 | self.gearman_server.port, |
| 2094 | get_default(self.config, 'gearman', 'ssl_key'), |
| 2095 | get_default(self.config, 'gearman', 'ssl_cert'), |
| 2096 | get_default(self.config, 'gearman', 'ssl_ca')) |
| 2097 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 2098 | gerritsource.GerritSource.replication_timeout = 1.5 |
| 2099 | gerritsource.GerritSource.replication_retry_interval = 0.5 |
| 2100 | gerritconnection.GerritEventConnector.delay = 0.0 |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2101 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 2102 | self.sched = zuul.scheduler.Scheduler(self.config) |
James E. Blair | bdd50e6 | 2017-10-21 08:18:55 -0700 | [diff] [blame] | 2103 | self.sched._stats_interval = 1 |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2104 | |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 2105 | self.event_queues = [ |
| 2106 | self.sched.result_event_queue, |
James E. Blair | 646322f | 2017-01-27 15:50:34 -0800 | [diff] [blame] | 2107 | self.sched.trigger_event_queue, |
| 2108 | self.sched.management_event_queue |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 2109 | ] |
| 2110 | |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 2111 | self.configure_connections() |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 2112 | self.sched.registerConnections(self.connections) |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 2113 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2114 | self.executor_server = RecordingExecutorServer( |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 2115 | self.config, self.connections, |
James E. Blair | 854f889 | 2017-02-02 11:25:39 -0800 | [diff] [blame] | 2116 | jobdir_root=self.test_root, |
James E. Blair | a92cbc8 | 2017-01-23 14:56:49 -0800 | [diff] [blame] | 2117 | _run_ansible=self.run_ansible, |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 2118 | _test_root=self.test_root, |
| 2119 | keep_jobdir=KEEP_TEMPDIRS) |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2120 | self.executor_server.start() |
| 2121 | self.history = self.executor_server.build_history |
| 2122 | self.builds = self.executor_server.running_builds |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 2123 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2124 | self.executor_client = zuul.executor.client.ExecutorClient( |
James E. Blair | 92e953a | 2017-03-07 13:08:47 -0800 | [diff] [blame] | 2125 | self.config, self.sched) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 2126 | self.merge_client = zuul.merger.client.MergeClient( |
| 2127 | self.config, self.sched) |
James E. Blair | da5bb7e | 2018-01-22 16:12:17 -0800 | [diff] [blame] | 2128 | self.merge_server = None |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 2129 | self.nodepool = zuul.nodepool.Nodepool(self.sched) |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2130 | self.zk = zuul.zk.ZooKeeper() |
James E. Blair | 0d5a36e | 2017-02-21 10:53:44 -0500 | [diff] [blame] | 2131 | self.zk.connect(self.zk_config) |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2132 | |
James E. Blair | 0d5a36e | 2017-02-21 10:53:44 -0500 | [diff] [blame] | 2133 | self.fake_nodepool = FakeNodepool( |
| 2134 | self.zk_chroot_fixture.zookeeper_host, |
| 2135 | self.zk_chroot_fixture.zookeeper_port, |
| 2136 | self.zk_chroot_fixture.zookeeper_chroot) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2137 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2138 | self.sched.setExecutor(self.executor_client) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2139 | self.sched.setMerger(self.merge_client) |
James E. Blair | 8d69239 | 2016-04-08 17:47:58 -0700 | [diff] [blame] | 2140 | self.sched.setNodepool(self.nodepool) |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2141 | self.sched.setZooKeeper(self.zk) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2142 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2143 | self.sched.start() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2144 | self.executor_client.gearman.waitForServer() |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 2145 | # Cleanups are run in reverse order |
| 2146 | self.addCleanup(self.assertCleanShutdown) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2147 | self.addCleanup(self.shutdown) |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 2148 | self.addCleanup(self.assertFinalState) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2149 | |
James E. Blair | b9c0d77 | 2017-03-03 14:34:49 -0800 | [diff] [blame] | 2150 | self.sched.reconfigure(self.config) |
| 2151 | self.sched.resume() |
| 2152 | |
Tobias Henkel | 7df274b | 2017-05-26 17:41:11 +0200 | [diff] [blame] | 2153 | def configure_connections(self, source_only=False): |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 2154 | # Set up gerrit related fakes |
| 2155 | # Set a changes database so multiple FakeGerrit's can report back to |
| 2156 | # a virtual canonical database given by the configured hostname |
| 2157 | self.gerrit_changes_dbs = {} |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 2158 | self.github_changes_dbs = {} |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 2159 | |
| 2160 | def getGerritConnection(driver, name, config): |
| 2161 | db = self.gerrit_changes_dbs.setdefault(config['server'], {}) |
| 2162 | con = FakeGerritConnection(driver, name, config, |
| 2163 | changes_db=db, |
| 2164 | upstream_root=self.upstream_root) |
| 2165 | self.event_queues.append(con.event_queue) |
| 2166 | setattr(self, 'fake_' + name, con) |
| 2167 | return con |
| 2168 | |
| 2169 | self.useFixture(fixtures.MonkeyPatch( |
| 2170 | 'zuul.driver.gerrit.GerritDriver.getConnection', |
| 2171 | getGerritConnection)) |
| 2172 | |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 2173 | def getGithubConnection(driver, name, config): |
James E. Blair | 6bacffb | 2018-01-05 13:45:25 -0800 | [diff] [blame] | 2174 | server = config.get('server', 'github.com') |
| 2175 | db = self.github_changes_dbs.setdefault(server, {}) |
Tobias Henkel | 054eccc | 2017-12-20 11:36:19 +0100 | [diff] [blame] | 2176 | con = FakeGithubConnection( |
| 2177 | driver, name, config, |
| 2178 | self.rpcclient, |
| 2179 | changes_db=db, |
| 2180 | upstream_root=self.upstream_root, |
| 2181 | git_url_with_auth=self.git_url_with_auth) |
Jesse Keating | 64d2901 | 2017-09-06 12:27:49 -0700 | [diff] [blame] | 2182 | self.event_queues.append(con.event_queue) |
Gregory Haynes | 4fc1254 | 2015-04-22 20:38:06 -0700 | [diff] [blame] | 2183 | setattr(self, 'fake_' + name, con) |
| 2184 | return con |
| 2185 | |
| 2186 | self.useFixture(fixtures.MonkeyPatch( |
| 2187 | 'zuul.driver.github.GithubDriver.getConnection', |
| 2188 | getGithubConnection)) |
| 2189 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 2190 | # Set up smtp related fakes |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 2191 | # TODO(jhesketh): This should come from lib.connections for better |
| 2192 | # coverage |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 2193 | # Register connections from the config |
| 2194 | self.smtp_messages = [] |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 2195 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 2196 | def FakeSMTPFactory(*args, **kw): |
| 2197 | args = [self.smtp_messages] + list(args) |
| 2198 | return FakeSMTP(*args, **kw) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 2199 | |
Joshua Hesketh | 352264b | 2015-08-11 23:42:08 +1000 | [diff] [blame] | 2200 | self.useFixture(fixtures.MonkeyPatch('smtplib.SMTP', FakeSMTPFactory)) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 2201 | |
James E. Blair | e511d2f | 2016-12-08 15:22:26 -0800 | [diff] [blame] | 2202 | # Register connections from the config using fakes |
James E. Blair | fef7894 | 2016-03-11 16:28:56 -0800 | [diff] [blame] | 2203 | self.connections = zuul.lib.connections.ConnectionRegistry() |
Tobias Henkel | 7df274b | 2017-05-26 17:41:11 +0200 | [diff] [blame] | 2204 | self.connections.configure(self.config, source_only=source_only) |
Joshua Hesketh | 850ccb6 | 2014-11-27 11:31:02 +1100 | [diff] [blame] | 2205 | |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 2206 | def setup_config(self): |
James E. Blair | e7b99a0 | 2016-08-05 14:27:34 -0700 | [diff] [blame] | 2207 | # This creates the per-test configuration object. It can be |
| 2208 | # overriden by subclasses, but should not need to be since it |
| 2209 | # obeys the config_file and tenant_config_file attributes. |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 2210 | self.config = configparser.ConfigParser() |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 2211 | self.config.read(os.path.join(FIXTURE_DIR, self.config_file)) |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2212 | |
James E. Blair | 3984036 | 2017-06-23 20:34:02 +0100 | [diff] [blame] | 2213 | sections = ['zuul', 'scheduler', 'executor', 'merger'] |
| 2214 | for section in sections: |
| 2215 | if not self.config.has_section(section): |
| 2216 | self.config.add_section(section) |
| 2217 | |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2218 | if not self.setupSimpleLayout(): |
| 2219 | if hasattr(self, 'tenant_config_file'): |
James E. Blair | 3984036 | 2017-06-23 20:34:02 +0100 | [diff] [blame] | 2220 | self.config.set('scheduler', 'tenant_config', |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2221 | self.tenant_config_file) |
| 2222 | git_path = os.path.join( |
| 2223 | os.path.dirname( |
| 2224 | os.path.join(FIXTURE_DIR, self.tenant_config_file)), |
| 2225 | 'git') |
| 2226 | if os.path.exists(git_path): |
| 2227 | for reponame in os.listdir(git_path): |
| 2228 | project = reponame.replace('_', '/') |
| 2229 | self.copyDirToRepo(project, |
| 2230 | os.path.join(git_path, reponame)) |
Tristan Cacqueray | 44aef15 | 2017-06-15 06:00:12 +0000 | [diff] [blame] | 2231 | # Make test_root persist after ansible run for .flag test |
Monty Taylor | 01380dd | 2017-07-28 16:01:20 -0500 | [diff] [blame] | 2232 | self.config.set('executor', 'trusted_rw_paths', self.test_root) |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2233 | self.setupAllProjectKeys() |
| 2234 | |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2235 | def setupSimpleLayout(self): |
| 2236 | # If the test method has been decorated with a simple_layout, |
| 2237 | # use that instead of the class tenant_config_file. Set up a |
| 2238 | # single config-project with the specified layout, and |
| 2239 | # initialize repos for all of the 'project' entries which |
| 2240 | # appear in the layout. |
| 2241 | test_name = self.id().split('.')[-1] |
| 2242 | test = getattr(self, test_name) |
| 2243 | if hasattr(test, '__simple_layout__'): |
Jesse Keating | 436a545 | 2017-04-20 11:48:41 -0700 | [diff] [blame] | 2244 | path, driver = getattr(test, '__simple_layout__') |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2245 | else: |
| 2246 | return False |
| 2247 | |
James E. Blair | b70e55a | 2017-04-19 12:57:02 -0700 | [diff] [blame] | 2248 | files = {} |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2249 | path = os.path.join(FIXTURE_DIR, path) |
| 2250 | with open(path) as f: |
James E. Blair | b70e55a | 2017-04-19 12:57:02 -0700 | [diff] [blame] | 2251 | data = f.read() |
| 2252 | layout = yaml.safe_load(data) |
| 2253 | files['zuul.yaml'] = data |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2254 | untrusted_projects = [] |
| 2255 | for item in layout: |
| 2256 | if 'project' in item: |
| 2257 | name = item['project']['name'] |
| 2258 | untrusted_projects.append(name) |
| 2259 | self.init_repo(name) |
| 2260 | self.addCommitToRepo(name, 'initial commit', |
| 2261 | files={'README': ''}, |
| 2262 | branch='master', tag='init') |
James E. Blair | b70e55a | 2017-04-19 12:57:02 -0700 | [diff] [blame] | 2263 | if 'job' in item: |
James E. Blair | b09a0c5 | 2017-10-04 07:35:14 -0700 | [diff] [blame] | 2264 | if 'run' in item['job']: |
Ian Wienand | 5ede2fa | 2017-12-05 14:16:19 +1100 | [diff] [blame] | 2265 | files['%s' % item['job']['run']] = '' |
James E. Blair | b09a0c5 | 2017-10-04 07:35:14 -0700 | [diff] [blame] | 2266 | for fn in zuul.configloader.as_list( |
| 2267 | item['job'].get('pre-run', [])): |
Ian Wienand | 5ede2fa | 2017-12-05 14:16:19 +1100 | [diff] [blame] | 2268 | files['%s' % fn] = '' |
James E. Blair | b09a0c5 | 2017-10-04 07:35:14 -0700 | [diff] [blame] | 2269 | for fn in zuul.configloader.as_list( |
| 2270 | item['job'].get('post-run', [])): |
Ian Wienand | 5ede2fa | 2017-12-05 14:16:19 +1100 | [diff] [blame] | 2271 | files['%s' % fn] = '' |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2272 | |
| 2273 | root = os.path.join(self.test_root, "config") |
| 2274 | if not os.path.exists(root): |
| 2275 | os.makedirs(root) |
| 2276 | f = tempfile.NamedTemporaryFile(dir=root, delete=False) |
| 2277 | config = [{'tenant': |
| 2278 | {'name': 'tenant-one', |
Jesse Keating | 436a545 | 2017-04-20 11:48:41 -0700 | [diff] [blame] | 2279 | 'source': {driver: |
Tobias Henkel | 3c17d5f | 2017-08-03 11:46:54 +0200 | [diff] [blame] | 2280 | {'config-projects': ['org/common-config'], |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2281 | 'untrusted-projects': untrusted_projects}}}}] |
Clint Byrum | d52b7d7 | 2017-05-10 19:40:35 -0700 | [diff] [blame] | 2282 | f.write(yaml.dump(config).encode('utf8')) |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2283 | f.close() |
James E. Blair | 3984036 | 2017-06-23 20:34:02 +0100 | [diff] [blame] | 2284 | self.config.set('scheduler', 'tenant_config', |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2285 | os.path.join(FIXTURE_DIR, f.name)) |
| 2286 | |
Tobias Henkel | 3c17d5f | 2017-08-03 11:46:54 +0200 | [diff] [blame] | 2287 | self.init_repo('org/common-config') |
| 2288 | self.addCommitToRepo('org/common-config', 'add content from fixture', |
James E. Blair | 06cc392 | 2017-04-19 10:08:10 -0700 | [diff] [blame] | 2289 | files, branch='master', tag='init') |
| 2290 | |
| 2291 | return True |
| 2292 | |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2293 | def setupAllProjectKeys(self): |
| 2294 | if self.create_project_keys: |
| 2295 | return |
| 2296 | |
James E. Blair | 3984036 | 2017-06-23 20:34:02 +0100 | [diff] [blame] | 2297 | path = self.config.get('scheduler', 'tenant_config') |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2298 | with open(os.path.join(FIXTURE_DIR, path)) as f: |
| 2299 | tenant_config = yaml.safe_load(f.read()) |
| 2300 | for tenant in tenant_config: |
| 2301 | sources = tenant['tenant']['source'] |
| 2302 | for source, conf in sources.items(): |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2303 | for project in conf.get('config-projects', []): |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2304 | self.setupProjectKeys(source, project) |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2305 | for project in conf.get('untrusted-projects', []): |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2306 | self.setupProjectKeys(source, project) |
| 2307 | |
| 2308 | def setupProjectKeys(self, source, project): |
| 2309 | # Make sure we set up an RSA key for the project so that we |
| 2310 | # don't spend time generating one: |
| 2311 | |
James E. Blair | 6459db1 | 2017-06-29 14:57:20 -0700 | [diff] [blame] | 2312 | if isinstance(project, dict): |
| 2313 | project = list(project.keys())[0] |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2314 | key_root = os.path.join(self.state_root, 'keys') |
| 2315 | if not os.path.isdir(key_root): |
| 2316 | os.mkdir(key_root, 0o700) |
| 2317 | private_key_file = os.path.join(key_root, source, project + '.pem') |
| 2318 | private_key_dir = os.path.dirname(private_key_file) |
| 2319 | self.log.debug("Installing test keys for project %s at %s" % ( |
| 2320 | project, private_key_file)) |
| 2321 | if not os.path.isdir(private_key_dir): |
| 2322 | os.makedirs(private_key_dir) |
| 2323 | with open(os.path.join(FIXTURE_DIR, 'private.pem')) as i: |
| 2324 | with open(private_key_file, 'w') as o: |
| 2325 | o.write(i.read()) |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 2326 | |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 2327 | def setupZK(self): |
Clark Boylan | 621ec9a | 2017-04-07 17:41:33 -0700 | [diff] [blame] | 2328 | self.zk_chroot_fixture = self.useFixture( |
| 2329 | ChrootedKazooFixture(self.id())) |
James E. Blair | 0d5a36e | 2017-02-21 10:53:44 -0500 | [diff] [blame] | 2330 | self.zk_config = '%s:%s%s' % ( |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2331 | self.zk_chroot_fixture.zookeeper_host, |
| 2332 | self.zk_chroot_fixture.zookeeper_port, |
| 2333 | self.zk_chroot_fixture.zookeeper_chroot) |
James E. Blair | 498059b | 2016-12-20 13:50:13 -0800 | [diff] [blame] | 2334 | |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 2335 | def copyDirToRepo(self, project, source_path): |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 2336 | self.init_repo(project) |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 2337 | |
| 2338 | files = {} |
| 2339 | for (dirpath, dirnames, filenames) in os.walk(source_path): |
| 2340 | for filename in filenames: |
| 2341 | test_tree_filepath = os.path.join(dirpath, filename) |
| 2342 | common_path = os.path.commonprefix([test_tree_filepath, |
| 2343 | source_path]) |
| 2344 | relative_filepath = test_tree_filepath[len(common_path) + 1:] |
| 2345 | with open(test_tree_filepath, 'r') as f: |
| 2346 | content = f.read() |
| 2347 | files[relative_filepath] = content |
| 2348 | self.addCommitToRepo(project, 'add content from fixture', |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 2349 | files, branch='master', tag='init') |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 2350 | |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 2351 | def assertNodepoolState(self): |
| 2352 | # Make sure that there are no pending requests |
| 2353 | |
| 2354 | requests = self.fake_nodepool.getNodeRequests() |
| 2355 | self.assertEqual(len(requests), 0) |
| 2356 | |
| 2357 | nodes = self.fake_nodepool.getNodes() |
| 2358 | for node in nodes: |
| 2359 | self.assertFalse(node['_lock'], "Node %s is locked" % |
| 2360 | (node['_oid'],)) |
| 2361 | |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2362 | def assertNoGeneratedKeys(self): |
| 2363 | # Make sure that Zuul did not generate any project keys |
| 2364 | # (unless it was supposed to). |
| 2365 | |
| 2366 | if self.create_project_keys: |
| 2367 | return |
| 2368 | |
| 2369 | with open(os.path.join(FIXTURE_DIR, 'private.pem')) as i: |
| 2370 | test_key = i.read() |
| 2371 | |
| 2372 | key_root = os.path.join(self.state_root, 'keys') |
| 2373 | for root, dirname, files in os.walk(key_root): |
| 2374 | for fn in files: |
| 2375 | with open(os.path.join(root, fn)) as f: |
| 2376 | self.assertEqual(test_key, f.read()) |
| 2377 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2378 | def assertFinalState(self): |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 2379 | self.log.debug("Assert final state") |
| 2380 | # Make sure no jobs are running |
| 2381 | self.assertEqual({}, self.executor_server.job_workers) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2382 | # Make sure that git.Repo objects have been garbage collected. |
James E. Blair | 73b4177 | 2017-05-22 13:22:55 -0700 | [diff] [blame] | 2383 | gc.disable() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2384 | gc.collect() |
| 2385 | for obj in gc.get_objects(): |
| 2386 | if isinstance(obj, git.Repo): |
James E. Blair | 73b4177 | 2017-05-22 13:22:55 -0700 | [diff] [blame] | 2387 | self.log.debug("Leaked git repo object: 0x%x %s" % |
| 2388 | (id(obj), repr(obj))) |
James E. Blair | 73b4177 | 2017-05-22 13:22:55 -0700 | [diff] [blame] | 2389 | gc.enable() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2390 | self.assertEmptyQueues() |
James E. Blair | e18d460 | 2017-01-05 11:17:28 -0800 | [diff] [blame] | 2391 | self.assertNodepoolState() |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2392 | self.assertNoGeneratedKeys() |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 2393 | ipm = zuul.manager.independent.IndependentPipelineManager |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 2394 | for tenant in self.sched.abide.tenants.values(): |
| 2395 | for pipeline in tenant.layout.pipelines.values(): |
James E. Blair | 8300578 | 2015-12-11 14:46:03 -0800 | [diff] [blame] | 2396 | if isinstance(pipeline.manager, ipm): |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 2397 | self.assertEqual(len(pipeline.queues), 0) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2398 | |
| 2399 | def shutdown(self): |
| 2400 | self.log.debug("Shutting down after tests") |
James E. Blair | 5426b11 | 2017-05-26 14:19:54 -0700 | [diff] [blame] | 2401 | self.executor_server.hold_jobs_in_build = False |
| 2402 | self.executor_server.release() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2403 | self.executor_client.stop() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2404 | self.merge_client.stop() |
James E. Blair | da5bb7e | 2018-01-22 16:12:17 -0800 | [diff] [blame] | 2405 | if self.merge_server: |
| 2406 | self.merge_server.stop() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2407 | self.executor_server.stop() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2408 | self.sched.stop() |
| 2409 | self.sched.join() |
| 2410 | self.statsd.stop() |
| 2411 | self.statsd.join() |
Jesse Keating | 80730e6 | 2017-09-14 15:35:11 -0600 | [diff] [blame] | 2412 | self.rpcclient.shutdown() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2413 | self.gearman_server.shutdown() |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2414 | self.fake_nodepool.stop() |
| 2415 | self.zk.disconnect() |
Clark Boylan | 8208c19 | 2017-04-24 18:08:08 -0700 | [diff] [blame] | 2416 | self.printHistory() |
Tobias Henkel | 9b546cd | 2017-05-16 09:48:03 +0200 | [diff] [blame] | 2417 | # We whitelist watchdog threads as they have relatively long delays |
Clark Boylan | f18e3b8 | 2017-04-24 17:34:13 -0700 | [diff] [blame] | 2418 | # before noticing they should exit, but they should exit on their own. |
Tobias Henkel | 9b546cd | 2017-05-16 09:48:03 +0200 | [diff] [blame] | 2419 | # Further the pydevd threads also need to be whitelisted so debugging |
| 2420 | # e.g. in PyCharm is possible without breaking shutdown. |
James E. Blair | 7a04df2 | 2017-10-17 08:44:52 -0700 | [diff] [blame] | 2421 | whitelist = ['watchdog', |
Tobias Henkel | 9b546cd | 2017-05-16 09:48:03 +0200 | [diff] [blame] | 2422 | 'pydevd.CommandThread', |
| 2423 | 'pydevd.Reader', |
| 2424 | 'pydevd.Writer', |
David Shrewsbury | fe1f194 | 2017-12-04 13:57:46 -0500 | [diff] [blame] | 2425 | 'socketserver_Thread', |
Tobias Henkel | 9b546cd | 2017-05-16 09:48:03 +0200 | [diff] [blame] | 2426 | ] |
Clark Boylan | f18e3b8 | 2017-04-24 17:34:13 -0700 | [diff] [blame] | 2427 | threads = [t for t in threading.enumerate() |
Tobias Henkel | 9b546cd | 2017-05-16 09:48:03 +0200 | [diff] [blame] | 2428 | if t.name not in whitelist] |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2429 | if len(threads) > 1: |
Clark Boylan | 8208c19 | 2017-04-24 18:08:08 -0700 | [diff] [blame] | 2430 | log_str = "" |
| 2431 | for thread_id, stack_frame in sys._current_frames().items(): |
| 2432 | log_str += "Thread: %s\n" % thread_id |
| 2433 | log_str += "".join(traceback.format_stack(stack_frame)) |
| 2434 | self.log.debug(log_str) |
| 2435 | raise Exception("More than one thread is running: %s" % threads) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2436 | |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 2437 | def assertCleanShutdown(self): |
| 2438 | pass |
| 2439 | |
James E. Blair | c4ba97a | 2017-04-19 16:26:24 -0700 | [diff] [blame] | 2440 | def init_repo(self, project, tag=None): |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2441 | parts = project.split('/') |
| 2442 | path = os.path.join(self.upstream_root, *parts[:-1]) |
| 2443 | if not os.path.exists(path): |
| 2444 | os.makedirs(path) |
| 2445 | path = os.path.join(self.upstream_root, project) |
| 2446 | repo = git.Repo.init(path) |
| 2447 | |
Morgan Fainberg | 78c301a | 2016-07-14 13:47:01 -0700 | [diff] [blame] | 2448 | with repo.config_writer() as config_writer: |
| 2449 | config_writer.set_value('user', 'email', 'user@example.com') |
| 2450 | config_writer.set_value('user', 'name', 'User Name') |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2451 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2452 | repo.index.commit('initial commit') |
| 2453 | master = repo.create_head('master') |
James E. Blair | c4ba97a | 2017-04-19 16:26:24 -0700 | [diff] [blame] | 2454 | if tag: |
| 2455 | repo.create_tag(tag) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2456 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2457 | repo.head.reference = master |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 2458 | zuul.merger.merger.reset_repo_to_head(repo) |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2459 | repo.git.clean('-x', '-f', '-d') |
| 2460 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2461 | def create_branch(self, project, branch): |
| 2462 | path = os.path.join(self.upstream_root, project) |
James E. Blair | b815c71 | 2017-09-22 10:10:19 -0700 | [diff] [blame] | 2463 | repo = git.Repo(path) |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2464 | fn = os.path.join(path, 'README') |
| 2465 | |
| 2466 | branch_head = repo.create_head(branch) |
| 2467 | repo.head.reference = branch_head |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2468 | f = open(fn, 'a') |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2469 | f.write("test %s\n" % branch) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2470 | f.close() |
| 2471 | repo.index.add([fn]) |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2472 | repo.index.commit('%s commit' % branch) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2473 | |
James E. Blair | 97d902e | 2014-08-21 13:25:56 -0700 | [diff] [blame] | 2474 | repo.head.reference = repo.heads['master'] |
James E. Blair | 879dafb | 2015-07-17 14:04:49 -0700 | [diff] [blame] | 2475 | zuul.merger.merger.reset_repo_to_head(repo) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2476 | repo.git.clean('-x', '-f', '-d') |
| 2477 | |
James E. Blair | da5bb7e | 2018-01-22 16:12:17 -0800 | [diff] [blame] | 2478 | def delete_branch(self, project, branch): |
| 2479 | path = os.path.join(self.upstream_root, project) |
| 2480 | repo = git.Repo(path) |
| 2481 | repo.head.reference = repo.heads['master'] |
| 2482 | zuul.merger.merger.reset_repo_to_head(repo) |
| 2483 | repo.delete_head(repo.heads[branch], force=True) |
| 2484 | |
Sachi King | 9f16d52 | 2016-03-16 12:20:45 +1100 | [diff] [blame] | 2485 | def create_commit(self, project): |
| 2486 | path = os.path.join(self.upstream_root, project) |
| 2487 | repo = git.Repo(path) |
| 2488 | repo.head.reference = repo.heads['master'] |
| 2489 | file_name = os.path.join(path, 'README') |
| 2490 | with open(file_name, 'a') as f: |
| 2491 | f.write('creating fake commit\n') |
| 2492 | repo.index.add([file_name]) |
| 2493 | commit = repo.index.commit('Creating a fake commit') |
| 2494 | return commit.hexsha |
| 2495 | |
James E. Blair | f4a5f02 | 2017-04-18 14:01:10 -0700 | [diff] [blame] | 2496 | def orderedRelease(self, count=None): |
James E. Blair | b8c1647 | 2015-05-05 14:55:26 -0700 | [diff] [blame] | 2497 | # Run one build at a time to ensure non-race order: |
James E. Blair | f4a5f02 | 2017-04-18 14:01:10 -0700 | [diff] [blame] | 2498 | i = 0 |
James E. Blair | b8c1647 | 2015-05-05 14:55:26 -0700 | [diff] [blame] | 2499 | while len(self.builds): |
| 2500 | self.release(self.builds[0]) |
| 2501 | self.waitUntilSettled() |
James E. Blair | f4a5f02 | 2017-04-18 14:01:10 -0700 | [diff] [blame] | 2502 | i += 1 |
| 2503 | if count is not None and i >= count: |
| 2504 | break |
James E. Blair | b8c1647 | 2015-05-05 14:55:26 -0700 | [diff] [blame] | 2505 | |
James E. Blair | df25ddc | 2017-07-08 07:57:09 -0700 | [diff] [blame] | 2506 | def getSortedBuilds(self): |
| 2507 | "Return the list of currently running builds sorted by name" |
| 2508 | |
| 2509 | return sorted(self.builds, key=lambda x: x.name) |
| 2510 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2511 | def release(self, job): |
| 2512 | if isinstance(job, FakeBuild): |
| 2513 | job.release() |
| 2514 | else: |
| 2515 | job.waiting = False |
| 2516 | self.log.debug("Queued job %s released" % job.unique) |
| 2517 | self.gearman_server.wakeConnections() |
| 2518 | |
| 2519 | def getParameter(self, job, name): |
| 2520 | if isinstance(job, FakeBuild): |
| 2521 | return job.parameters[name] |
| 2522 | else: |
| 2523 | parameters = json.loads(job.arguments) |
| 2524 | return parameters[name] |
| 2525 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2526 | def haveAllBuildsReported(self): |
| 2527 | # See if Zuul is waiting on a meta job to complete |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2528 | if self.executor_client.meta_jobs: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2529 | return False |
| 2530 | # Find out if every build that the worker has completed has been |
| 2531 | # reported back to Zuul. If it hasn't then that means a Gearman |
| 2532 | # event is still in transit and the system is not stable. |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2533 | for build in self.history: |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2534 | zbuild = self.executor_client.builds.get(build.uuid) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2535 | if not zbuild: |
| 2536 | # It has already been reported |
| 2537 | continue |
| 2538 | # It hasn't been reported yet. |
| 2539 | return False |
| 2540 | # Make sure that none of the worker connections are in GRAB_WAIT |
James E. Blair | 24c0703 | 2017-06-02 15:26:35 -0700 | [diff] [blame] | 2541 | worker = self.executor_server.executor_worker |
| 2542 | for connection in worker.active_connections: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2543 | if connection.state == 'GRAB_WAIT': |
| 2544 | return False |
| 2545 | return True |
| 2546 | |
| 2547 | def areAllBuildsWaiting(self): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2548 | builds = self.executor_client.builds.values() |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 2549 | seen_builds = set() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2550 | for build in builds: |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 2551 | seen_builds.add(build.uuid) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2552 | client_job = None |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2553 | for conn in self.executor_client.gearman.active_connections: |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2554 | for j in conn.related_jobs.values(): |
| 2555 | if j.unique == build.uuid: |
| 2556 | client_job = j |
| 2557 | break |
| 2558 | if not client_job: |
| 2559 | self.log.debug("%s is not known to the gearman client" % |
| 2560 | build) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 2561 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2562 | if not client_job.handle: |
| 2563 | self.log.debug("%s has no handle" % client_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 2564 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2565 | server_job = self.gearman_server.jobs.get(client_job.handle) |
| 2566 | if not server_job: |
| 2567 | self.log.debug("%s is not known to the gearman server" % |
| 2568 | client_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 2569 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2570 | if not hasattr(server_job, 'waiting'): |
| 2571 | self.log.debug("%s is being enqueued" % server_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 2572 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2573 | if server_job.waiting: |
| 2574 | continue |
James E. Blair | 1730297 | 2016-08-10 16:11:42 -0700 | [diff] [blame] | 2575 | if build.url is None: |
James E. Blair | bbda470 | 2016-03-09 15:19:56 -0800 | [diff] [blame] | 2576 | self.log.debug("%s has not reported start" % build) |
| 2577 | return False |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 2578 | # using internal ServerJob which offers no Text interface |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2579 | worker_build = self.executor_server.job_builds.get( |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 2580 | server_job.unique.decode('utf8')) |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 2581 | if worker_build: |
| 2582 | if worker_build.isWaiting(): |
| 2583 | continue |
| 2584 | else: |
| 2585 | self.log.debug("%s is running" % worker_build) |
| 2586 | return False |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2587 | else: |
James E. Blair | 962220f | 2016-08-03 11:22:38 -0700 | [diff] [blame] | 2588 | self.log.debug("%s is unassigned" % server_job) |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 2589 | return False |
James E. Blair | a002b03 | 2017-04-18 10:35:48 -0700 | [diff] [blame] | 2590 | for (build_uuid, job_worker) in \ |
| 2591 | self.executor_server.job_workers.items(): |
| 2592 | if build_uuid not in seen_builds: |
| 2593 | self.log.debug("%s is not finalized" % build_uuid) |
| 2594 | return False |
James E. Blair | f15139b | 2015-04-02 16:37:15 -0700 | [diff] [blame] | 2595 | return True |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2596 | |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2597 | def areAllNodeRequestsComplete(self): |
James E. Blair | 15be0e1 | 2017-01-03 13:45:20 -0800 | [diff] [blame] | 2598 | if self.fake_nodepool.paused: |
| 2599 | return True |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2600 | if self.sched.nodepool.requests: |
| 2601 | return False |
| 2602 | return True |
| 2603 | |
James E. Blair | a615c36 | 2017-10-02 17:34:42 -0700 | [diff] [blame] | 2604 | def areAllMergeJobsWaiting(self): |
| 2605 | for client_job in list(self.merge_client.jobs): |
| 2606 | if not client_job.handle: |
| 2607 | self.log.debug("%s has no handle" % client_job) |
| 2608 | return False |
| 2609 | server_job = self.gearman_server.jobs.get(client_job.handle) |
| 2610 | if not server_job: |
| 2611 | self.log.debug("%s is not known to the gearman server" % |
| 2612 | client_job) |
| 2613 | return False |
| 2614 | if not hasattr(server_job, 'waiting'): |
| 2615 | self.log.debug("%s is being enqueued" % server_job) |
| 2616 | return False |
| 2617 | if server_job.waiting: |
| 2618 | self.log.debug("%s is waiting" % server_job) |
| 2619 | continue |
| 2620 | self.log.debug("%s is not waiting" % server_job) |
| 2621 | return False |
| 2622 | return True |
| 2623 | |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 2624 | def eventQueuesEmpty(self): |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 2625 | for event_queue in self.event_queues: |
| 2626 | yield event_queue.empty() |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 2627 | |
| 2628 | def eventQueuesJoin(self): |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 2629 | for event_queue in self.event_queues: |
| 2630 | event_queue.join() |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 2631 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2632 | def waitUntilSettled(self): |
| 2633 | self.log.debug("Waiting until settled...") |
| 2634 | start = time.time() |
| 2635 | while True: |
Clint Byrum | a962657 | 2017-02-22 14:04:00 -0500 | [diff] [blame] | 2636 | if time.time() - start > self.wait_timeout: |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 2637 | self.log.error("Timeout waiting for Zuul to settle") |
| 2638 | self.log.error("Queue status:") |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 2639 | for event_queue in self.event_queues: |
| 2640 | self.log.error(" %s: %s" % |
| 2641 | (event_queue, event_queue.empty())) |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 2642 | self.log.error("All builds waiting: %s" % |
James E. Blair | 622c968 | 2016-06-09 08:14:53 -0700 | [diff] [blame] | 2643 | (self.areAllBuildsWaiting(),)) |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 2644 | self.log.error("All builds reported: %s" % |
James E. Blair | f3156c9 | 2016-08-10 15:32:19 -0700 | [diff] [blame] | 2645 | (self.haveAllBuildsReported(),)) |
James E. Blair | 10fc1eb | 2016-12-21 16:16:25 -0800 | [diff] [blame] | 2646 | self.log.error("All requests completed: %s" % |
| 2647 | (self.areAllNodeRequestsComplete(),)) |
| 2648 | self.log.error("Merge client jobs: %s" % |
| 2649 | (self.merge_client.jobs,)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2650 | raise Exception("Timeout waiting for Zuul to settle") |
| 2651 | # Make sure no new events show up while we're checking |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2652 | |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2653 | self.executor_server.lock.acquire() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2654 | # have all build states propogated to zuul? |
| 2655 | if self.haveAllBuildsReported(): |
| 2656 | # Join ensures that the queue is empty _and_ events have been |
| 2657 | # processed |
Jan Hruban | 6b71aff | 2015-10-22 16:58:08 +0200 | [diff] [blame] | 2658 | self.eventQueuesJoin() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2659 | self.sched.run_handler_lock.acquire() |
James E. Blair | a615c36 | 2017-10-02 17:34:42 -0700 | [diff] [blame] | 2660 | if (self.areAllMergeJobsWaiting() and |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2661 | self.haveAllBuildsReported() and |
James E. Blair | dce6cea | 2016-12-20 16:45:32 -0800 | [diff] [blame] | 2662 | self.areAllBuildsWaiting() and |
James E. Blair | 36c611a | 2017-02-06 15:59:43 -0800 | [diff] [blame] | 2663 | self.areAllNodeRequestsComplete() and |
| 2664 | all(self.eventQueuesEmpty())): |
| 2665 | # The queue empty check is placed at the end to |
| 2666 | # ensure that if a component adds an event between |
| 2667 | # when locked the run handler and checked that the |
| 2668 | # components were stable, we don't erroneously |
| 2669 | # report that we are settled. |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2670 | self.sched.run_handler_lock.release() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2671 | self.executor_server.lock.release() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2672 | self.log.debug("...settled.") |
| 2673 | return |
| 2674 | self.sched.run_handler_lock.release() |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2675 | self.executor_server.lock.release() |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2676 | self.sched.wake_event.wait(0.1) |
| 2677 | |
| 2678 | def countJobResults(self, jobs, result): |
| 2679 | jobs = filter(lambda x: x.result == result, jobs) |
Clint Byrum | 1d0c7d1 | 2017-05-10 19:40:53 -0700 | [diff] [blame] | 2680 | return len(list(jobs)) |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2681 | |
Monty Taylor | 0d92612 | 2017-05-24 08:07:56 -0500 | [diff] [blame] | 2682 | def getBuildByName(self, name): |
| 2683 | for build in self.builds: |
| 2684 | if build.name == name: |
| 2685 | return build |
| 2686 | raise Exception("Unable to find build %s" % name) |
| 2687 | |
David Shrewsbury | f6dc176 | 2017-10-02 13:34:37 -0400 | [diff] [blame] | 2688 | def assertJobNotInHistory(self, name, project=None): |
| 2689 | for job in self.history: |
| 2690 | if (project is None or |
| 2691 | job.parameters['zuul']['project']['name'] == project): |
| 2692 | self.assertNotEqual(job.name, name, |
| 2693 | 'Job %s found in history' % name) |
| 2694 | |
James E. Blair | 96c6bf8 | 2016-01-15 16:20:40 -0800 | [diff] [blame] | 2695 | def getJobFromHistory(self, name, project=None): |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2696 | for job in self.history: |
| 2697 | if (job.name == name and |
| 2698 | (project is None or |
James E. Blair | e536609 | 2017-07-21 15:30:39 -0700 | [diff] [blame] | 2699 | job.parameters['zuul']['project']['name'] == project)): |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2700 | return job |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2701 | raise Exception("Unable to find job %s in history" % name) |
| 2702 | |
| 2703 | def assertEmptyQueues(self): |
| 2704 | # Make sure there are no orphaned jobs |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 2705 | for tenant in self.sched.abide.tenants.values(): |
| 2706 | for pipeline in tenant.layout.pipelines.values(): |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 2707 | for pipeline_queue in pipeline.queues: |
| 2708 | if len(pipeline_queue.queue) != 0: |
Joshua Hesketh | 0aa7e8b | 2016-07-14 00:12:25 +1000 | [diff] [blame] | 2709 | print('pipeline %s queue %s contents %s' % ( |
Monty Taylor | b934c1a | 2017-06-16 19:31:47 -0500 | [diff] [blame] | 2710 | pipeline.name, pipeline_queue.name, |
| 2711 | pipeline_queue.queue)) |
| 2712 | self.assertEqual(len(pipeline_queue.queue), 0, |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 2713 | "Pipelines queues should be empty") |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2714 | |
| 2715 | def assertReportedStat(self, key, value=None, kind=None): |
| 2716 | start = time.time() |
| 2717 | while time.time() < (start + 5): |
| 2718 | for stat in self.statsd.stats: |
Clint Byrum | f322fe2 | 2017-05-10 20:53:12 -0700 | [diff] [blame] | 2719 | k, v = stat.decode('utf-8').split(':') |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2720 | if key == k: |
| 2721 | if value is None and kind is None: |
| 2722 | return |
| 2723 | elif value: |
| 2724 | if value == v: |
| 2725 | return |
| 2726 | elif kind: |
| 2727 | if v.endswith('|' + kind): |
| 2728 | return |
| 2729 | time.sleep(0.1) |
| 2730 | |
Clark Boylan | b640e05 | 2014-04-03 16:41:46 -0700 | [diff] [blame] | 2731 | raise Exception("Key %s not found in reported stats" % key) |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 2732 | |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 2733 | def assertBuilds(self, builds): |
| 2734 | """Assert that the running builds are as described. |
| 2735 | |
| 2736 | The list of running builds is examined and must match exactly |
| 2737 | the list of builds described by the input. |
| 2738 | |
| 2739 | :arg list builds: A list of dictionaries. Each item in the |
| 2740 | list must match the corresponding build in the build |
| 2741 | history, and each element of the dictionary must match the |
| 2742 | corresponding attribute of the build. |
| 2743 | |
| 2744 | """ |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 2745 | try: |
| 2746 | self.assertEqual(len(self.builds), len(builds)) |
| 2747 | for i, d in enumerate(builds): |
| 2748 | for k, v in d.items(): |
| 2749 | self.assertEqual( |
| 2750 | getattr(self.builds[i], k), v, |
| 2751 | "Element %i in builds does not match" % (i,)) |
| 2752 | except Exception: |
| 2753 | for build in self.builds: |
| 2754 | self.log.error("Running build: %s" % build) |
| 2755 | else: |
| 2756 | self.log.error("No running builds") |
| 2757 | raise |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 2758 | |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 2759 | def assertHistory(self, history, ordered=True): |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 2760 | """Assert that the completed builds are as described. |
| 2761 | |
| 2762 | The list of completed builds is examined and must match |
| 2763 | exactly the list of builds described by the input. |
| 2764 | |
| 2765 | :arg list history: A list of dictionaries. Each item in the |
| 2766 | list must match the corresponding build in the build |
| 2767 | history, and each element of the dictionary must match the |
| 2768 | corresponding attribute of the build. |
| 2769 | |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 2770 | :arg bool ordered: If true, the history must match the order |
| 2771 | supplied, if false, the builds are permitted to have |
| 2772 | arrived in any order. |
| 2773 | |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 2774 | """ |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 2775 | def matches(history_item, item): |
| 2776 | for k, v in item.items(): |
| 2777 | if getattr(history_item, k) != v: |
| 2778 | return False |
| 2779 | return True |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 2780 | try: |
| 2781 | self.assertEqual(len(self.history), len(history)) |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 2782 | if ordered: |
| 2783 | for i, d in enumerate(history): |
| 2784 | if not matches(self.history[i], d): |
| 2785 | raise Exception( |
K Jonathan Harker | cc3a6f0 | 2017-02-22 19:08:06 -0800 | [diff] [blame] | 2786 | "Element %i in history does not match %s" % |
| 2787 | (i, self.history[i])) |
James E. Blair | b536ecc | 2016-08-31 10:11:42 -0700 | [diff] [blame] | 2788 | else: |
| 2789 | unseen = self.history[:] |
| 2790 | for i, d in enumerate(history): |
| 2791 | found = False |
| 2792 | for unseen_item in unseen: |
| 2793 | if matches(unseen_item, d): |
| 2794 | found = True |
| 2795 | unseen.remove(unseen_item) |
| 2796 | break |
| 2797 | if not found: |
| 2798 | raise Exception("No match found for element %i " |
| 2799 | "in history" % (i,)) |
| 2800 | if unseen: |
| 2801 | raise Exception("Unexpected items in history") |
James E. Blair | 3158e28 | 2016-08-19 09:34:11 -0700 | [diff] [blame] | 2802 | except Exception: |
| 2803 | for build in self.history: |
| 2804 | self.log.error("Completed build: %s" % build) |
| 2805 | else: |
| 2806 | self.log.error("No completed builds") |
| 2807 | raise |
James E. Blair | 2b2a8ab | 2016-08-11 14:39:11 -0700 | [diff] [blame] | 2808 | |
James E. Blair | 6ac368c | 2016-12-22 18:07:20 -0800 | [diff] [blame] | 2809 | def printHistory(self): |
| 2810 | """Log the build history. |
| 2811 | |
| 2812 | This can be useful during tests to summarize what jobs have |
| 2813 | completed. |
| 2814 | |
| 2815 | """ |
| 2816 | self.log.debug("Build history:") |
| 2817 | for build in self.history: |
| 2818 | self.log.debug(build) |
| 2819 | |
James E. Blair | 59fdbac | 2015-12-07 17:08:06 -0800 | [diff] [blame] | 2820 | def getPipeline(self, name): |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2821 | return self.sched.abide.tenants.values()[0].layout.pipelines.get(name) |
| 2822 | |
James E. Blair | 9ea7007 | 2017-04-19 16:05:30 -0700 | [diff] [blame] | 2823 | def updateConfigLayout(self, path): |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2824 | root = os.path.join(self.test_root, "config") |
Clint Byrum | ead6c56 | 2017-02-01 16:34:04 -0800 | [diff] [blame] | 2825 | if not os.path.exists(root): |
| 2826 | os.makedirs(root) |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2827 | f = tempfile.NamedTemporaryFile(dir=root, delete=False) |
| 2828 | f.write(""" |
Paul Belanger | 66e9596 | 2016-11-11 12:11:06 -0500 | [diff] [blame] | 2829 | - tenant: |
| 2830 | name: openstack |
| 2831 | source: |
| 2832 | gerrit: |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2833 | config-projects: |
Paul Belanger | 66e9596 | 2016-11-11 12:11:06 -0500 | [diff] [blame] | 2834 | - %s |
James E. Blair | 109da3f | 2017-04-04 14:39:43 -0700 | [diff] [blame] | 2835 | untrusted-projects: |
James E. Blair | 0ffa010 | 2017-03-30 13:11:33 -0700 | [diff] [blame] | 2836 | - org/project |
| 2837 | - org/project1 |
James E. Blair | 7cb8454 | 2017-04-19 13:35:05 -0700 | [diff] [blame] | 2838 | - org/project2\n""" % path) |
James E. Blair | f84026c | 2015-12-08 16:11:46 -0800 | [diff] [blame] | 2839 | f.close() |
James E. Blair | 3984036 | 2017-06-23 20:34:02 +0100 | [diff] [blame] | 2840 | self.config.set('scheduler', 'tenant_config', |
Paul Belanger | 66e9596 | 2016-11-11 12:11:06 -0500 | [diff] [blame] | 2841 | os.path.join(FIXTURE_DIR, f.name)) |
Ricardo Carrillo Cruz | 22994f9 | 2016-12-02 11:41:58 +0000 | [diff] [blame] | 2842 | self.setupAllProjectKeys() |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2843 | |
Fabien Boucher | 194a2bf | 2017-12-02 18:17:58 +0100 | [diff] [blame] | 2844 | def addTagToRepo(self, project, name, sha): |
| 2845 | path = os.path.join(self.upstream_root, project) |
| 2846 | repo = git.Repo(path) |
| 2847 | repo.git.tag(name, sha) |
| 2848 | |
| 2849 | def delTagFromRepo(self, project, name): |
| 2850 | path = os.path.join(self.upstream_root, project) |
| 2851 | repo = git.Repo(path) |
| 2852 | repo.git.tag('-d', name) |
| 2853 | |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 2854 | def addCommitToRepo(self, project, message, files, |
| 2855 | branch='master', tag=None): |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2856 | path = os.path.join(self.upstream_root, project) |
| 2857 | repo = git.Repo(path) |
| 2858 | repo.head.reference = branch |
| 2859 | zuul.merger.merger.reset_repo_to_head(repo) |
| 2860 | for fn, content in files.items(): |
| 2861 | fn = os.path.join(path, fn) |
James E. Blair | c73c73a | 2017-01-20 15:15:15 -0800 | [diff] [blame] | 2862 | try: |
| 2863 | os.makedirs(os.path.dirname(fn)) |
| 2864 | except OSError: |
| 2865 | pass |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2866 | with open(fn, 'w') as f: |
| 2867 | f.write(content) |
| 2868 | repo.index.add([fn]) |
| 2869 | commit = repo.index.commit(message) |
Clint Byrum | 58264dc | 2017-02-07 21:21:22 -0800 | [diff] [blame] | 2870 | before = repo.heads[branch].commit |
James E. Blair | 14abdf4 | 2015-12-09 16:11:53 -0800 | [diff] [blame] | 2871 | repo.heads[branch].commit = commit |
| 2872 | repo.head.reference = branch |
| 2873 | repo.git.clean('-x', '-f', '-d') |
| 2874 | repo.heads[branch].checkout() |
James E. Blair | 8b1dc3f | 2016-07-05 16:49:00 -0700 | [diff] [blame] | 2875 | if tag: |
| 2876 | repo.create_tag(tag) |
Clint Byrum | 58264dc | 2017-02-07 21:21:22 -0800 | [diff] [blame] | 2877 | return before |
| 2878 | |
James E. Blair | 9ea0d0b | 2017-04-20 09:27:15 -0700 | [diff] [blame] | 2879 | def commitConfigUpdate(self, project_name, source_name): |
| 2880 | """Commit an update to zuul.yaml |
| 2881 | |
| 2882 | This overwrites the zuul.yaml in the specificed project with |
| 2883 | the contents specified. |
| 2884 | |
| 2885 | :arg str project_name: The name of the project containing |
| 2886 | zuul.yaml (e.g., common-config) |
| 2887 | |
| 2888 | :arg str source_name: The path to the file (underneath the |
| 2889 | test fixture directory) whose contents should be used to |
| 2890 | replace zuul.yaml. |
| 2891 | """ |
| 2892 | |
| 2893 | source_path = os.path.join(FIXTURE_DIR, source_name) |
James E. Blair | dfdfcfc | 2017-04-20 10:19:20 -0700 | [diff] [blame] | 2894 | files = {} |
| 2895 | with open(source_path, 'r') as f: |
| 2896 | data = f.read() |
| 2897 | layout = yaml.safe_load(data) |
| 2898 | files['zuul.yaml'] = data |
| 2899 | for item in layout: |
| 2900 | if 'job' in item: |
| 2901 | jobname = item['job']['name'] |
| 2902 | files['playbooks/%s.yaml' % jobname] = '' |
James E. Blair | 9ea0d0b | 2017-04-20 09:27:15 -0700 | [diff] [blame] | 2903 | before = self.addCommitToRepo( |
| 2904 | project_name, 'Pulling content from %s' % source_name, |
James E. Blair | dfdfcfc | 2017-04-20 10:19:20 -0700 | [diff] [blame] | 2905 | files) |
James E. Blair | 9ea0d0b | 2017-04-20 09:27:15 -0700 | [diff] [blame] | 2906 | return before |
| 2907 | |
Clint Byrum | 627ba36 | 2017-08-14 13:20:40 -0700 | [diff] [blame] | 2908 | def newTenantConfig(self, source_name): |
| 2909 | """ Use this to update the tenant config file in tests |
| 2910 | |
| 2911 | This will update self.tenant_config_file to point to a temporary file |
| 2912 | for the duration of this particular test. The content of that file will |
| 2913 | be taken from FIXTURE_DIR/source_name |
| 2914 | |
| 2915 | After the test the original value of self.tenant_config_file will be |
| 2916 | restored. |
| 2917 | |
| 2918 | :arg str source_name: The path of the file under |
| 2919 | FIXTURE_DIR that will be used to populate the new tenant |
| 2920 | config file. |
| 2921 | """ |
| 2922 | source_path = os.path.join(FIXTURE_DIR, source_name) |
| 2923 | orig_tenant_config_file = self.tenant_config_file |
| 2924 | with tempfile.NamedTemporaryFile( |
| 2925 | delete=False, mode='wb') as new_tenant_config: |
| 2926 | self.tenant_config_file = new_tenant_config.name |
| 2927 | with open(source_path, mode='rb') as source_tenant_config: |
| 2928 | new_tenant_config.write(source_tenant_config.read()) |
| 2929 | self.config['scheduler']['tenant_config'] = self.tenant_config_file |
| 2930 | self.setupAllProjectKeys() |
| 2931 | self.log.debug( |
| 2932 | 'tenant_config_file = {}'.format(self.tenant_config_file)) |
| 2933 | |
| 2934 | def _restoreTenantConfig(): |
| 2935 | self.log.debug( |
| 2936 | 'restoring tenant_config_file = {}'.format( |
| 2937 | orig_tenant_config_file)) |
| 2938 | os.unlink(self.tenant_config_file) |
| 2939 | self.tenant_config_file = orig_tenant_config_file |
| 2940 | self.config['scheduler']['tenant_config'] = orig_tenant_config_file |
| 2941 | self.addCleanup(_restoreTenantConfig) |
| 2942 | |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 2943 | def addEvent(self, connection, event): |
James E. Blair | 9ea0d0b | 2017-04-20 09:27:15 -0700 | [diff] [blame] | 2944 | |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 2945 | """Inject a Fake (Gerrit) event. |
| 2946 | |
| 2947 | This method accepts a JSON-encoded event and simulates Zuul |
| 2948 | having received it from Gerrit. It could (and should) |
| 2949 | eventually apply to any connection type, but is currently only |
| 2950 | used with Gerrit connections. The name of the connection is |
| 2951 | used to look up the corresponding server, and the event is |
| 2952 | simulated as having been received by all Zuul connections |
| 2953 | attached to that server. So if two Gerrit connections in Zuul |
| 2954 | are connected to the same Gerrit server, and you invoke this |
| 2955 | method specifying the name of one of them, the event will be |
| 2956 | received by both. |
| 2957 | |
| 2958 | .. note:: |
| 2959 | |
| 2960 | "self.fake_gerrit.addEvent" calls should be migrated to |
| 2961 | this method. |
| 2962 | |
| 2963 | :arg str connection: The name of the connection corresponding |
Clark Boylan | 500992b | 2017-04-03 14:28:24 -0700 | [diff] [blame] | 2964 | to the gerrit server. |
James E. Blair | 7fc8daa | 2016-08-08 15:37:15 -0700 | [diff] [blame] | 2965 | :arg str event: The JSON-encoded event. |
| 2966 | |
| 2967 | """ |
| 2968 | specified_conn = self.connections.connections[connection] |
| 2969 | for conn in self.connections.connections.values(): |
| 2970 | if (isinstance(conn, specified_conn.__class__) and |
| 2971 | specified_conn.server == conn.server): |
| 2972 | conn.addEvent(event) |
| 2973 | |
James E. Blair | d8af542 | 2017-05-24 13:59:40 -0700 | [diff] [blame] | 2974 | def getUpstreamRepos(self, projects): |
| 2975 | """Return upstream git repo objects for the listed projects |
| 2976 | |
| 2977 | :arg list projects: A list of strings, each the canonical name |
| 2978 | of a project. |
| 2979 | |
| 2980 | :returns: A dictionary of {name: repo} for every listed |
| 2981 | project. |
| 2982 | :rtype: dict |
| 2983 | |
| 2984 | """ |
| 2985 | |
| 2986 | repos = {} |
| 2987 | for project in projects: |
| 2988 | # FIXME(jeblair): the upstream root does not yet have a |
| 2989 | # hostname component; that needs to be added, and this |
| 2990 | # line removed: |
| 2991 | tmp_project_name = '/'.join(project.split('/')[1:]) |
| 2992 | path = os.path.join(self.upstream_root, tmp_project_name) |
| 2993 | repo = git.Repo(path) |
| 2994 | repos[project] = repo |
| 2995 | return repos |
| 2996 | |
James E. Blair | 3f876d5 | 2016-07-22 13:07:14 -0700 | [diff] [blame] | 2997 | |
| 2998 | class AnsibleZuulTestCase(ZuulTestCase): |
Paul Belanger | 174a827 | 2017-03-14 13:20:10 -0400 | [diff] [blame] | 2999 | """ZuulTestCase but with an actual ansible executor running""" |
James E. Blair | e1767bc | 2016-08-02 10:00:27 -0700 | [diff] [blame] | 3000 | run_ansible = True |
Joshua Hesketh | 25695cb | 2017-03-06 12:50:04 +1100 | [diff] [blame] | 3001 | |
Jamie Lennox | 7655b55 | 2017-03-17 12:33:38 +1100 | [diff] [blame] | 3002 | @contextmanager |
| 3003 | def jobLog(self, build): |
| 3004 | """Print job logs on assertion errors |
| 3005 | |
| 3006 | This method is a context manager which, if it encounters an |
| 3007 | ecxeption, adds the build log to the debug output. |
| 3008 | |
| 3009 | :arg Build build: The build that's being asserted. |
| 3010 | """ |
| 3011 | try: |
| 3012 | yield |
| 3013 | except Exception: |
| 3014 | path = os.path.join(self.test_root, build.uuid, |
| 3015 | 'work', 'logs', 'job-output.txt') |
| 3016 | with open(path) as f: |
| 3017 | self.log.debug(f.read()) |
| 3018 | raise |
| 3019 | |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 3020 | |
Paul Belanger | 0a21f0a | 2017-06-13 13:14:42 -0400 | [diff] [blame] | 3021 | class SSLZuulTestCase(ZuulTestCase): |
Paul Belanger | d3232f5 | 2017-06-14 13:54:31 -0400 | [diff] [blame] | 3022 | """ZuulTestCase but using SSL when possible""" |
Paul Belanger | 0a21f0a | 2017-06-13 13:14:42 -0400 | [diff] [blame] | 3023 | use_ssl = True |
| 3024 | |
| 3025 | |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 3026 | class ZuulDBTestCase(ZuulTestCase): |
James E. Blair | 8284489 | 2017-03-06 10:55:26 -0800 | [diff] [blame] | 3027 | def setup_config(self): |
| 3028 | super(ZuulDBTestCase, self).setup_config() |
Joshua Hesketh | d78b448 | 2015-09-14 16:56:34 -0600 | [diff] [blame] | 3029 | for section_name in self.config.sections(): |
| 3030 | con_match = re.match(r'^connection ([\'\"]?)(.*)(\1)$', |
| 3031 | section_name, re.I) |
| 3032 | if not con_match: |
| 3033 | continue |
| 3034 | |
| 3035 | if self.config.get(section_name, 'driver') == 'sql': |
| 3036 | f = MySQLSchemaFixture() |
| 3037 | self.useFixture(f) |
| 3038 | if (self.config.get(section_name, 'dburi') == |
| 3039 | '$MYSQL_FIXTURE_DBURI$'): |
| 3040 | self.config.set(section_name, 'dburi', f.dburi) |