blob: 6321fe9784bbfc6f009b8dc6f007fe5f134f3575 [file] [log] [blame]
Clark Boylanb640e052014-04-03 16:41:46 -07001#!/usr/bin/env python
2
3# Copyright 2012 Hewlett-Packard Development Company, L.P.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
Christian Berendtffba5df2014-06-07 21:30:22 +020017from six.moves import configparser as ConfigParser
Clark Boylanb640e052014-04-03 16:41:46 -070018import gc
19import hashlib
20import json
21import logging
22import os
23import pprint
Christian Berendt12d4d722014-06-07 21:03:45 +020024from six.moves import queue as Queue
Morgan Fainberg293f7f82016-05-30 14:01:22 -070025from six.moves import urllib
Clark Boylanb640e052014-04-03 16:41:46 -070026import random
27import re
28import select
29import shutil
Monty Taylor74fa3862016-06-02 07:39:49 +030030from six.moves import reload_module
Clark Boylanb640e052014-04-03 16:41:46 -070031import socket
32import string
33import subprocess
34import swiftclient
James E. Blairf84026c2015-12-08 16:11:46 -080035import tempfile
Clark Boylanb640e052014-04-03 16:41:46 -070036import threading
37import time
Clark Boylanb640e052014-04-03 16:41:46 -070038
39import git
40import gear
41import fixtures
Clark Boylanb640e052014-04-03 16:41:46 -070042import statsd
43import testtools
Mike Heald8225f522014-11-21 09:52:33 +000044from git import GitCommandError
Clark Boylanb640e052014-04-03 16:41:46 -070045
Joshua Hesketh352264b2015-08-11 23:42:08 +100046import zuul.connection.gerrit
47import zuul.connection.smtp
Clark Boylanb640e052014-04-03 16:41:46 -070048import zuul.scheduler
49import zuul.webapp
50import zuul.rpclistener
Joshua Hesketh0c54b2a2016-04-11 21:23:33 +100051import zuul.launcher.server
52import zuul.launcher.client
Clark Boylanb640e052014-04-03 16:41:46 -070053import zuul.lib.swift
James E. Blair83005782015-12-11 14:46:03 -080054import zuul.lib.connections
Clark Boylanb640e052014-04-03 16:41:46 -070055import zuul.merger.client
James E. Blair879dafb2015-07-17 14:04:49 -070056import zuul.merger.merger
57import zuul.merger.server
James E. Blair8d692392016-04-08 17:47:58 -070058import zuul.nodepool
Clark Boylanb640e052014-04-03 16:41:46 -070059import zuul.reporter.gerrit
60import zuul.reporter.smtp
Joshua Hesketh850ccb62014-11-27 11:31:02 +110061import zuul.source.gerrit
Clark Boylanb640e052014-04-03 16:41:46 -070062import zuul.trigger.gerrit
63import zuul.trigger.timer
James E. Blairc494d542014-08-06 09:23:52 -070064import zuul.trigger.zuultrigger
Clark Boylanb640e052014-04-03 16:41:46 -070065
66FIXTURE_DIR = os.path.join(os.path.dirname(__file__),
67 'fixtures')
James E. Blair97d902e2014-08-21 13:25:56 -070068USE_TEMPDIR = True
Clark Boylanb640e052014-04-03 16:41:46 -070069
70logging.basicConfig(level=logging.DEBUG,
71 format='%(asctime)s %(name)-32s '
72 '%(levelname)-8s %(message)s')
73
74
75def repack_repo(path):
76 cmd = ['git', '--git-dir=%s/.git' % path, 'repack', '-afd']
77 output = subprocess.Popen(cmd, close_fds=True,
78 stdout=subprocess.PIPE,
79 stderr=subprocess.PIPE)
80 out = output.communicate()
81 if output.returncode:
82 raise Exception("git repack returned %d" % output.returncode)
83 return out
84
85
86def random_sha1():
87 return hashlib.sha1(str(random.random())).hexdigest()
88
89
James E. Blaira190f3b2015-01-05 14:56:54 -080090def iterate_timeout(max_seconds, purpose):
91 start = time.time()
92 count = 0
93 while (time.time() < start + max_seconds):
94 count += 1
95 yield count
96 time.sleep(0)
97 raise Exception("Timeout waiting for %s" % purpose)
98
99
Clark Boylanb640e052014-04-03 16:41:46 -0700100class ChangeReference(git.Reference):
101 _common_path_default = "refs/changes"
102 _points_to_commits_only = True
103
104
105class FakeChange(object):
106 categories = {'APRV': ('Approved', -1, 1),
107 'CRVW': ('Code-Review', -2, 2),
108 'VRFY': ('Verified', -2, 2)}
109
110 def __init__(self, gerrit, number, project, branch, subject,
111 status='NEW', upstream_root=None):
112 self.gerrit = gerrit
113 self.reported = 0
114 self.queried = 0
115 self.patchsets = []
116 self.number = number
117 self.project = project
118 self.branch = branch
119 self.subject = subject
120 self.latest_patchset = 0
121 self.depends_on_change = None
122 self.needed_by_changes = []
123 self.fail_merge = False
124 self.messages = []
125 self.data = {
126 'branch': branch,
127 'comments': [],
128 'commitMessage': subject,
129 'createdOn': time.time(),
130 'id': 'I' + random_sha1(),
131 'lastUpdated': time.time(),
132 'number': str(number),
133 'open': status == 'NEW',
134 'owner': {'email': 'user@example.com',
135 'name': 'User Name',
136 'username': 'username'},
137 'patchSets': self.patchsets,
138 'project': project,
139 'status': status,
140 'subject': subject,
141 'submitRecords': [],
142 'url': 'https://hostname/%s' % number}
143
144 self.upstream_root = upstream_root
145 self.addPatchset()
146 self.data['submitRecords'] = self.getSubmitRecords()
147 self.open = status == 'NEW'
148
149 def add_fake_change_to_repo(self, msg, fn, large):
150 path = os.path.join(self.upstream_root, self.project)
151 repo = git.Repo(path)
152 ref = ChangeReference.create(repo, '1/%s/%s' % (self.number,
153 self.latest_patchset),
154 'refs/tags/init')
155 repo.head.reference = ref
James E. Blair879dafb2015-07-17 14:04:49 -0700156 zuul.merger.merger.reset_repo_to_head(repo)
Clark Boylanb640e052014-04-03 16:41:46 -0700157 repo.git.clean('-x', '-f', '-d')
158
159 path = os.path.join(self.upstream_root, self.project)
160 if not large:
161 fn = os.path.join(path, fn)
162 f = open(fn, 'w')
163 f.write("test %s %s %s\n" %
164 (self.branch, self.number, self.latest_patchset))
165 f.close()
166 repo.index.add([fn])
167 else:
168 for fni in range(100):
169 fn = os.path.join(path, str(fni))
170 f = open(fn, 'w')
171 for ci in range(4096):
172 f.write(random.choice(string.printable))
173 f.close()
174 repo.index.add([fn])
175
176 r = repo.index.commit(msg)
177 repo.head.reference = 'master'
James E. Blair879dafb2015-07-17 14:04:49 -0700178 zuul.merger.merger.reset_repo_to_head(repo)
Clark Boylanb640e052014-04-03 16:41:46 -0700179 repo.git.clean('-x', '-f', '-d')
180 repo.heads['master'].checkout()
181 return r
182
183 def addPatchset(self, files=[], large=False):
184 self.latest_patchset += 1
185 if files:
186 fn = files[0]
187 else:
James E. Blair97d902e2014-08-21 13:25:56 -0700188 fn = '%s-%s' % (self.branch.replace('/', '_'), self.number)
Clark Boylanb640e052014-04-03 16:41:46 -0700189 msg = self.subject + '-' + str(self.latest_patchset)
190 c = self.add_fake_change_to_repo(msg, fn, large)
191 ps_files = [{'file': '/COMMIT_MSG',
192 'type': 'ADDED'},
193 {'file': 'README',
194 'type': 'MODIFIED'}]
195 for f in files:
196 ps_files.append({'file': f, 'type': 'ADDED'})
197 d = {'approvals': [],
198 'createdOn': time.time(),
199 'files': ps_files,
200 'number': str(self.latest_patchset),
201 'ref': 'refs/changes/1/%s/%s' % (self.number,
202 self.latest_patchset),
203 'revision': c.hexsha,
204 'uploader': {'email': 'user@example.com',
205 'name': 'User name',
206 'username': 'user'}}
207 self.data['currentPatchSet'] = d
208 self.patchsets.append(d)
209 self.data['submitRecords'] = self.getSubmitRecords()
210
211 def getPatchsetCreatedEvent(self, patchset):
212 event = {"type": "patchset-created",
213 "change": {"project": self.project,
214 "branch": self.branch,
215 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
216 "number": str(self.number),
217 "subject": self.subject,
218 "owner": {"name": "User Name"},
219 "url": "https://hostname/3"},
220 "patchSet": self.patchsets[patchset - 1],
221 "uploader": {"name": "User Name"}}
222 return event
223
224 def getChangeRestoredEvent(self):
225 event = {"type": "change-restored",
226 "change": {"project": self.project,
227 "branch": self.branch,
228 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
229 "number": str(self.number),
230 "subject": self.subject,
231 "owner": {"name": "User Name"},
232 "url": "https://hostname/3"},
233 "restorer": {"name": "User Name"},
Antoine Mussobd86a312014-01-08 14:51:33 +0100234 "patchSet": self.patchsets[-1],
235 "reason": ""}
236 return event
237
238 def getChangeAbandonedEvent(self):
239 event = {"type": "change-abandoned",
240 "change": {"project": self.project,
241 "branch": self.branch,
242 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
243 "number": str(self.number),
244 "subject": self.subject,
245 "owner": {"name": "User Name"},
246 "url": "https://hostname/3"},
247 "abandoner": {"name": "User Name"},
248 "patchSet": self.patchsets[-1],
Clark Boylanb640e052014-04-03 16:41:46 -0700249 "reason": ""}
250 return event
251
252 def getChangeCommentEvent(self, patchset):
253 event = {"type": "comment-added",
254 "change": {"project": self.project,
255 "branch": self.branch,
256 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
257 "number": str(self.number),
258 "subject": self.subject,
259 "owner": {"name": "User Name"},
260 "url": "https://hostname/3"},
261 "patchSet": self.patchsets[patchset - 1],
262 "author": {"name": "User Name"},
263 "approvals": [{"type": "Code-Review",
264 "description": "Code-Review",
265 "value": "0"}],
266 "comment": "This is a comment"}
267 return event
268
Joshua Hesketh642824b2014-07-01 17:54:59 +1000269 def addApproval(self, category, value, username='reviewer_john',
270 granted_on=None, message=''):
Clark Boylanb640e052014-04-03 16:41:46 -0700271 if not granted_on:
272 granted_on = time.time()
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000273 approval = {
274 'description': self.categories[category][0],
275 'type': category,
276 'value': str(value),
277 'by': {
278 'username': username,
279 'email': username + '@example.com',
280 },
281 'grantedOn': int(granted_on)
282 }
Clark Boylanb640e052014-04-03 16:41:46 -0700283 for i, x in enumerate(self.patchsets[-1]['approvals'][:]):
284 if x['by']['username'] == username and x['type'] == category:
285 del self.patchsets[-1]['approvals'][i]
286 self.patchsets[-1]['approvals'].append(approval)
287 event = {'approvals': [approval],
Joshua Hesketh642824b2014-07-01 17:54:59 +1000288 'author': {'email': 'author@example.com',
289 'name': 'Patchset Author',
290 'username': 'author_phil'},
Clark Boylanb640e052014-04-03 16:41:46 -0700291 'change': {'branch': self.branch,
292 'id': 'Iaa69c46accf97d0598111724a38250ae76a22c87',
293 'number': str(self.number),
Joshua Hesketh642824b2014-07-01 17:54:59 +1000294 'owner': {'email': 'owner@example.com',
295 'name': 'Change Owner',
296 'username': 'owner_jane'},
Clark Boylanb640e052014-04-03 16:41:46 -0700297 'project': self.project,
298 'subject': self.subject,
299 'topic': 'master',
300 'url': 'https://hostname/459'},
Joshua Hesketh642824b2014-07-01 17:54:59 +1000301 'comment': message,
Clark Boylanb640e052014-04-03 16:41:46 -0700302 'patchSet': self.patchsets[-1],
303 'type': 'comment-added'}
304 self.data['submitRecords'] = self.getSubmitRecords()
305 return json.loads(json.dumps(event))
306
307 def getSubmitRecords(self):
308 status = {}
309 for cat in self.categories.keys():
310 status[cat] = 0
311
312 for a in self.patchsets[-1]['approvals']:
313 cur = status[a['type']]
314 cat_min, cat_max = self.categories[a['type']][1:]
315 new = int(a['value'])
316 if new == cat_min:
317 cur = new
318 elif abs(new) > abs(cur):
319 cur = new
320 status[a['type']] = cur
321
322 labels = []
323 ok = True
324 for typ, cat in self.categories.items():
325 cur = status[typ]
326 cat_min, cat_max = cat[1:]
327 if cur == cat_min:
328 value = 'REJECT'
329 ok = False
330 elif cur == cat_max:
331 value = 'OK'
332 else:
333 value = 'NEED'
334 ok = False
335 labels.append({'label': cat[0], 'status': value})
336 if ok:
337 return [{'status': 'OK'}]
338 return [{'status': 'NOT_READY',
339 'labels': labels}]
340
341 def setDependsOn(self, other, patchset):
342 self.depends_on_change = other
343 d = {'id': other.data['id'],
344 'number': other.data['number'],
345 'ref': other.patchsets[patchset - 1]['ref']
346 }
347 self.data['dependsOn'] = [d]
348
349 other.needed_by_changes.append(self)
350 needed = other.data.get('neededBy', [])
351 d = {'id': self.data['id'],
352 'number': self.data['number'],
353 'ref': self.patchsets[patchset - 1]['ref'],
354 'revision': self.patchsets[patchset - 1]['revision']
355 }
356 needed.append(d)
357 other.data['neededBy'] = needed
358
359 def query(self):
360 self.queried += 1
361 d = self.data.get('dependsOn')
362 if d:
363 d = d[0]
364 if (self.depends_on_change.patchsets[-1]['ref'] == d['ref']):
365 d['isCurrentPatchSet'] = True
366 else:
367 d['isCurrentPatchSet'] = False
368 return json.loads(json.dumps(self.data))
369
370 def setMerged(self):
371 if (self.depends_on_change and
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000372 self.depends_on_change.data['status'] != 'MERGED'):
Clark Boylanb640e052014-04-03 16:41:46 -0700373 return
374 if self.fail_merge:
375 return
376 self.data['status'] = 'MERGED'
377 self.open = False
378
379 path = os.path.join(self.upstream_root, self.project)
380 repo = git.Repo(path)
381 repo.heads[self.branch].commit = \
382 repo.commit(self.patchsets[-1]['revision'])
383
384 def setReported(self):
385 self.reported += 1
386
387
Joshua Hesketh352264b2015-08-11 23:42:08 +1000388class FakeGerritConnection(zuul.connection.gerrit.GerritConnection):
389 log = logging.getLogger("zuul.test.FakeGerritConnection")
James E. Blair96698e22015-04-02 07:48:21 -0700390
Joshua Hesketh352264b2015-08-11 23:42:08 +1000391 def __init__(self, connection_name, connection_config,
Jan Hruban6b71aff2015-10-22 16:58:08 +0200392 changes_db=None, queues_db=None, upstream_root=None):
Joshua Hesketh352264b2015-08-11 23:42:08 +1000393 super(FakeGerritConnection, self).__init__(connection_name,
394 connection_config)
395
396 self.event_queue = queues_db
Clark Boylanb640e052014-04-03 16:41:46 -0700397 self.fixture_dir = os.path.join(FIXTURE_DIR, 'gerrit')
398 self.change_number = 0
Joshua Hesketh352264b2015-08-11 23:42:08 +1000399 self.changes = changes_db
James E. Blairf8ff9932014-08-15 15:24:24 -0700400 self.queries = []
Jan Hruban6b71aff2015-10-22 16:58:08 +0200401 self.upstream_root = upstream_root
Clark Boylanb640e052014-04-03 16:41:46 -0700402
403 def addFakeChange(self, project, branch, subject, status='NEW'):
404 self.change_number += 1
405 c = FakeChange(self, self.change_number, project, branch, subject,
406 upstream_root=self.upstream_root,
407 status=status)
408 self.changes[self.change_number] = c
409 return c
410
Clark Boylanb640e052014-04-03 16:41:46 -0700411 def review(self, project, changeid, message, action):
412 number, ps = changeid.split(',')
413 change = self.changes[int(number)]
Joshua Hesketh642824b2014-07-01 17:54:59 +1000414
415 # Add the approval back onto the change (ie simulate what gerrit would
416 # do).
417 # Usually when zuul leaves a review it'll create a feedback loop where
418 # zuul's review enters another gerrit event (which is then picked up by
419 # zuul). However, we can't mimic this behaviour (by adding this
420 # approval event into the queue) as it stops jobs from checking what
421 # happens before this event is triggered. If a job needs to see what
422 # happens they can add their own verified event into the queue.
423 # Nevertheless, we can update change with the new review in gerrit.
424
425 for cat in ['CRVW', 'VRFY', 'APRV']:
426 if cat in action:
Joshua Hesketh352264b2015-08-11 23:42:08 +1000427 change.addApproval(cat, action[cat], username=self.user)
Joshua Hesketh642824b2014-07-01 17:54:59 +1000428
429 if 'label' in action:
430 parts = action['label'].split('=')
Joshua Hesketh352264b2015-08-11 23:42:08 +1000431 change.addApproval(parts[0], parts[2], username=self.user)
Joshua Hesketh642824b2014-07-01 17:54:59 +1000432
Clark Boylanb640e052014-04-03 16:41:46 -0700433 change.messages.append(message)
Joshua Hesketh642824b2014-07-01 17:54:59 +1000434
Clark Boylanb640e052014-04-03 16:41:46 -0700435 if 'submit' in action:
436 change.setMerged()
437 if message:
438 change.setReported()
439
440 def query(self, number):
441 change = self.changes.get(int(number))
442 if change:
443 return change.query()
444 return {}
445
James E. Blairc494d542014-08-06 09:23:52 -0700446 def simpleQuery(self, query):
James E. Blair96698e22015-04-02 07:48:21 -0700447 self.log.debug("simpleQuery: %s" % query)
James E. Blairf8ff9932014-08-15 15:24:24 -0700448 self.queries.append(query)
James E. Blair5ee24252014-12-30 10:12:29 -0800449 if query.startswith('change:'):
450 # Query a specific changeid
451 changeid = query[len('change:'):]
452 l = [change.query() for change in self.changes.values()
453 if change.data['id'] == changeid]
James E. Blair96698e22015-04-02 07:48:21 -0700454 elif query.startswith('message:'):
455 # Query the content of a commit message
456 msg = query[len('message:'):].strip()
457 l = [change.query() for change in self.changes.values()
458 if msg in change.data['commitMessage']]
James E. Blair5ee24252014-12-30 10:12:29 -0800459 else:
460 # Query all open changes
461 l = [change.query() for change in self.changes.values()]
James E. Blairf8ff9932014-08-15 15:24:24 -0700462 return l
James E. Blairc494d542014-08-06 09:23:52 -0700463
Joshua Hesketh352264b2015-08-11 23:42:08 +1000464 def _start_watcher_thread(self, *args, **kw):
Clark Boylanb640e052014-04-03 16:41:46 -0700465 pass
466
Joshua Hesketh352264b2015-08-11 23:42:08 +1000467 def getGitUrl(self, project):
468 return os.path.join(self.upstream_root, project.name)
469
Clark Boylanb640e052014-04-03 16:41:46 -0700470
471class BuildHistory(object):
472 def __init__(self, **kw):
473 self.__dict__.update(kw)
474
475 def __repr__(self):
476 return ("<Completed build, result: %s name: %s #%s changes: %s>" %
477 (self.result, self.name, self.number, self.changes))
478
479
480class FakeURLOpener(object):
Jan Hruban6b71aff2015-10-22 16:58:08 +0200481 def __init__(self, upstream_root, url):
Clark Boylanb640e052014-04-03 16:41:46 -0700482 self.upstream_root = upstream_root
Clark Boylanb640e052014-04-03 16:41:46 -0700483 self.url = url
484
485 def read(self):
Morgan Fainberg293f7f82016-05-30 14:01:22 -0700486 res = urllib.parse.urlparse(self.url)
Clark Boylanb640e052014-04-03 16:41:46 -0700487 path = res.path
488 project = '/'.join(path.split('/')[2:-2])
489 ret = '001e# service=git-upload-pack\n'
490 ret += ('000000a31270149696713ba7e06f1beb760f20d359c4abed HEAD\x00'
491 'multi_ack thin-pack side-band side-band-64k ofs-delta '
492 'shallow no-progress include-tag multi_ack_detailed no-done\n')
493 path = os.path.join(self.upstream_root, project)
494 repo = git.Repo(path)
495 for ref in repo.refs:
496 r = ref.object.hexsha + ' ' + ref.path + '\n'
497 ret += '%04x%s' % (len(r) + 4, r)
498 ret += '0000'
499 return ret
500
501
Clark Boylanb640e052014-04-03 16:41:46 -0700502class FakeStatsd(threading.Thread):
503 def __init__(self):
504 threading.Thread.__init__(self)
505 self.daemon = True
506 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
507 self.sock.bind(('', 0))
508 self.port = self.sock.getsockname()[1]
509 self.wake_read, self.wake_write = os.pipe()
510 self.stats = []
511
512 def run(self):
513 while True:
514 poll = select.poll()
515 poll.register(self.sock, select.POLLIN)
516 poll.register(self.wake_read, select.POLLIN)
517 ret = poll.poll()
518 for (fd, event) in ret:
519 if fd == self.sock.fileno():
520 data = self.sock.recvfrom(1024)
521 if not data:
522 return
523 self.stats.append(data[0])
524 if fd == self.wake_read:
525 return
526
527 def stop(self):
528 os.write(self.wake_write, '1\n')
529
530
531class FakeBuild(threading.Thread):
532 log = logging.getLogger("zuul.test")
533
534 def __init__(self, worker, job, number, node):
535 threading.Thread.__init__(self)
536 self.daemon = True
537 self.worker = worker
538 self.job = job
539 self.name = job.name.split(':')[1]
540 self.number = number
541 self.node = node
542 self.parameters = json.loads(job.arguments)
543 self.unique = self.parameters['ZUUL_UUID']
544 self.wait_condition = threading.Condition()
545 self.waiting = False
546 self.aborted = False
547 self.created = time.time()
548 self.description = ''
549 self.run_error = False
550
551 def release(self):
552 self.wait_condition.acquire()
553 self.wait_condition.notify()
554 self.waiting = False
555 self.log.debug("Build %s released" % self.unique)
556 self.wait_condition.release()
557
558 def isWaiting(self):
559 self.wait_condition.acquire()
560 if self.waiting:
561 ret = True
562 else:
563 ret = False
564 self.wait_condition.release()
565 return ret
566
567 def _wait(self):
568 self.wait_condition.acquire()
569 self.waiting = True
570 self.log.debug("Build %s waiting" % self.unique)
571 self.wait_condition.wait()
572 self.wait_condition.release()
573
574 def run(self):
575 data = {
576 'url': 'https://server/job/%s/%s/' % (self.name, self.number),
577 'name': self.name,
578 'number': self.number,
579 'manager': self.worker.worker_id,
580 'worker_name': 'My Worker',
581 'worker_hostname': 'localhost',
582 'worker_ips': ['127.0.0.1', '192.168.1.1'],
583 'worker_fqdn': 'zuul.example.org',
584 'worker_program': 'FakeBuilder',
585 'worker_version': 'v1.1',
586 'worker_extra': {'something': 'else'}
587 }
588
589 self.log.debug('Running build %s' % self.unique)
590
591 self.job.sendWorkData(json.dumps(data))
592 self.log.debug('Sent WorkData packet with %s' % json.dumps(data))
593 self.job.sendWorkStatus(0, 100)
594
595 if self.worker.hold_jobs_in_build:
596 self.log.debug('Holding build %s' % self.unique)
597 self._wait()
598 self.log.debug("Build %s continuing" % self.unique)
599
600 self.worker.lock.acquire()
601
602 result = 'SUCCESS'
603 if (('ZUUL_REF' in self.parameters) and
604 self.worker.shouldFailTest(self.name,
605 self.parameters['ZUUL_REF'])):
606 result = 'FAILURE'
607 if self.aborted:
608 result = 'ABORTED'
609
610 if self.run_error:
611 work_fail = True
612 result = 'RUN_ERROR'
613 else:
614 data['result'] = result
Timothy Chavezb2332082015-08-07 20:08:04 -0500615 data['node_labels'] = ['bare-necessities']
616 data['node_name'] = 'foo'
Clark Boylanb640e052014-04-03 16:41:46 -0700617 work_fail = False
618
619 changes = None
620 if 'ZUUL_CHANGE_IDS' in self.parameters:
621 changes = self.parameters['ZUUL_CHANGE_IDS']
622
623 self.worker.build_history.append(
624 BuildHistory(name=self.name, number=self.number,
625 result=result, changes=changes, node=self.node,
626 uuid=self.unique, description=self.description,
James E. Blair456f2fb2016-02-09 09:29:33 -0800627 parameters=self.parameters,
Clark Boylanb640e052014-04-03 16:41:46 -0700628 pipeline=self.parameters['ZUUL_PIPELINE'])
629 )
630
631 self.job.sendWorkData(json.dumps(data))
632 if work_fail:
633 self.job.sendWorkFail()
634 else:
635 self.job.sendWorkComplete(json.dumps(data))
636 del self.worker.gearman_jobs[self.job.unique]
637 self.worker.running_builds.remove(self)
638 self.worker.lock.release()
639
640
Joshua Hesketh0c54b2a2016-04-11 21:23:33 +1000641class RecordingLaunchServer(zuul.launcher.server.LaunchServer):
James E. Blairf5dbd002015-12-23 15:26:17 -0800642 def __init__(self, *args, **kw):
643 super(RecordingLaunchServer, self).__init__(*args, **kw)
644 self.job_history = []
645
646 def launch(self, job):
647 self.job_history.append(job)
648 job.data = []
649
650 def sendWorkComplete(data=b''):
651 job.data.append(data)
652 gear.WorkerJob.sendWorkComplete(job, data)
653
654 job.sendWorkComplete = sendWorkComplete
655 super(RecordingLaunchServer, self).launch(job)
656
657
Clark Boylanb640e052014-04-03 16:41:46 -0700658class FakeWorker(gear.Worker):
659 def __init__(self, worker_id, test):
660 super(FakeWorker, self).__init__(worker_id)
661 self.gearman_jobs = {}
662 self.build_history = []
663 self.running_builds = []
664 self.build_counter = 0
665 self.fail_tests = {}
666 self.test = test
667
668 self.hold_jobs_in_build = False
669 self.lock = threading.Lock()
670 self.__work_thread = threading.Thread(target=self.work)
671 self.__work_thread.daemon = True
672 self.__work_thread.start()
673
674 def handleJob(self, job):
675 parts = job.name.split(":")
676 cmd = parts[0]
677 name = parts[1]
678 if len(parts) > 2:
679 node = parts[2]
680 else:
681 node = None
682 if cmd == 'build':
683 self.handleBuild(job, name, node)
684 elif cmd == 'stop':
685 self.handleStop(job, name)
686 elif cmd == 'set_description':
687 self.handleSetDescription(job, name)
688
689 def handleBuild(self, job, name, node):
690 build = FakeBuild(self, job, self.build_counter, node)
691 job.build = build
692 self.gearman_jobs[job.unique] = job
693 self.build_counter += 1
694
695 self.running_builds.append(build)
696 build.start()
697
698 def handleStop(self, job, name):
699 self.log.debug("handle stop")
700 parameters = json.loads(job.arguments)
701 name = parameters['name']
702 number = parameters['number']
703 for build in self.running_builds:
704 if build.name == name and build.number == number:
705 build.aborted = True
706 build.release()
707 job.sendWorkComplete()
708 return
709 job.sendWorkFail()
710
711 def handleSetDescription(self, job, name):
712 self.log.debug("handle set description")
713 parameters = json.loads(job.arguments)
714 name = parameters['name']
715 number = parameters['number']
716 descr = parameters['html_description']
717 for build in self.running_builds:
718 if build.name == name and build.number == number:
719 build.description = descr
720 job.sendWorkComplete()
721 return
722 for build in self.build_history:
723 if build.name == name and build.number == number:
724 build.description = descr
725 job.sendWorkComplete()
726 return
727 job.sendWorkFail()
728
729 def work(self):
730 while self.running:
731 try:
732 job = self.getJob()
733 except gear.InterruptedError:
734 continue
735 try:
736 self.handleJob(job)
737 except:
738 self.log.exception("Worker exception:")
739
740 def addFailTest(self, name, change):
741 l = self.fail_tests.get(name, [])
742 l.append(change)
743 self.fail_tests[name] = l
744
745 def shouldFailTest(self, name, ref):
746 l = self.fail_tests.get(name, [])
747 for change in l:
748 if self.test.ref_has_change(ref, change):
749 return True
750 return False
751
752 def release(self, regex=None):
753 builds = self.running_builds[:]
754 self.log.debug("releasing build %s (%s)" % (regex,
755 len(self.running_builds)))
756 for build in builds:
757 if not regex or re.match(regex, build.name):
758 self.log.debug("releasing build %s" %
759 (build.parameters['ZUUL_UUID']))
760 build.release()
761 else:
762 self.log.debug("not releasing build %s" %
763 (build.parameters['ZUUL_UUID']))
764 self.log.debug("done releasing builds %s (%s)" %
765 (regex, len(self.running_builds)))
766
767
768class FakeGearmanServer(gear.Server):
769 def __init__(self):
770 self.hold_jobs_in_queue = False
771 super(FakeGearmanServer, self).__init__(0)
772
773 def getJobForConnection(self, connection, peek=False):
774 for queue in [self.high_queue, self.normal_queue, self.low_queue]:
775 for job in queue:
776 if not hasattr(job, 'waiting'):
777 if job.name.startswith('build:'):
778 job.waiting = self.hold_jobs_in_queue
779 else:
780 job.waiting = False
781 if job.waiting:
782 continue
783 if job.name in connection.functions:
784 if not peek:
785 queue.remove(job)
786 connection.related_jobs[job.handle] = job
787 job.worker_connection = connection
788 job.running = True
789 return job
790 return None
791
792 def release(self, regex=None):
793 released = False
794 qlen = (len(self.high_queue) + len(self.normal_queue) +
795 len(self.low_queue))
796 self.log.debug("releasing queued job %s (%s)" % (regex, qlen))
797 for job in self.getQueue():
798 cmd, name = job.name.split(':')
799 if cmd != 'build':
800 continue
801 if not regex or re.match(regex, name):
802 self.log.debug("releasing queued job %s" %
803 job.unique)
804 job.waiting = False
805 released = True
806 else:
807 self.log.debug("not releasing queued job %s" %
808 job.unique)
809 if released:
810 self.wakeConnections()
811 qlen = (len(self.high_queue) + len(self.normal_queue) +
812 len(self.low_queue))
813 self.log.debug("done releasing queued jobs %s (%s)" % (regex, qlen))
814
815
816class FakeSMTP(object):
817 log = logging.getLogger('zuul.FakeSMTP')
818
819 def __init__(self, messages, server, port):
820 self.server = server
821 self.port = port
822 self.messages = messages
823
824 def sendmail(self, from_email, to_email, msg):
825 self.log.info("Sending email from %s, to %s, with msg %s" % (
826 from_email, to_email, msg))
827
828 headers = msg.split('\n\n', 1)[0]
829 body = msg.split('\n\n', 1)[1]
830
831 self.messages.append(dict(
832 from_email=from_email,
833 to_email=to_email,
834 msg=msg,
835 headers=headers,
836 body=body,
837 ))
838
839 return True
840
841 def quit(self):
842 return True
843
844
845class FakeSwiftClientConnection(swiftclient.client.Connection):
846 def post_account(self, headers):
847 # Do nothing
848 pass
849
850 def get_auth(self):
851 # Returns endpoint and (unused) auth token
852 endpoint = os.path.join('https://storage.example.org', 'V1',
853 'AUTH_account')
854 return endpoint, ''
855
856
Maru Newby3fe5f852015-01-13 04:22:14 +0000857class BaseTestCase(testtools.TestCase):
Clark Boylanb640e052014-04-03 16:41:46 -0700858 log = logging.getLogger("zuul.test")
859
860 def setUp(self):
Maru Newby3fe5f852015-01-13 04:22:14 +0000861 super(BaseTestCase, self).setUp()
Clark Boylanb640e052014-04-03 16:41:46 -0700862 test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
863 try:
864 test_timeout = int(test_timeout)
865 except ValueError:
866 # If timeout value is invalid do not set a timeout.
867 test_timeout = 0
868 if test_timeout > 0:
869 self.useFixture(fixtures.Timeout(test_timeout, gentle=False))
870
871 if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or
872 os.environ.get('OS_STDOUT_CAPTURE') == '1'):
873 stdout = self.useFixture(fixtures.StringStream('stdout')).stream
874 self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
875 if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or
876 os.environ.get('OS_STDERR_CAPTURE') == '1'):
877 stderr = self.useFixture(fixtures.StringStream('stderr')).stream
878 self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
879 if (os.environ.get('OS_LOG_CAPTURE') == 'True' or
880 os.environ.get('OS_LOG_CAPTURE') == '1'):
881 self.useFixture(fixtures.FakeLogger(
882 level=logging.DEBUG,
883 format='%(asctime)s %(name)-32s '
884 '%(levelname)-8s %(message)s'))
Maru Newby3fe5f852015-01-13 04:22:14 +0000885
Morgan Fainbergd34e0b42016-06-09 19:10:38 -0700886 # NOTE(notmorgan): Extract logging overrides for specific libraries
887 # from the OS_LOG_DEFAULTS env and create FakeLogger fixtures for
888 # each. This is used to limit the output during test runs from
889 # libraries that zuul depends on such as gear.
890 log_defaults_from_env = os.environ.get('OS_LOG_DEFAULTS')
891
892 if log_defaults_from_env:
893 for default in log_defaults_from_env.split(','):
894 try:
895 name, level_str = default.split('=', 1)
896 level = getattr(logging, level_str, logging.DEBUG)
897 self.useFixture(fixtures.FakeLogger(
898 name=name,
899 level=level,
900 format='%(asctime)s %(name)-32s '
901 '%(levelname)-8s %(message)s'))
902 except ValueError:
903 # NOTE(notmorgan): Invalid format of the log default,
904 # skip and don't try and apply a logger for the
905 # specified module
906 pass
907
Maru Newby3fe5f852015-01-13 04:22:14 +0000908
909class ZuulTestCase(BaseTestCase):
James E. Blair83005782015-12-11 14:46:03 -0800910 config_file = 'zuul.conf'
Maru Newby3fe5f852015-01-13 04:22:14 +0000911
912 def setUp(self):
913 super(ZuulTestCase, self).setUp()
James E. Blair97d902e2014-08-21 13:25:56 -0700914 if USE_TEMPDIR:
915 tmp_root = self.useFixture(fixtures.TempDir(
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000916 rootdir=os.environ.get("ZUUL_TEST_ROOT"))
917 ).path
James E. Blair97d902e2014-08-21 13:25:56 -0700918 else:
919 tmp_root = os.environ.get("ZUUL_TEST_ROOT")
Clark Boylanb640e052014-04-03 16:41:46 -0700920 self.test_root = os.path.join(tmp_root, "zuul-test")
921 self.upstream_root = os.path.join(self.test_root, "upstream")
922 self.git_root = os.path.join(self.test_root, "git")
James E. Blairce8a2132016-05-19 15:21:52 -0700923 self.state_root = os.path.join(self.test_root, "lib")
Clark Boylanb640e052014-04-03 16:41:46 -0700924
925 if os.path.exists(self.test_root):
926 shutil.rmtree(self.test_root)
927 os.makedirs(self.test_root)
928 os.makedirs(self.upstream_root)
James E. Blairce8a2132016-05-19 15:21:52 -0700929 os.makedirs(self.state_root)
Clark Boylanb640e052014-04-03 16:41:46 -0700930
931 # Make per test copy of Configuration.
932 self.setup_config()
James E. Blair59fdbac2015-12-07 17:08:06 -0800933 self.config.set('zuul', 'tenant_config',
Joshua Heskethacccffc2015-03-31 23:38:17 +1100934 os.path.join(FIXTURE_DIR,
James E. Blair59fdbac2015-12-07 17:08:06 -0800935 self.config.get('zuul', 'tenant_config')))
Clark Boylanb640e052014-04-03 16:41:46 -0700936 self.config.set('merger', 'git_dir', self.git_root)
James E. Blairce8a2132016-05-19 15:21:52 -0700937 self.config.set('zuul', 'state_dir', self.state_root)
Clark Boylanb640e052014-04-03 16:41:46 -0700938
939 # For each project in config:
940 self.init_repo("org/project")
941 self.init_repo("org/project1")
942 self.init_repo("org/project2")
943 self.init_repo("org/project3")
James E. Blair97d902e2014-08-21 13:25:56 -0700944 self.init_repo("org/project4")
James E. Blairbce35e12014-08-21 14:31:17 -0700945 self.init_repo("org/project5")
946 self.init_repo("org/project6")
Clark Boylanb640e052014-04-03 16:41:46 -0700947 self.init_repo("org/one-job-project")
948 self.init_repo("org/nonvoting-project")
949 self.init_repo("org/templated-project")
950 self.init_repo("org/layered-project")
951 self.init_repo("org/node-project")
952 self.init_repo("org/conflict-project")
953 self.init_repo("org/noop-project")
954 self.init_repo("org/experimental-project")
Evgeny Antyshevd6e546c2015-06-11 15:13:57 +0000955 self.init_repo("org/no-jobs-project")
Clark Boylanb640e052014-04-03 16:41:46 -0700956
James E. Blair83005782015-12-11 14:46:03 -0800957 self.setup_repos()
958
Clark Boylanb640e052014-04-03 16:41:46 -0700959 self.statsd = FakeStatsd()
Ian Wienandff977bf2015-09-30 15:38:47 +1000960 # note, use 127.0.0.1 rather than localhost to avoid getting ipv6
961 # see: https://github.com/jsocol/pystatsd/issues/61
962 os.environ['STATSD_HOST'] = '127.0.0.1'
Clark Boylanb640e052014-04-03 16:41:46 -0700963 os.environ['STATSD_PORT'] = str(self.statsd.port)
964 self.statsd.start()
965 # the statsd client object is configured in the statsd module import
Monty Taylor74fa3862016-06-02 07:39:49 +0300966 reload_module(statsd)
967 reload_module(zuul.scheduler)
Clark Boylanb640e052014-04-03 16:41:46 -0700968
969 self.gearman_server = FakeGearmanServer()
970
971 self.config.set('gearman', 'port', str(self.gearman_server.port))
972
Joshua Hesketh352264b2015-08-11 23:42:08 +1000973 zuul.source.gerrit.GerritSource.replication_timeout = 1.5
974 zuul.source.gerrit.GerritSource.replication_retry_interval = 0.5
975 zuul.connection.gerrit.GerritEventConnector.delay = 0.0
Clark Boylanb640e052014-04-03 16:41:46 -0700976
Joshua Hesketh352264b2015-08-11 23:42:08 +1000977 self.sched = zuul.scheduler.Scheduler(self.config)
Clark Boylanb640e052014-04-03 16:41:46 -0700978
979 self.useFixture(fixtures.MonkeyPatch('swiftclient.client.Connection',
980 FakeSwiftClientConnection))
981 self.swift = zuul.lib.swift.Swift(self.config)
982
Jan Hruban6b71aff2015-10-22 16:58:08 +0200983 self.event_queues = [
984 self.sched.result_event_queue,
985 self.sched.trigger_event_queue
986 ]
987
James E. Blairfef78942016-03-11 16:28:56 -0800988 self.configure_connections()
Joshua Hesketh352264b2015-08-11 23:42:08 +1000989 self.sched.registerConnections(self.connections)
Joshua Hesketh352264b2015-08-11 23:42:08 +1000990
James E. Blairf5dbd002015-12-23 15:26:17 -0800991 self.ansible_server = RecordingLaunchServer(
992 self.config, self.connections)
993 self.ansible_server.start()
994
Clark Boylanb640e052014-04-03 16:41:46 -0700995 def URLOpenerFactory(*args, **kw):
Morgan Fainberg293f7f82016-05-30 14:01:22 -0700996 if isinstance(args[0], urllib.request.Request):
Clark Boylanb640e052014-04-03 16:41:46 -0700997 return old_urlopen(*args, **kw)
Clark Boylanb640e052014-04-03 16:41:46 -0700998 return FakeURLOpener(self.upstream_root, *args, **kw)
999
Morgan Fainberg293f7f82016-05-30 14:01:22 -07001000 old_urlopen = urllib.request.urlopen
1001 urllib.request.urlopen = URLOpenerFactory
Clark Boylanb640e052014-04-03 16:41:46 -07001002
Joshua Hesketh0c54b2a2016-04-11 21:23:33 +10001003 self.launcher = zuul.launcher.client.LaunchClient(
James E. Blair82938472016-01-11 14:38:13 -08001004 self.config, self.sched, self.swift)
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001005 self.merge_client = zuul.merger.client.MergeClient(
1006 self.config, self.sched)
James E. Blair8d692392016-04-08 17:47:58 -07001007 self.nodepool = zuul.nodepool.Nodepool(self.sched)
Clark Boylanb640e052014-04-03 16:41:46 -07001008
1009 self.sched.setLauncher(self.launcher)
1010 self.sched.setMerger(self.merge_client)
James E. Blair8d692392016-04-08 17:47:58 -07001011 self.sched.setNodepool(self.nodepool)
Clark Boylanb640e052014-04-03 16:41:46 -07001012
Paul Belanger88ef0ea2015-12-23 11:57:02 -05001013 self.webapp = zuul.webapp.WebApp(
1014 self.sched, port=0, listen_address='127.0.0.1')
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001015 self.rpc = zuul.rpclistener.RPCListener(self.config, self.sched)
Clark Boylanb640e052014-04-03 16:41:46 -07001016
1017 self.sched.start()
1018 self.sched.reconfigure(self.config)
1019 self.sched.resume()
1020 self.webapp.start()
1021 self.rpc.start()
1022 self.launcher.gearman.waitForServer()
Clark Boylanb640e052014-04-03 16:41:46 -07001023
1024 self.addCleanup(self.assertFinalState)
1025 self.addCleanup(self.shutdown)
1026
James E. Blairfef78942016-03-11 16:28:56 -08001027 def configure_connections(self):
Joshua Hesketh352264b2015-08-11 23:42:08 +10001028 # Register connections from the config
1029 self.smtp_messages = []
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001030
Joshua Hesketh352264b2015-08-11 23:42:08 +10001031 def FakeSMTPFactory(*args, **kw):
1032 args = [self.smtp_messages] + list(args)
1033 return FakeSMTP(*args, **kw)
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001034
Joshua Hesketh352264b2015-08-11 23:42:08 +10001035 self.useFixture(fixtures.MonkeyPatch('smtplib.SMTP', FakeSMTPFactory))
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001036
Joshua Hesketh352264b2015-08-11 23:42:08 +10001037 # Set a changes database so multiple FakeGerrit's can report back to
1038 # a virtual canonical database given by the configured hostname
1039 self.gerrit_changes_dbs = {}
1040 self.gerrit_queues_dbs = {}
James E. Blairfef78942016-03-11 16:28:56 -08001041 self.connections = zuul.lib.connections.ConnectionRegistry()
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001042
Joshua Hesketh352264b2015-08-11 23:42:08 +10001043 for section_name in self.config.sections():
1044 con_match = re.match(r'^connection ([\'\"]?)(.*)(\1)$',
1045 section_name, re.I)
1046 if not con_match:
1047 continue
1048 con_name = con_match.group(2)
1049 con_config = dict(self.config.items(section_name))
1050
1051 if 'driver' not in con_config:
1052 raise Exception("No driver specified for connection %s."
1053 % con_name)
1054
1055 con_driver = con_config['driver']
1056
1057 # TODO(jhesketh): load the required class automatically
1058 if con_driver == 'gerrit':
Joshua Heskethacccffc2015-03-31 23:38:17 +11001059 if con_config['server'] not in self.gerrit_changes_dbs.keys():
1060 self.gerrit_changes_dbs[con_config['server']] = {}
1061 if con_config['server'] not in self.gerrit_queues_dbs.keys():
1062 self.gerrit_queues_dbs[con_config['server']] = \
1063 Queue.Queue()
1064 self.event_queues.append(
1065 self.gerrit_queues_dbs[con_config['server']])
James E. Blair83005782015-12-11 14:46:03 -08001066 self.connections.connections[con_name] = FakeGerritConnection(
Joshua Hesketh352264b2015-08-11 23:42:08 +10001067 con_name, con_config,
Joshua Heskethacccffc2015-03-31 23:38:17 +11001068 changes_db=self.gerrit_changes_dbs[con_config['server']],
1069 queues_db=self.gerrit_queues_dbs[con_config['server']],
Jan Hruban6b71aff2015-10-22 16:58:08 +02001070 upstream_root=self.upstream_root
Joshua Hesketh352264b2015-08-11 23:42:08 +10001071 )
James E. Blair83005782015-12-11 14:46:03 -08001072 setattr(self, 'fake_' + con_name,
1073 self.connections.connections[con_name])
Joshua Hesketh352264b2015-08-11 23:42:08 +10001074 elif con_driver == 'smtp':
James E. Blair83005782015-12-11 14:46:03 -08001075 self.connections.connections[con_name] = \
Joshua Hesketh352264b2015-08-11 23:42:08 +10001076 zuul.connection.smtp.SMTPConnection(con_name, con_config)
1077 else:
1078 raise Exception("Unknown driver, %s, for connection %s"
1079 % (con_config['driver'], con_name))
1080
1081 # If the [gerrit] or [smtp] sections still exist, load them in as a
1082 # connection named 'gerrit' or 'smtp' respectfully
1083
1084 if 'gerrit' in self.config.sections():
1085 self.gerrit_changes_dbs['gerrit'] = {}
1086 self.gerrit_queues_dbs['gerrit'] = Queue.Queue()
Jan Hruban6b71aff2015-10-22 16:58:08 +02001087 self.event_queues.append(self.gerrit_queues_dbs['gerrit'])
James E. Blair83005782015-12-11 14:46:03 -08001088 self.connections.connections['gerrit'] = FakeGerritConnection(
Joshua Hesketh352264b2015-08-11 23:42:08 +10001089 '_legacy_gerrit', dict(self.config.items('gerrit')),
1090 changes_db=self.gerrit_changes_dbs['gerrit'],
1091 queues_db=self.gerrit_queues_dbs['gerrit'])
1092
1093 if 'smtp' in self.config.sections():
James E. Blair83005782015-12-11 14:46:03 -08001094 self.connections.connections['smtp'] = \
Joshua Hesketh352264b2015-08-11 23:42:08 +10001095 zuul.connection.smtp.SMTPConnection(
1096 '_legacy_smtp', dict(self.config.items('smtp')))
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001097
James E. Blair83005782015-12-11 14:46:03 -08001098 def setup_config(self):
Clark Boylanb640e052014-04-03 16:41:46 -07001099 """Per test config object. Override to set different config."""
1100 self.config = ConfigParser.ConfigParser()
James E. Blair83005782015-12-11 14:46:03 -08001101 self.config.read(os.path.join(FIXTURE_DIR, self.config_file))
James E. Blair2a629ec2015-12-22 15:32:02 -08001102 if hasattr(self, 'tenant_config_file'):
1103 self.config.set('zuul', 'tenant_config', self.tenant_config_file)
James E. Blair96c6bf82016-01-15 16:20:40 -08001104 git_path = os.path.join(
1105 os.path.dirname(
1106 os.path.join(FIXTURE_DIR, self.tenant_config_file)),
1107 'git')
1108 if os.path.exists(git_path):
1109 for reponame in os.listdir(git_path):
1110 self.copyDirToRepo(reponame,
1111 os.path.join(git_path, reponame))
1112
1113 def copyDirToRepo(self, project, source_path):
1114 repo_path = os.path.join(self.upstream_root, project)
1115 if not os.path.exists(repo_path):
1116 self.init_repo(project)
1117
1118 files = {}
1119 for (dirpath, dirnames, filenames) in os.walk(source_path):
1120 for filename in filenames:
1121 test_tree_filepath = os.path.join(dirpath, filename)
1122 common_path = os.path.commonprefix([test_tree_filepath,
1123 source_path])
1124 relative_filepath = test_tree_filepath[len(common_path) + 1:]
1125 with open(test_tree_filepath, 'r') as f:
1126 content = f.read()
1127 files[relative_filepath] = content
1128 self.addCommitToRepo(project, 'add content from fixture',
1129 files, branch='master')
James E. Blair83005782015-12-11 14:46:03 -08001130
1131 def setup_repos(self):
1132 """Subclasses can override to manipulate repos before tests"""
1133 pass
Clark Boylanb640e052014-04-03 16:41:46 -07001134
1135 def assertFinalState(self):
Clark Boylanb640e052014-04-03 16:41:46 -07001136 # Make sure that git.Repo objects have been garbage collected.
1137 repos = []
1138 gc.collect()
1139 for obj in gc.get_objects():
1140 if isinstance(obj, git.Repo):
1141 repos.append(obj)
1142 self.assertEqual(len(repos), 0)
1143 self.assertEmptyQueues()
James E. Blair83005782015-12-11 14:46:03 -08001144 ipm = zuul.manager.independent.IndependentPipelineManager
James E. Blair59fdbac2015-12-07 17:08:06 -08001145 for tenant in self.sched.abide.tenants.values():
1146 for pipeline in tenant.layout.pipelines.values():
James E. Blair83005782015-12-11 14:46:03 -08001147 if isinstance(pipeline.manager, ipm):
James E. Blair59fdbac2015-12-07 17:08:06 -08001148 self.assertEqual(len(pipeline.queues), 0)
Clark Boylanb640e052014-04-03 16:41:46 -07001149
1150 def shutdown(self):
1151 self.log.debug("Shutting down after tests")
1152 self.launcher.stop()
Clark Boylanb640e052014-04-03 16:41:46 -07001153 self.merge_client.stop()
Clark Boylanb640e052014-04-03 16:41:46 -07001154 self.sched.stop()
1155 self.sched.join()
1156 self.statsd.stop()
1157 self.statsd.join()
1158 self.webapp.stop()
1159 self.webapp.join()
1160 self.rpc.stop()
1161 self.rpc.join()
1162 self.gearman_server.shutdown()
1163 threads = threading.enumerate()
1164 if len(threads) > 1:
1165 self.log.error("More than one thread is running: %s" % threads)
Clark Boylanb640e052014-04-03 16:41:46 -07001166
1167 def init_repo(self, project):
1168 parts = project.split('/')
1169 path = os.path.join(self.upstream_root, *parts[:-1])
1170 if not os.path.exists(path):
1171 os.makedirs(path)
1172 path = os.path.join(self.upstream_root, project)
1173 repo = git.Repo.init(path)
1174
Morgan Fainberg78c301a2016-07-14 13:47:01 -07001175 with repo.config_writer() as config_writer:
1176 config_writer.set_value('user', 'email', 'user@example.com')
1177 config_writer.set_value('user', 'name', 'User Name')
Clark Boylanb640e052014-04-03 16:41:46 -07001178
1179 fn = os.path.join(path, 'README')
1180 f = open(fn, 'w')
1181 f.write("test\n")
1182 f.close()
1183 repo.index.add([fn])
1184 repo.index.commit('initial commit')
1185 master = repo.create_head('master')
1186 repo.create_tag('init')
1187
James E. Blair97d902e2014-08-21 13:25:56 -07001188 repo.head.reference = master
James E. Blair879dafb2015-07-17 14:04:49 -07001189 zuul.merger.merger.reset_repo_to_head(repo)
James E. Blair97d902e2014-08-21 13:25:56 -07001190 repo.git.clean('-x', '-f', '-d')
1191
1192 self.create_branch(project, 'mp')
1193
1194 def create_branch(self, project, branch):
1195 path = os.path.join(self.upstream_root, project)
1196 repo = git.Repo.init(path)
1197 fn = os.path.join(path, 'README')
1198
1199 branch_head = repo.create_head(branch)
1200 repo.head.reference = branch_head
Clark Boylanb640e052014-04-03 16:41:46 -07001201 f = open(fn, 'a')
James E. Blair97d902e2014-08-21 13:25:56 -07001202 f.write("test %s\n" % branch)
Clark Boylanb640e052014-04-03 16:41:46 -07001203 f.close()
1204 repo.index.add([fn])
James E. Blair97d902e2014-08-21 13:25:56 -07001205 repo.index.commit('%s commit' % branch)
Clark Boylanb640e052014-04-03 16:41:46 -07001206
James E. Blair97d902e2014-08-21 13:25:56 -07001207 repo.head.reference = repo.heads['master']
James E. Blair879dafb2015-07-17 14:04:49 -07001208 zuul.merger.merger.reset_repo_to_head(repo)
Clark Boylanb640e052014-04-03 16:41:46 -07001209 repo.git.clean('-x', '-f', '-d')
1210
Sachi King9f16d522016-03-16 12:20:45 +11001211 def create_commit(self, project):
1212 path = os.path.join(self.upstream_root, project)
1213 repo = git.Repo(path)
1214 repo.head.reference = repo.heads['master']
1215 file_name = os.path.join(path, 'README')
1216 with open(file_name, 'a') as f:
1217 f.write('creating fake commit\n')
1218 repo.index.add([file_name])
1219 commit = repo.index.commit('Creating a fake commit')
1220 return commit.hexsha
1221
Clark Boylanb640e052014-04-03 16:41:46 -07001222 def ref_has_change(self, ref, change):
1223 path = os.path.join(self.git_root, change.project)
1224 repo = git.Repo(path)
Mike Heald8225f522014-11-21 09:52:33 +00001225 try:
1226 for commit in repo.iter_commits(ref):
1227 if commit.message.strip() == ('%s-1' % change.subject):
1228 return True
1229 except GitCommandError:
1230 pass
Clark Boylanb640e052014-04-03 16:41:46 -07001231 return False
1232
1233 def job_has_changes(self, *args):
1234 job = args[0]
1235 commits = args[1:]
1236 if isinstance(job, FakeBuild):
1237 parameters = job.parameters
1238 else:
1239 parameters = json.loads(job.arguments)
1240 project = parameters['ZUUL_PROJECT']
1241 path = os.path.join(self.git_root, project)
1242 repo = git.Repo(path)
1243 ref = parameters['ZUUL_REF']
1244 sha = parameters['ZUUL_COMMIT']
1245 repo_messages = [c.message.strip() for c in repo.iter_commits(ref)]
1246 repo_shas = [c.hexsha for c in repo.iter_commits(ref)]
1247 commit_messages = ['%s-1' % commit.subject for commit in commits]
1248 self.log.debug("Checking if job %s has changes; commit_messages %s;"
1249 " repo_messages %s; sha %s" % (job, commit_messages,
1250 repo_messages, sha))
1251 for msg in commit_messages:
1252 if msg not in repo_messages:
1253 self.log.debug(" messages do not match")
1254 return False
1255 if repo_shas[0] != sha:
1256 self.log.debug(" sha does not match")
1257 return False
1258 self.log.debug(" OK")
1259 return True
1260
James E. Blairb8c16472015-05-05 14:55:26 -07001261 def orderedRelease(self):
1262 # Run one build at a time to ensure non-race order:
1263 while len(self.builds):
1264 self.release(self.builds[0])
1265 self.waitUntilSettled()
1266
Clark Boylanb640e052014-04-03 16:41:46 -07001267 def release(self, job):
1268 if isinstance(job, FakeBuild):
1269 job.release()
1270 else:
1271 job.waiting = False
1272 self.log.debug("Queued job %s released" % job.unique)
1273 self.gearman_server.wakeConnections()
1274
1275 def getParameter(self, job, name):
1276 if isinstance(job, FakeBuild):
1277 return job.parameters[name]
1278 else:
1279 parameters = json.loads(job.arguments)
1280 return parameters[name]
1281
1282 def resetGearmanServer(self):
1283 self.worker.setFunctions([])
1284 while True:
1285 done = True
1286 for connection in self.gearman_server.active_connections:
1287 if (connection.functions and
1288 connection.client_id not in ['Zuul RPC Listener',
1289 'Zuul Merger']):
1290 done = False
1291 if done:
1292 break
1293 time.sleep(0)
1294 self.gearman_server.functions = set()
1295 self.rpc.register()
Clark Boylanb640e052014-04-03 16:41:46 -07001296
1297 def haveAllBuildsReported(self):
1298 # See if Zuul is waiting on a meta job to complete
1299 if self.launcher.meta_jobs:
1300 return False
1301 # Find out if every build that the worker has completed has been
1302 # reported back to Zuul. If it hasn't then that means a Gearman
1303 # event is still in transit and the system is not stable.
James E. Blairf5dbd002015-12-23 15:26:17 -08001304 for job in self.ansible_server.job_history:
1305 zbuild = self.launcher.builds.get(job.unique)
Clark Boylanb640e052014-04-03 16:41:46 -07001306 if not zbuild:
1307 # It has already been reported
1308 continue
1309 # It hasn't been reported yet.
1310 return False
1311 # Make sure that none of the worker connections are in GRAB_WAIT
James E. Blairf5dbd002015-12-23 15:26:17 -08001312 for connection in self.ansible_server.worker.active_connections:
Clark Boylanb640e052014-04-03 16:41:46 -07001313 if connection.state == 'GRAB_WAIT':
1314 return False
1315 return True
1316
1317 def areAllBuildsWaiting(self):
Clark Boylanb640e052014-04-03 16:41:46 -07001318 builds = self.launcher.builds.values()
1319 for build in builds:
1320 client_job = None
1321 for conn in self.launcher.gearman.active_connections:
1322 for j in conn.related_jobs.values():
1323 if j.unique == build.uuid:
1324 client_job = j
1325 break
1326 if not client_job:
1327 self.log.debug("%s is not known to the gearman client" %
1328 build)
James E. Blairf15139b2015-04-02 16:37:15 -07001329 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001330 if not client_job.handle:
1331 self.log.debug("%s has no handle" % client_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001332 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001333 server_job = self.gearman_server.jobs.get(client_job.handle)
1334 if not server_job:
1335 self.log.debug("%s is not known to the gearman server" %
1336 client_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001337 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001338 if not hasattr(server_job, 'waiting'):
1339 self.log.debug("%s is being enqueued" % server_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001340 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001341 if server_job.waiting:
1342 continue
James E. Blairbbda4702016-03-09 15:19:56 -08001343 if build.number is None:
1344 self.log.debug("%s has not reported start" % build)
1345 return False
1346 if False: # worker_job.build.isWaiting():
1347 # TODOv3: when we grow the ability to have fake
1348 # ansible jobs wait, check for that here.
1349 continue
Clark Boylanb640e052014-04-03 16:41:46 -07001350 else:
James E. Blairbbda4702016-03-09 15:19:56 -08001351 self.log.debug("%s is running" % build)
James E. Blairf15139b2015-04-02 16:37:15 -07001352 return False
1353 return True
Clark Boylanb640e052014-04-03 16:41:46 -07001354
Jan Hruban6b71aff2015-10-22 16:58:08 +02001355 def eventQueuesEmpty(self):
1356 for queue in self.event_queues:
1357 yield queue.empty()
1358
1359 def eventQueuesJoin(self):
1360 for queue in self.event_queues:
1361 queue.join()
1362
Clark Boylanb640e052014-04-03 16:41:46 -07001363 def waitUntilSettled(self):
1364 self.log.debug("Waiting until settled...")
1365 start = time.time()
1366 while True:
1367 if time.time() - start > 10:
James E. Blair622c9682016-06-09 08:14:53 -07001368 self.log.debug("Queue status:")
1369 for queue in self.event_queues:
1370 self.log.debug(" %s: %s" % (queue, queue.empty()))
1371 self.log.debug("All builds waiting: %s" %
1372 (self.areAllBuildsWaiting(),))
Clark Boylanb640e052014-04-03 16:41:46 -07001373 raise Exception("Timeout waiting for Zuul to settle")
1374 # Make sure no new events show up while we're checking
Clark Boylanb640e052014-04-03 16:41:46 -07001375 # have all build states propogated to zuul?
1376 if self.haveAllBuildsReported():
1377 # Join ensures that the queue is empty _and_ events have been
1378 # processed
Jan Hruban6b71aff2015-10-22 16:58:08 +02001379 self.eventQueuesJoin()
Clark Boylanb640e052014-04-03 16:41:46 -07001380 self.sched.run_handler_lock.acquire()
James E. Blair14abdf42015-12-09 16:11:53 -08001381 if (not self.merge_client.jobs and
Jan Hruban6b71aff2015-10-22 16:58:08 +02001382 all(self.eventQueuesEmpty()) and
Clark Boylanb640e052014-04-03 16:41:46 -07001383 self.haveAllBuildsReported() and
1384 self.areAllBuildsWaiting()):
1385 self.sched.run_handler_lock.release()
Clark Boylanb640e052014-04-03 16:41:46 -07001386 self.log.debug("...settled.")
1387 return
1388 self.sched.run_handler_lock.release()
Clark Boylanb640e052014-04-03 16:41:46 -07001389 self.sched.wake_event.wait(0.1)
1390
1391 def countJobResults(self, jobs, result):
1392 jobs = filter(lambda x: x.result == result, jobs)
1393 return len(jobs)
1394
James E. Blair96c6bf82016-01-15 16:20:40 -08001395 def getJobFromHistory(self, name, project=None):
James E. Blairf5dbd002015-12-23 15:26:17 -08001396 history = self.ansible_server.job_history
Clark Boylanb640e052014-04-03 16:41:46 -07001397 for job in history:
James E. Blairf5dbd002015-12-23 15:26:17 -08001398 params = json.loads(job.arguments)
James E. Blair96c6bf82016-01-15 16:20:40 -08001399 if (params['job'] == name and
1400 (project is None or params['ZUUL_PROJECT'] == project)):
James E. Blairf5dbd002015-12-23 15:26:17 -08001401 result = json.loads(job.data[-1])
James E. Blairf5dbd002015-12-23 15:26:17 -08001402 ret = BuildHistory(job=job,
1403 name=params['job'],
1404 result=result['result'])
1405 return ret
Clark Boylanb640e052014-04-03 16:41:46 -07001406 raise Exception("Unable to find job %s in history" % name)
1407
1408 def assertEmptyQueues(self):
1409 # Make sure there are no orphaned jobs
James E. Blair59fdbac2015-12-07 17:08:06 -08001410 for tenant in self.sched.abide.tenants.values():
1411 for pipeline in tenant.layout.pipelines.values():
1412 for queue in pipeline.queues:
1413 if len(queue.queue) != 0:
Joshua Hesketh0aa7e8b2016-07-14 00:12:25 +10001414 print('pipeline %s queue %s contents %s' % (
1415 pipeline.name, queue.name, queue.queue))
James E. Blair59fdbac2015-12-07 17:08:06 -08001416 self.assertEqual(len(queue.queue), 0,
1417 "Pipelines queues should be empty")
Clark Boylanb640e052014-04-03 16:41:46 -07001418
1419 def assertReportedStat(self, key, value=None, kind=None):
1420 start = time.time()
1421 while time.time() < (start + 5):
1422 for stat in self.statsd.stats:
1423 pprint.pprint(self.statsd.stats)
1424 k, v = stat.split(':')
1425 if key == k:
1426 if value is None and kind is None:
1427 return
1428 elif value:
1429 if value == v:
1430 return
1431 elif kind:
1432 if v.endswith('|' + kind):
1433 return
1434 time.sleep(0.1)
1435
1436 pprint.pprint(self.statsd.stats)
1437 raise Exception("Key %s not found in reported stats" % key)
James E. Blair59fdbac2015-12-07 17:08:06 -08001438
1439 def getPipeline(self, name):
James E. Blairf84026c2015-12-08 16:11:46 -08001440 return self.sched.abide.tenants.values()[0].layout.pipelines.get(name)
1441
1442 def updateConfigLayout(self, path):
1443 root = os.path.join(self.test_root, "config")
1444 os.makedirs(root)
1445 f = tempfile.NamedTemporaryFile(dir=root, delete=False)
1446 f.write("""
1447tenants:
1448 - name: openstack
1449 include:
1450 - %s
1451 """ % os.path.abspath(path))
1452 f.close()
1453 self.config.set('zuul', 'tenant_config', f.name)
James E. Blair14abdf42015-12-09 16:11:53 -08001454
1455 def addCommitToRepo(self, project, message, files, branch='master'):
1456 path = os.path.join(self.upstream_root, project)
1457 repo = git.Repo(path)
1458 repo.head.reference = branch
1459 zuul.merger.merger.reset_repo_to_head(repo)
1460 for fn, content in files.items():
1461 fn = os.path.join(path, fn)
1462 with open(fn, 'w') as f:
1463 f.write(content)
1464 repo.index.add([fn])
1465 commit = repo.index.commit(message)
1466 repo.heads[branch].commit = commit
1467 repo.head.reference = branch
1468 repo.git.clean('-x', '-f', '-d')
1469 repo.heads[branch].checkout()